monarchLexer.ts 14.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

/**
 * Create a syntax highighter with a fully declarative JSON style lexer description
 * using regular expressions.
 */

import {AbstractState} from 'vs/editor/common/modes/abstractState';
import {LineStream} from 'vs/editor/common/modes/lineStream';
import ModesRegistry = require('vs/editor/common/modes/modesRegistry');
import Supports = require('vs/editor/common/modes/supports');
import MonarchCommonTypes = require('vs/editor/common/modes/monarch/monarchCommon');
import Modes = require('vs/editor/common/modes');
import {Registry} from 'vs/platform/platform';
import {IModeService} from 'vs/editor/common/services/modeService';

var modesRegistry = <ModesRegistry.IEditorModesRegistry>Registry.as(ModesRegistry.Extensions.EditorModes);

/**
 * The MonarchLexer class implements a monaco lexer that highlights source code.
 * It takes a compiled lexer to guide the tokenizer and maintains a stack of
 * lexer states.
 */
export class MonarchLexer extends AbstractState {

	static ID = 0;

	private id: number;
	private lexer: MonarchCommonTypes.ILexer;
	private stack: string[];

	public embeddedMode: string;
	public embeddedEntered: boolean;

	private groupActions: MonarchCommonTypes.IAction[];
	private groupMatches: string[];
	private groupMatched: string[];
	private groupRule: MonarchCommonTypes.IRule;

	constructor(mode: Modes.IMode, lexer: MonarchCommonTypes.ILexer, stack?: string[], embeddedMode?: string) {
		super(mode);
		this.id = MonarchLexer.ID++; // for debugging, assigns unique id to each instance

		this.lexer = lexer; // (compiled) lexer description
		this.stack = (stack ? stack : [lexer.start]); // stack of states
		this.embeddedMode = (embeddedMode ? embeddedMode : null); // are we scanning an embedded section?

		// did we encounter an embedded start on this line?
		// no need for cloning or equality since it is used only within a line
		this.embeddedEntered = false;

		// regular expression group matching
		// these never need cloning or equality since they are only used within a line match
		this.groupActions = null;
		this.groupMatches = null;
		this.groupMatched = null;
		this.groupRule = null;
	}

	public makeClone(): MonarchLexer {
		return new MonarchLexer(this.getMode(), this.lexer, this.stack.slice(0), this.embeddedMode);
	}

	public equals(other: Modes.IState): boolean {
		if (!super.equals(other)) {
			return false;
		}
A
tslint  
Alex Dima 已提交
72 73 74
		if (!(other instanceof MonarchLexer)) {
			return false;
		}
E
Erich Gamma 已提交
75 76 77 78 79 80 81 82
		var otherm: MonarchLexer = <MonarchLexer>other;
		if ((this.stack.length !== otherm.stack.length) || (this.lexer.name !== otherm.lexer.name) ||
			(this.embeddedMode !== otherm.embeddedMode)) {
			return false;
		}
		var idx: string;
		for (idx in this.stack) {
			if (this.stack.hasOwnProperty(idx)) {
A
tslint  
Alex Dima 已提交
83 84 85
				if (this.stack[idx] !== otherm.stack[idx]) {
					return false;
				}
E
Erich Gamma 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
			}
		}
		return true;
	}

