tokenTree.ts 10.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import {Position} from 'vs/editor/common/core/position';
A
Alex Dima 已提交
8
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
9
import {ILineTokens, IModel, IPosition, IRichEditBracket} from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
10
import {IRichEditBrackets} from 'vs/editor/common/modes';
11
import {ignoreBracketsInToken} from 'vs/editor/common/modes/supports';
A
Alex Dima 已提交
12
import {BracketsUtils} from 'vs/editor/common/modes/supports/richEditBrackets';
13
import {LanguageConfigurationRegistry} from 'vs/editor/common/modes/languageConfigurationRegistry';
A
Alex Dima 已提交
14
import {ModeTransition} from 'vs/editor/common/core/modeTransition';
E
Erich Gamma 已提交
15

A
Alex Dima 已提交
16
export const enum TokenTreeBracket {
A
Alex Dima 已提交
17 18 19 20 21
	None = 0,
	Open = 1,
	Close = -1
}

E
Erich Gamma 已提交
22 23
export class Node {

A
Alex Dima 已提交
24
	start: Position;
E
Erich Gamma 已提交
25

A
Alex Dima 已提交
26
	end: Position;
E
Erich Gamma 已提交
27

A
Alex Dima 已提交
28 29 30 31 32 33 34
	get range(): Range {
		return new Range(
			this.start.lineNumber,
			this.start.column,
			this.end.lineNumber,
			this.end.column
		);
E
Erich Gamma 已提交
35 36 37 38 39 40 41 42 43
	}

	parent: Node;
}

export class NodeList extends Node {

	children: Node[];

A
Alex Dima 已提交
44
	get start(): Position {
E
Erich Gamma 已提交
45 46 47 48 49
		return this.hasChildren
			? this.children[0].start
			: this.parent.start;
	}

A
Alex Dima 已提交
50
	get end(): Position {
E
Erich Gamma 已提交
51 52 53 54 55 56 57 58 59
		return this.hasChildren
			? this.children[this.children.length - 1].end
			: this.parent.end;
	}

	get hasChildren() {
		return this.children && this.children.length > 0;
	}

60 61 62 63
	get isEmpty() {
		return !this.hasChildren && !this.parent;
	}

E
Erich Gamma 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	public append(node: Node): boolean {
		if (!node) {
			return false;
		}
		node.parent = this;
		if (!this.children) {
			this.children = [];
		}
		if (node instanceof NodeList) {
			if (node.children) {
				this.children.push.apply(this.children, node.children);
			}
		} else {
			this.children.push(node);
		}
		return true;
	}
}

export class Block extends Node {

	open: Node;
	close: Node;
	elements: NodeList;

A
Alex Dima 已提交
89
	get start(): Position {
E
Erich Gamma 已提交
90 91 92
		return this.open.start;
	}

A
Alex Dima 已提交
93
	get end(): Position {
E
Erich Gamma 已提交
94 95 96 97 98 99 100 101 102 103 104
		return this.close.end;
	}

	constructor() {
		super();
		this.elements = new NodeList();
		this.elements.parent = this;
	}
}

interface Token {
A
Alex Dima 已提交
105
	range: Range;
A
Alex Dima 已提交
106
	bracket: TokenTreeBracket;
E
Erich Gamma 已提交
107 108 109 110 111 112
	type: string;
	__debugContent?: string;
}

function newNode(token: Token): Node {
	var node = new Node();
A
Alex Dima 已提交
113 114
	node.start = token.range.getStartPosition();
	node.end = token.range.getEndPosition();
E
Erich Gamma 已提交
115 116 117 118 119
	return node;
}

class TokenScanner {

A
Alex Dima 已提交
120
	private _model: IModel;
E
Erich Gamma 已提交
121 122 123
	private _versionId: number;
	private _currentLineNumber: number;
	private _currentTokenIndex: number;
124
	private _currentTokenStart: number;
A
Alex Dima 已提交
125
	private _currentLineTokens: ILineTokens;
A
Alex Dima 已提交
126
	private _currentLineModeTransitions: ModeTransition[];
127 128
	private _currentModeIndex: number;
	private _nextModeStart: number;
A
Alex Dima 已提交
129
	private _currentModeBrackets: IRichEditBrackets;
130
	private _currentLineText: string;
E
Erich Gamma 已提交
131

A
Alex Dima 已提交
132
	constructor(model: IModel) {
E
Erich Gamma 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
		this._model = model;
		this._versionId = model.getVersionId();
		this._currentLineNumber = 1;
	}

