tokenTree.ts 10.3 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 17 18 19 20 21
export enum TokenTreeBracket {
	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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
		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 已提交
85
	get start(): Position {
E
Erich Gamma 已提交
86 87 88
		return this.open.start;
	}

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

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

interface Token {
A
Alex Dima 已提交
101
	range: Range;
A
Alex Dima 已提交
102
	bracket: TokenTreeBracket;
E
Erich Gamma 已提交
103 104 105 106 107 108
	type: string;
	__debugContent?: string;
}

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

class TokenScanner {

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

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

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

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

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

A
Alex Dima 已提交
182
		let bracketData: IRichEditBracket = null;
183 184 185 186 187 188 189 190 191 192
		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 已提交
193
				bracket: TokenTreeBracket.None,
A
Alex Dima 已提交
194 195 196 197 198 199
				range: new Range(
					this._currentLineNumber,
					1 + this._currentTokenStart,
					this._currentLineNumber,
					1 + tmpTokenEndIndex
				)
200
			};
A
Alex Dima 已提交
201 202 203 204 205 206 207 208 209
			// 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);
			}
210 211 212 213 214 215
			return token;
		}

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

class TokenTreeBuilder {

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

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

	private _block(): Node {

		var bracketType: string,
			accepted: boolean;

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

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

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

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

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