	/**
	 * The main tokenizer: this function gets called by monaco to tokenize lines
	 * Note: we don't want to raise exceptions here and always keep going..
	 *
	 * TODO: there are many optimizations possible here for the common cases
	 * but for now I concentrated on functionality and correctness.
	 */
	public tokenize(stream: Modes.IStream, noConsumeIsOk?: boolean): Modes.ITokenizationResult {
		var stackLen0 = this.stack.length;  // these are saved to check progress
		var groupLen0 = 0;
		var state: string = this.stack[0];  // the current state
		this.embeddedEntered = false;

		var matches: string[] = null;
		var matched: string = null;
		var action: MonarchCommonTypes.IAction = null;
		var next: string = null;
		var rule: MonarchCommonTypes.IRule = null;

		// check if we need to process group matches first
		if (this.groupActions) {
			groupLen0 = this.groupActions.length;
			matches = this.groupMatches;
			matched = this.groupMatched.shift();
			action = this.groupActions.shift();
			rule = this.groupRule;

			// cleanup if necessary
			if (this.groupActions.length === 0) {
				this.groupActions = null;
				this.groupMatches = null;
				this.groupMatched = null;
				this.groupRule = null;
			}
		}
			// otherwise we match on the token stream
		else {
			// nothing to do
			if (stream.eos()) {
				return { type: '' };
			}

			// get the entire line
			var line = stream.advanceToEOS();
			stream.goBack(line.length);

			// get the rules for this state
			var rules = this.lexer.tokenizer[state];
A
tslint  
Alex Dima 已提交
139 140 141
			if (!rules) {
				rules = MonarchCommonTypes.findRules(this.lexer, state); // do parent matching
			}
E
Erich Gamma 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

			if (!rules) {
				MonarchCommonTypes.throwError(this.lexer, 'tokenizer state is not defined: ' + state);
			}
			else {
				// try each rule until we match
				rule = null;
				var pos = stream.pos();
				var idx: string;
				for (idx in rules) {
					if (rules.hasOwnProperty(idx)) {
						rule = rules[idx];
						if (pos === 0 || !rule.matchOnlyAtLineStart) {
							matches = line.match(rule.regex);
							if (matches) {
								matched = matches[0];
								action = rule.action;
								break;
							}
						}
					}
				}
			}
		}

		// We matched 'rule' with 'matches' and 'action'
		if (!matches) {
			matches = [''];
			matched = '';
		}
		if (!action) {
			// bad: we didn't match anything, and there is no action to take
			// we need to advance the stream or we get progress trouble
			if (!stream.eos()) {
				matches = [stream.peek()];
				matched = matches[0];
			}
			action = this.lexer.defaultToken;
		}

		// advance stream
		stream.advance(matched.length);

		// maybe call action function (used for 'cases')
		while (action.test) {
			var callres = action.test(matched, matches, state, stream.eos());
			action = callres;
		}

		// set the result: either a string or an array of actions
		var result = null;
		if (typeof (action) === 'string' || Array.isArray(action)) {
			result = action;
		}
		else if (action.group) {
			result = action.group;
		}
		else if (action.token !== null && action.token !== undefined) {
			result = action.token;

			// do $n replacements?
			if (action.tokenSubst) {
				result = MonarchCommonTypes.substituteMatches(this.lexer, result, matched, matches, state);
			}

			// enter embedded mode?
			if (action.nextEmbedded) {
				if (action.nextEmbedded === '@pop') {
					if (!this.embeddedMode) {
						MonarchCommonTypes.throwError(this.lexer, 'cannot pop embedded mode if not inside one');
					}
					this.embeddedMode = null;
				}
				else if (this.embeddedMode) {
					MonarchCommonTypes.throwError(this.lexer, 'cannot enter embedded mode from within an embedded mode');
				}
				else {
					this.embeddedMode = MonarchCommonTypes.substituteMatches(this.lexer, action.nextEmbedded, matched, matches, state);

					// substitute language alias to known modes to support syntax highlighting
					var embeddedMode = modesRegistry.getModeIdForLanguageName(this.embeddedMode);
					if (this.embeddedMode && embeddedMode) {
						this.embeddedMode = embeddedMode;
					}

					this.embeddedEntered = true;
				}
			}

			// state transformations
			if (action.goBack) { // back up the stream..
				stream.goBack(action.goBack);
			}
			if (action.switchTo && typeof action.switchTo === 'string') {
				var nextState = MonarchCommonTypes.substituteMatches(this.lexer, action.switchTo, matched, matches, state);  // switch state without a push...
A
tslint  
Alex Dima 已提交
237 238 239
				if (nextState[0] === '@') {
					nextState = nextState.substr(1); // peel off starting '@'
				}
E
Erich Gamma 已提交
240 241 242 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
				if (!MonarchCommonTypes.findRules(this.lexer, nextState)) {
					MonarchCommonTypes.throwError(this.lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + rule.name);
				}
				else {
					this.stack[0] = nextState;
				}
				next = null;
			}
			else if (action.transform && typeof action.transform === 'function') {
				this.stack = action.transform(this.stack); // if you need to do really funky stuff...
				next = null;
			}
			else if (action.next) {
				if (action.next === '@push') {
					if (this.stack.length >= this.lexer.maxStack) {
						MonarchCommonTypes.throwError(this.lexer, 'maximum tokenizer stack size reached: [' +
							this.stack[0] + ',' + this.stack[1] + ',...,' +
							this.stack[this.stack.length - 2] + ',' + this.stack[this.stack.length - 1] + ']');
					}
					else {
						this.stack.unshift(state);
					}
				}
				else if (action.next === '@pop') {
					if (this.stack.length <= 1) {
						MonarchCommonTypes.throwError(this.lexer, 'trying to pop an empty stack in rule: ' + rule.name);
					}
					else {
						this.stack.shift();
					}
				}
				else if (action.next === '@popall') {
A
tslint  
Alex Dima 已提交
272 273 274
					if (this.stack.length > 1) {
						this.stack = [this.stack[this.stack.length - 1]];
					}
E
Erich Gamma 已提交
275 276 277
				}
				else {
					var nextState = MonarchCommonTypes.substituteMatches(this.lexer, action.next, matched, matches, state);
A
tslint  
Alex Dima 已提交
278 279 280
					if (nextState[0] === '@') {
						nextState = nextState.substr(1); // peel off starting '@'
					}
E
Erich Gamma 已提交
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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

					if (!MonarchCommonTypes.findRules(this.lexer, nextState)) {
						MonarchCommonTypes.throwError(this.lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + rule.name);
					}
					else {
						this.stack.unshift(nextState);
					}
				}
			}

			if (action.log && typeof (action.log) === 'string') {
				MonarchCommonTypes.log(this.lexer, this.lexer.displayName + ': ' + MonarchCommonTypes.substituteMatches(this.lexer, action.log, matched, matches, state));
			}
		}

		// check result
		if (result === null) {
			MonarchCommonTypes.throwError(this.lexer, 'lexer rule has no well-defined action in rule: ' + rule.name);
			result = this.lexer.defaultToken;
		}

		// is the result a group match?
		if (Array.isArray(result)) {
			if (this.groupActions && this.groupActions.length > 0) {
				MonarchCommonTypes.throwError(this.lexer, 'groups cannot be nested: ' + rule.name);
			}
			if (matches.length !== result.length + 1) {
				MonarchCommonTypes.throwError(this.lexer, 'matched number of groups does not match the number of actions in rule: ' + rule.name);
			}
			var totalLen = 0;
			for (var i = 1; i < matches.length; i++) {
				totalLen += matches[i].length;
			}
			if (totalLen !== matched.length) {
				MonarchCommonTypes.throwError(this.lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + rule.name);
			}
			this.groupMatches = matches;
			this.groupMatched = matches.slice(1);
			this.groupActions = result.slice(0);
			this.groupRule = rule;
			stream.goBack(matched.length);
			return this.tokenize(stream);  // call recursively to initiate first result match
		}
			// regular result
		else {
			// check for '@rematch'
			if (result === '@rematch') {
				stream.goBack(matched.length);
				matched = '';  // better set the next state too..
				matches = null;
				result = '';
			}

			// check progress
			if (matched.length === 0) {
				if (stackLen0 !== this.stack.length || state !== this.stack[0]
					|| (!this.groupActions ? 0 : this.groupActions.length) !== groupLen0) {
					if (!noConsumeIsOk) { // used for nested modes..
						return this.tokenize(stream); // tokenize again in the new state
					}
				}
				else {
					MonarchCommonTypes.throwError(this.lexer, 'no progress in tokenizer in rule: ' + rule.name);
					stream.advanceToEOS(); // must make progress or editor loops
					// result='';
				}
			}

			// return the result (and check for brace matching)
			// todo: for efficiency we could pre-sanitize tokenPostfix and substitutions
			if (result.indexOf('@brackets') === 0) {
				var rest = result.substr('@brackets'.length);
				var bracket = findBracket(this.lexer, matched);
				if (!bracket) {
					MonarchCommonTypes.throwError(this.lexer, '@brackets token returned but no bracket defined as: ' + matched);
					bracket = { token: '', bracketType: Modes.Bracket.None };
				}
				return { type: MonarchCommonTypes.sanitize(bracket.token + rest), bracket: bracket.bracketType };
			}
			else {
				var token = (result === '' ? '' : result + this.lexer.tokenPostfix);
				return { type: MonarchCommonTypes.sanitize(token), bracket: action.bracket };
			}
		}
	}
}