	next(): Token {
		if (this._versionId !== this._model.getVersionId()) {
			// model has been modified
			return null;
		}
		if (this._currentLineNumber >= this._model.getLineCount() + 1) {
			// all line visisted
			return null;
		}
		if (!this._currentLineTokens) {
			// no tokens for this line
			this._currentLineTokens = this._model.getLineTokens(this._currentLineNumber);
150
			this._currentLineText = this._model.getLineContent(this._currentLineNumber);
151
			this._currentLineModeTransitions = this._model._getLineModeTransitions(this._currentLineNumber);
E
Erich Gamma 已提交
152
			this._currentTokenIndex = 0;
153 154 155
			this._currentTokenStart = 0;
			this._currentModeIndex = -1;
			this._nextModeStart = 0;
E
Erich Gamma 已提交
156 157 158 159 160 161 162
		}
		if (this._currentTokenIndex >= this._currentLineTokens.getTokenCount()) {
			// last token of line visited
			this._currentLineNumber += 1;
			this._currentLineTokens = null;
			return this.next();
		}
163 164 165 166 167

		if (this._currentTokenStart >= this._nextModeStart) {
			this._currentModeIndex++;
			this._nextModeStart = (this._currentModeIndex + 1 < this._currentLineModeTransitions.length ? this._currentLineModeTransitions[this._currentModeIndex + 1].startIndex : this._currentLineText.length + 1);
			let mode = (this._currentModeIndex < this._currentLineModeTransitions.length ? this._currentLineModeTransitions[this._currentModeIndex] : null);
A
Alex Dima 已提交
168
			this._currentModeBrackets = (mode ? LanguageConfigurationRegistry.getBracketsSupport(mode.modeId) : null);
169 170
		}

171
		let tokenType = this._currentLineTokens.getTokenType(this._currentTokenIndex);
A
Alex Dima 已提交
172
		let tokenEndIndex = this._currentLineTokens.getTokenEndOffset(this._currentTokenIndex, this._currentLineText.length);
A
Alex Dima 已提交
173
		let tmpTokenEndIndex = tokenEndIndex;
174 175 176 177 178 179 180 181

		let nextBracket: Range = null;
		if (this._currentModeBrackets && !ignoreBracketsInToken(tokenType)) {
			nextBracket = BracketsUtils.findNextBracketInToken(this._currentModeBrackets.forwardRegex, this._currentLineNumber, this._currentLineText, this._currentTokenStart, tokenEndIndex);
		}

		if (nextBracket && this._currentTokenStart < nextBracket.startColumn - 1) {
			// found a bracket, but it is not at the beginning of the token
A
Alex Dima 已提交
182
			tmpTokenEndIndex = nextBracket.startColumn - 1;
183 184 185
			nextBracket = null;
		}

A
Alex Dima 已提交
186
		let bracketData: IRichEditBracket = null;
187 188 189
		let bracketIsOpen: boolean = false;
		if (nextBracket) {
			let bracketText = this._currentLineText.substring(nextBracket.startColumn - 1, nextBracket.endColumn - 1);
190 191
			bracketText = bracketText.toLowerCase();

192 193 194 195 196 197 198
			bracketData = this._currentModeBrackets.textIsBracket[bracketText];
			bracketIsOpen = this._currentModeBrackets.textIsOpenBracket[bracketText];
		}

		if (!bracketData) {
			let token: Token = {
				type: tokenType,
A
Alex Dima 已提交
199
				bracket: TokenTreeBracket.None,
A
Alex Dima 已提交
200 201 202 203 204 205
				range: new Range(
					this._currentLineNumber,
					1 + this._currentTokenStart,
					this._currentLineNumber,
					1 + tmpTokenEndIndex
				)
206
			};
A
Alex Dima 已提交
207 208 209 210 211 212 213
			// console.log('TOKEN: <<' + this._currentLineText.substring(this._currentTokenStart, tmpTokenEndIndex) + '>>');

			if (tmpTokenEndIndex < tokenEndIndex) {
				// there is a bracket somewhere in this token...
				this._currentTokenStart = tmpTokenEndIndex;
			} else {
				this._currentTokenIndex += 1;
A
Alex Dima 已提交
214
				this._currentTokenStart = (this._currentTokenIndex < this._currentLineTokens.getTokenCount() ? this._currentLineTokens.getTokenStartOffset(this._currentTokenIndex) : 0);
A
Alex Dima 已提交
215
			}
216 217 218 219 220 221
			return token;
		}

		let type = `${bracketData.modeId};${bracketData.open};${bracketData.close}`;
		let token: Token = {
			type: type,
A
Alex Dima 已提交
222
			bracket: bracketIsOpen ? TokenTreeBracket.Open : TokenTreeBracket.Close,
A
Alex Dima 已提交
223 224 225 226 227 228
			range: new Range(
				this._currentLineNumber,
				1 + this._currentTokenStart,
				this._currentLineNumber,
				nextBracket.endColumn
			)
E
Erich Gamma 已提交
229
		};
230 231 232 233 234 235 236
		// console.log('BRACKET: <<' + this._currentLineText.substring(this._currentTokenStart, nextBracket.endColumn - 1) + '>>');

		if (nextBracket.endColumn - 1 < tokenEndIndex) {
			// found a bracket, but it is not at the end of the token
			this._currentTokenStart = nextBracket.endColumn - 1;
		} else {
			this._currentTokenIndex += 1;
A
Alex Dima 已提交
237
			this._currentTokenStart = (this._currentTokenIndex < this._currentLineTokens.getTokenCount() ? this._currentLineTokens.getTokenStartOffset(this._currentTokenIndex) : 0);
238
		}
E
Erich Gamma 已提交
239 240 241 242 243 244 245 246 247 248
		return token;
	}
}

