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 9
import {Range} from 'vs/editor/common/core/range';
import {ILineTokens, IModel, IPosition, IRange, IRichEditBracket} from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
10
import {IModeTransition, 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';
E
Erich Gamma 已提交
14

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

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

A
Alex Dima 已提交
23
	start: IPosition;
E
Erich Gamma 已提交
24

A
Alex Dima 已提交
25
	end: IPosition;
E
Erich Gamma 已提交
26

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

	parent: Node;
}

export class NodeList extends Node {

	children: Node[];

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

A
Alex Dima 已提交
49
	get end(): IPosition {
E
Erich Gamma 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
		return this.hasChildren
			? this.children[this.children.length - 1].end
			: this.parent.end;
	}

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

	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 已提交
84
	get start(): IPosition {
E
Erich Gamma 已提交
85 86 87
		return this.open.start;
	}

A
Alex Dima 已提交
88
	get end(): IPosition {
E
Erich Gamma 已提交
89 90 91 92 93 94 95 96 97 98 99
		return this.close.end;
	}

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

interface Token {
A
Alex Dima 已提交
100
	range: IRange;
A
Alex Dima 已提交
101
	bracket: TokenTreeBracket;
E
Erich Gamma 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114
	type: string;
	__debugContent?: string;
}

function newNode(token: Token): Node {
	var node = new Node();
	node.start = Position.startPosition(token.range);
	node.end = Position.endPosition(token.range);
	return node;
}

class TokenScanner {

A
Alex Dima 已提交
115
	private _model: IModel;
E
Erich Gamma 已提交
116 117 118
	private _versionId: number;
	private _currentLineNumber: number;
	private _currentTokenIndex: number;
119
	private _currentTokenStart: number;
A
Alex Dima 已提交
120 121
	private _currentLineTokens: ILineTokens;
	private _currentLineModeTransitions: IModeTransition[];
122 123
	private _currentModeIndex: number;
	private _nextModeStart: number;
A
Alex Dima 已提交
124
	private _currentModeBrackets: IRichEditBrackets;
125
	private _currentLineText: string;
E
Erich Gamma 已提交
126

A
Alex Dima 已提交
127
	constructor(model: IModel) {
E
Erich Gamma 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
		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);
145
			this._currentLineText = this._model.getLineContent(this._currentLineNumber);
146
			this._currentLineModeTransitions = this._model._getLineModeTransitions(this._currentLineNumber);
E
Erich Gamma 已提交
147
			this._currentTokenIndex = 0;
148 149 150
			this._currentTokenStart = 0;
			this._currentModeIndex = -1;
			this._nextModeStart = 0;
E
Erich Gamma 已提交
151 152 153 154 155 156 157
		}
		if (this._currentTokenIndex >= this._currentLineTokens.getTokenCount()) {
			// last token of line visited
			this._currentLineNumber += 1;
			this._currentLineTokens = null;
			return this.next();
		}
158 159 160 161 162

		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);
163
			this._currentModeBrackets = (mode ? LanguageConfigurationRegistry.getBracketsSupport(mode.mode) : null);
164 165
		}

166
		let tokenType = this._currentLineTokens.getTokenType(this._currentTokenIndex);
167
		let tokenEndIndex = this._currentLineTokens.getTokenEndIndex(this._currentTokenIndex, this._currentLineText.length);
A
Alex Dima 已提交
168
		let tmpTokenEndIndex = tokenEndIndex;
169 170 171 172 173 174 175 176

		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 已提交
177
			tmpTokenEndIndex = nextBracket.startColumn - 1;
178 179 180
			nextBracket = null;
		}

A
Alex Dima 已提交
181
		let bracketData: IRichEditBracket = null;
182 183 184 185 186 187 188 189 190 191
		let bracketIsOpen: boolean = false;
		if (nextBracket) {
			let bracketText = this._currentLineText.substring(nextBracket.startColumn - 1, nextBracket.endColumn - 1);
			bracketData = this._currentModeBrackets.textIsBracket[bracketText];
			bracketIsOpen = this._currentModeBrackets.textIsOpenBracket[bracketText];
		}

		if (!bracketData) {
			let token: Token = {
				type: tokenType,
A
Alex Dima 已提交
192
				bracket: TokenTreeBracket.None,
193 194 195 196
				range: {
					startLineNumber: this._currentLineNumber,
					startColumn: 1 + this._currentTokenStart,
					endLineNumber: this._currentLineNumber,
A
Alex Dima 已提交
197
					endColumn: 1 + tmpTokenEndIndex
198 199
				}
			};
A
Alex Dima 已提交
200 201 202 203 204 205 206 207 208
			// 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;
				this._currentTokenStart = (this._currentTokenIndex < this._currentLineTokens.getTokenCount() ? this._currentLineTokens.getTokenStartIndex(this._currentTokenIndex) : 0);
			}
209 210 211 212 213 214
			return token;
		}

		let type = `${bracketData.modeId};${bracketData.open};${bracketData.close}`;
		let token: Token = {
			type: type,
A
Alex Dima 已提交
215
			bracket: bracketIsOpen ? TokenTreeBracket.Open : TokenTreeBracket.Close,
E
Erich Gamma 已提交
216 217
			range: {
				startLineNumber: this._currentLineNumber,
218
				startColumn: 1 + this._currentTokenStart,
E
Erich Gamma 已提交
219
				endLineNumber: this._currentLineNumber,
220
				endColumn: nextBracket.endColumn
E
Erich Gamma 已提交
221 222
			}
		};
223 224 225 226 227 228 229 230 231
		// 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;
			this._currentTokenStart = (this._currentTokenIndex < this._currentLineTokens.getTokenCount() ? this._currentLineTokens.getTokenStartIndex(this._currentTokenIndex) : 0);
		}
E
Erich Gamma 已提交
232 233 234 235 236 237 238 239 240 241
		return token;
	}
}

class TokenTreeBuilder {

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

A
Alex Dima 已提交
242
	constructor(model: IModel) {
E
Erich Gamma 已提交
243 244 245 246 247 248 249 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
		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 已提交
305
		if (!this._accept(token => token.bracket === TokenTreeBracket.None)) {
E
Erich Gamma 已提交
306 307 308 309 310 311 312 313 314 315 316 317
			return null;
		}
		return newNode(this._currentToken);
	}

	private _block(): Node {

		var bracketType: string,
			accepted: boolean;

		accepted = this._accept(token => {
			bracketType = token.type;
A
Alex Dima 已提交
318
			return token.bracket === TokenTreeBracket.Open;
E
Erich Gamma 已提交
319 320 321 322 323 324 325 326 327 328 329
		});
		if (!accepted) {
			return null;
		}

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

A
Alex Dima 已提交
330
		if (!this._accept(token => token.bracket === TokenTreeBracket.Close && token.type === bracketType)) {
E
Erich Gamma 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
			// 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 已提交
356
export function build(model: IModel): Node {
E
Erich Gamma 已提交
357 358 359 360
	var node = new TokenTreeBuilder(model).build();
	return node;
}

A
Alex Dima 已提交
361
export function find(node: Node, position: IPosition): Node {
E
Erich Gamma 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

	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;
}