/**
 * Searches for a bracket in the 'brackets' attribute that matches the input.
 */
function findBracket(lexer: MonarchCommonTypes.ILexer, matched: string) {
A
tslint  
Alex Dima 已提交
372 373 374
	if (!matched) {
		return null;
	}
E
Erich Gamma 已提交
375 376 377 378 379 380
	matched = MonarchCommonTypes.fixCase(lexer, matched);

	var brackets = lexer.brackets;
	for (var i = 0; i < brackets.length; i++) {
		var bracket = brackets[i];
		if (bracket.open === matched) {
A
tslint  
Alex Dima 已提交
381
			return { token: bracket.token, bracketType: Modes.Bracket.Open };
E
Erich Gamma 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
		}
		else if (bracket.close === matched) {
			return { token: bracket.token, bracketType: Modes.Bracket.Close };
		}
	}
	return null;
}

export function createTokenizationSupport(modeService:IModeService, mode:Modes.IMode, lexer: MonarchCommonTypes.ILexer): Modes.ITokenizationSupport {
	return new Supports.TokenizationSupport(mode, {
		getInitialState: (): Modes.IState => {
			return new MonarchLexer(mode, lexer);
		},

		enterNestedMode: (state: Modes.IState): boolean => {
			if (state instanceof MonarchLexer) {
				return state.embeddedEntered;
			}
			return false;
		},

		getNestedMode: (rawState: Modes.IState): Supports.IEnteringNestedModeData => {
			var mime = (<MonarchLexer>rawState).embeddedMode;

			if (!modesRegistry.isRegisteredMode(mime)) {
				// unknown mode
				return {
					mode: modeService.getMode('text/plain'),
					missingModePromise: null
				};
			}

			var mode = modeService.getMode(mime);
			if (mode) {
				// mode is available
				return {
					mode: mode,
					missingModePromise: null
				};
			}

			// mode is not yet loaded
			return {
				mode: modeService.getMode('text/plain'),
				missingModePromise: modeService.getOrCreateMode(mime).then(() => null)
			};
		},

		getLeavingNestedModeData: (line: string, state: Modes.IState) => {
			// state = state.clone();
			var mstate = <MonarchLexer>state.clone();
			var stream = new LineStream(line);
			while (!stream.eos() && mstate.embeddedMode) {
				mstate.tokenize(stream, true); // allow no consumption for @rematch
			}
A
tslint  
Alex Dima 已提交
437 438 439
			if (mstate.embeddedMode) {
				return null;  // don't leave yet
			}
E
Erich Gamma 已提交
440 441 442 443 444 445 446 447 448 449

			var end = stream.pos();
			return {
				nestedModeBuffer: line.substring(0, end),
				bufferAfterNestedMode: line.substring(end),
				stateAfterNestedMode: mstate
			};
		}
	}, lexer.usesEmbedded, false);
}