class TokenTreeBuilder {

	private _scanner: TokenScanner;
	private _stack: Token[] = [];
	private _currentToken: Token;

A
Alex Dima 已提交
249
	constructor(model: IModel) {
E
Erich Gamma 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
		this._scanner = new TokenScanner(model);
	}

	public build(): Node {
		var node = new NodeList();
		while (node.append(this._line() || this._any())) {
			// accept all
		}
		return node;
	}

	private _accept(condt: (info: Token) => boolean): boolean {
		var token = this._stack.pop() || this._scanner.next();
		if (!token) {
			return false;
		}
		var accepted = condt(token);
		if (!accepted) {
			this._stack.push(token);
			this._currentToken = null;
		} else {
			this._currentToken = token;
			//			console.log('accepted: ' + token.__debugContent);
		}
		return accepted;
	}

	private _peek(condt: (info: Token) => boolean): boolean {
		var ret = false;
		this._accept(info => {
			ret = condt(info);
			return false;
		});
		return ret;
	}

	private _line(): Node {
		var node = new NodeList(),
			lineNumber: number;

		// capture current linenumber
		this._peek(info => {
			lineNumber = info.range.startLineNumber;
			return false;
		});

		while (this._peek(info => info.range.startLineNumber === lineNumber)
			&& node.append(this._token() || this._block())) {

			// all children that started on this line
		}

		if (!node.children || node.children.length === 0) {
			return null;
		} else if (node.children.length === 1) {
			return node.children[0];
		} else {
			return node;
		}
	}

	private _token(): Node {
A
Alex Dima 已提交
312
		if (!this._accept(token => token.bracket === TokenTreeBracket.None)) {
E
Erich Gamma 已提交
313 314 315 316 317 318 319 320 321 322 323 324
			return null;
		}
		return newNode(this._currentToken);
	}

	private _block(): Node {

		var bracketType: string,
			accepted: boolean;

		accepted = this._accept(token => {
			bracketType = token.type;
A
Alex Dima 已提交
325
			return token.bracket === TokenTreeBracket.Open;
E
Erich Gamma 已提交
326 327 328 329 330 331 332 333 334 335 336
		});
		if (!accepted) {
			return null;
		}

		var bracket = new Block();
		bracket.open = newNode(this._currentToken);
		while (bracket.elements.append(this._line())) {
			// inside brackets
		}

A
Alex Dima 已提交
337
		if (!this._accept(token => token.bracket === TokenTreeBracket.Close && token.type === bracketType)) {
E
Erich Gamma 已提交
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
			// missing closing bracket -> return just a node list
			var nodelist = new NodeList();
			nodelist.append(bracket.open);
			nodelist.append(bracket.elements);
			return nodelist;
		}

		bracket.close = newNode(this._currentToken);
		return bracket;
	}

	private _any(): Node {
		if (!this._accept(_ => true)) {
			return null;
		}
		return newNode(this._currentToken);
	}
}

/**
 * Parses this grammar:
 *	grammer = { line }
 *	line = { block | "token" }
 *	block = "open_bracket" { line } "close_bracket"
 */
A
Alex Dima 已提交
363
export function build(model: IModel): Node {
E
Erich Gamma 已提交
364 365 366 367
	var node = new TokenTreeBuilder(model).build();
	return node;
}

A
Alex Dima 已提交
368
export function find(node: Node, position: IPosition): Node {
369 370 371
	if (node instanceof NodeList && node.isEmpty) {
		return null;
	}
E
Erich Gamma 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

	if (!Range.containsPosition(node.range, position)) {
		return null;
	}

	var result: Node;

	if (node instanceof NodeList) {
		for (var i = 0, len = node.children.length; i < len && !result; i++) {
			result = find(node.children[i], position);
		}

	} else if (node instanceof Block) {
		result = find(node.open, position) || find(node.elements, position) || find(node.close, position);
	}

	return result || node;
}