csharpTokenization.ts 18.2 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
/*---------------------------------------------------------------------------------------------
 *  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 objects = require('vs/base/common/objects');
import Modes = require('vs/editor/common/modes');
import htmlMode = require('vs/languages/html/common/html');
import VSXML = require('vs/languages/vsxml/common/vsxml');
import {AbstractState} from 'vs/editor/common/modes/abstractState';
import {isDigit} from 'vs/editor/common/modes/abstractMode';
import razorTokenTypes = require('vs/languages/razor/common/razorTokenTypes');

var htmlTokenTypes = htmlMode.htmlTokenTypes;

var punctuations = '+-*%&|^~!=<>/?;:.,';
var separators = '+-*/%&|^~!=<>(){}[]\"\'\\/?;:.,';
var whitespace = '\t ';

var brackets = (function() {

	let bracketsSource = [
		{ tokenType:'punctuation.bracket.cs', open: '{', close: '}', isElectric: true },
		{ tokenType:'punctuation.array.cs', open: '[', close: ']', isElectric: true },
A
Alex Dima 已提交
26
		{ tokenType:'punctuation.parenthesis.cs', open: '(', close: ')', isElectric: true }
E
Erich Gamma 已提交
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
	];

	let MAP: {
		[text:string]:{
			tokenType: string;
			bracketType: Modes.Bracket
		}
	} = Object.create(null);

	for (let i = 0; i < bracketsSource.length; i++) {
		let bracket = bracketsSource[i];
		MAP[bracket.open] = {
			tokenType: bracket.tokenType,
			bracketType: Modes.Bracket.Open
		};
		MAP[bracket.close] = {
			tokenType: bracket.tokenType,
			bracketType: Modes.Bracket.Close
		};
	}

	return {
		stringIsBracket: (text:string): boolean => {
			return !!MAP[text];
		},
		tokenTypeFromString: (text:string): string => {
A
tslint  
Alex Dima 已提交
53
			return MAP[text].tokenType;
E
Erich Gamma 已提交
54 55
		},
		bracketTypeFromString: (text:string): Modes.Bracket => {
A
tslint  
Alex Dima 已提交
56
			return MAP[text].bracketType;
E
Erich Gamma 已提交
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 85 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 139 140 141 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 237 238 239 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 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 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 372 373 374 375 376 377 378 379 380 381 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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
		}
	};
})();

var isKeyword = objects.createKeywordMatcher([
	'abstract', 'as', 'async', 'await', 'base', 'bool',
	'break', 'by', 'byte', 'case',
	'catch', 'char', 'checked', 'class',
	'const', 'continue', 'decimal', 'default',
	'delegate',	'do', 'double',	'descending',
	'explicit',	'event', 'extern', 'else',
	'enum',	'false', 'finally', 'fixed',
	'float', 'for', 'foreach', 'from',
	'goto',	'group', 'if', 'implicit',
	'in', 'int', 'interface', 'internal',
	'into', 'is', 'lock', 'long',
	'new', 'null', 'namespace', 'object',
	'operator', 'out', 'override', 'orderby',
	'params', 'private', 'protected', 'public',
	'readonly', 'ref', 'return', 'switch',
	'struct', 'sbyte', 'sealed', 'short',
	'sizeof', 'stackalloc', 'static', 'string',
	'select', 'this', 'throw', 'true',
	'try', 'typeof', 'uint', 'ulong',
	'unchecked', 'unsafe', 'ushort', 'using',
	'var', 'virtual', 'volatile', 'void',
	'while', 'where', 'yield',
	'model', 'inject' // Razor specific
]);

var ispunctuation = (character:string) => {
	return punctuations.indexOf(character) > -1;
};

export class CSState extends AbstractState {

	public name:string;
	public parent:AbstractState;

	constructor(mode:Modes.IMode, name:string, parent:AbstractState) {
		super(mode);
		this.name = name;
		this.parent = parent;
	}

	public equals(other:Modes.IState):boolean {
		if (!super.equals(other)) {
			return false;
		}
		var otherCSState:CSState = <CSState>other;
		return (other instanceof CSState) && (this.getMode() === otherCSState.getMode()) && (this.name === otherCSState.name) && ((this.parent === null && otherCSState.parent === null) || (this.parent !== null && this.parent.equals(otherCSState.parent)));
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		stream.setTokenRules(separators, whitespace);
		if (stream.skipWhitespace().length > 0) {
			return { type: '' };
		}
		return this.stateTokenize(stream);
	}

	public stateTokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		throw new Error('To be implemented');
	}
}

class CSString extends CSState {

	private isAtBeginning:boolean;
	private punctuation:string;

	constructor(mode:Modes.IMode, parent:AbstractState, punctuation:string) {
		super(mode, 'string', parent);
		this.isAtBeginning = true;
		this.punctuation = punctuation;
	}

	public makeClone():CSString {
		return new CSString(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null, this.punctuation);
	}

	public equals(other:CSString):boolean {
		return super.equals(other) && this.punctuation === other.punctuation;
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		var readChars = this.isAtBeginning ? 1 : 0;
		this.isAtBeginning = false;
		while (!stream.eos()) {
			var c = stream.next();
			if (c === '\\') {
				if (readChars === 0) {
					if (stream.eos()) {
						return { type: 'string.escape.cs' };
					} else {
						stream.next();
						if (stream.eos()) {
							return { type: 'string.escape.cs', nextState: this.parent };
						} else {
							return { type: 'string.escape.cs' };
						}
					}
				} else {
					stream.goBack(1);
					return { type: 'string.cs' };
				}
			} else if (c === this.punctuation) {
				break;
			}
			readChars += 1;
		}
		return { type: 'string.cs', nextState: this.parent };
	}
}

class CSVerbatimString extends CSState {

	constructor(mode:Modes.IMode, parent:AbstractState) {
		super(mode, 'verbatimstring', parent);
	}

	public makeClone():CSVerbatimString {
		return new CSVerbatimString(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null);
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		while (!stream.eos()) {
			var token = stream.next();
			if (token === '"') {
				if (!stream.eos() && stream.peek() === '"') {
					stream.next();
				} else {
					return { type: 'string.cs', nextState: this.parent };
				}
			}
		}
		return { type: 'string.cs' };
	}
}

class CSNumber extends CSState {
	private firstDigit:string;

	constructor(mode:Modes.IMode, parent:AbstractState, firstDigit:string) {
		super(mode, 'number', parent);
		this.firstDigit = firstDigit;
	}

	public makeClone():CSNumber {
		return new CSNumber(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null, this.firstDigit);
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		var character = this.firstDigit;
		var base = 10, isDecimal = false, isExponent = false;
		if (character === '0' && !stream.eos()) {
			character = stream.peek();
			if (character === 'x') {
				base = 16;
			} else if (character === '.') {
				base = 10;
			} else {
				return { type: 'number.cs', nextState: this.parent };
			}
			stream.next();
		}
		while (!stream.eos()) {
			character = stream.peek();
			if (isDigit(character, base)) {
				stream.next();
			} else if (base === 10) {
				if (character === '.' && !isExponent && !isDecimal) {
					isDecimal = true;
					stream.next();
				} else if (character.toLowerCase() === 'e' && !isExponent) {
					isExponent = true;
					stream.next();
					if (!stream.eos() && stream.peek() === '-') {
						stream.next();
					}
				} else if (character.toLowerCase() === 'f' || character.toLowerCase() === 'd') {
					stream.next();
					break;
				} else {
					break;
				}
			} else {
				break;
			}
		}
		var tokenType = 'number';
		if (base === 16) {
			tokenType += '.hex';
		}
		return { type: tokenType + '.cs', nextState: this.parent };
	}
}

// the multi line comment
export class CSComment extends CSState {
	private commentChar:string;

	constructor(mode:Modes.IMode, parent:AbstractState, commentChar:string) {
		super(mode, 'comment', parent);
		this.commentChar = commentChar;
	}

	public makeClone():CSComment {
		return new CSComment(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null, this.commentChar);
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {
		while (!stream.eos()) {
			var token = stream.next();
			if (token === '*' && !stream.eos() && !stream.peekWhitespace() && stream.peek() === this.commentChar) {
				stream.next();
				return { type: 'comment.cs', nextState: this.parent};
			}
		}
		return { type: 'comment.cs' };
	}
}

export class CSStatement extends CSState implements VSXML.IVSXMLWrapperState {
	private level:number;
	private plevel:number;
	private razorMode:boolean;
	private expression:boolean;
	private vsState: VSXML.VSXMLState;
	private firstToken: boolean;
	private firstTokenWasKeyword: boolean;

	constructor(mode: Modes.IMode, parent: AbstractState, level: number, plevel: number, razorMode: boolean,
				expression: boolean, firstToken: boolean, firstTokenWasKeyword: boolean) {
		super(mode, 'expression', parent);
		this.level = level;
		this.plevel = plevel;
		this.razorMode = razorMode;
		this.expression = expression;
		this.vsState = new VSXML.VSXMLExpression(mode, null);
		this.firstToken = firstToken;
		this.firstTokenWasKeyword = firstTokenWasKeyword;
	}

	public setVSXMLState(newVSState:VSXML.VSXMLState):void {
		this.vsState = newVSState;
	}

	public makeClone():CSStatement {
		var st = new CSStatement(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null, this.level,
			this.plevel, this.razorMode, this.expression, this.firstToken, this.firstTokenWasKeyword);
		if (this.vsState !== null) {
			st.setVSXMLState(<VSXML.VSXMLState>this.vsState.clone());
		}
		return st;
	}

	public equals(other:Modes.IState):boolean {
		return super.equals(other) &&
				(other instanceof CSStatement) &&
				((this.vsState === null && (<CSStatement>other).vsState === null) ||
				(this.vsState !== null && this.vsState.equals((<CSStatement>other).vsState)));
	}

	public stateTokenize(stream:Modes.IStream):Modes.ITokenizationResult {

		if (isDigit(stream.peek(), 10)) {
			this.firstToken = false;
			return { nextState: new CSNumber(this.getMode(), this, stream.next()) };
		}

		var token = stream.nextToken();
		var acceptNestedModes = !this.firstTokenWasKeyword;
		var nextStateAtEnd = (this.level <= 0 && this.plevel <= 0 && stream.eos()  ? this.parent : undefined);

		if (stream.eos()) {
			this.firstTokenWasKeyword = false; // Set this for the state starting on the next line.
		}

		if (isKeyword(token)) {
			if (this.level <= 0) {	// if we find a keyword outside of a block, we know that we are outside of an expression
				this.expression = false;
			}
			if (this.firstToken) {
				this.firstTokenWasKeyword = true;
			}
			return { type: 'keyword.cs' };
		}

		this.firstToken = false;

		if (this.razorMode && token === '<' && acceptNestedModes) {
			if (!stream.eos() && /[_:!\/\w]/.test(stream.peek())) {
				return { nextState: new CSSimpleHTML(this.getMode(), this, htmlMode.States.Content) };
			}
		}

		// exit expressions on anything that doesn't look like part of the same expression
		if (this.razorMode && this.expression && this.level <= 0 && this.plevel <= 0&& !stream.eos()) {
			if (!/^(\.|\[|\(|\{\w+)$/.test(stream.peekToken())) {
				nextStateAtEnd = this.parent;
			}
		}

		if (token === '/') {
			if (!stream.eos() && !stream.peekWhitespace()) {
				switch(stream.peekToken()) {
					case '/':
						stream.nextToken();
						if (!stream.eos() && stream.peekToken() === '/') {
							stream.nextToken();
							if (stream.eos()) {
								return {
									type: 'comment.vs'
								};
							}
							if (stream.peekToken() !== '/') {
								return {
									type: 'comment.vs',
									nextState: new VSXML.VSXMLEmbeddedState(this.getMode(), this.vsState, this)
								};
							}
						}
						stream.advanceToEOS();
						return { type: 'comment.cs' };
					case '*':
						stream.nextToken();
						return { nextState: new CSComment(this.getMode(), this, '/') };
				}
			}
			return { type: 'punctuation.cs', nextState: nextStateAtEnd };
		}
		if (token === '@') {	// a verbatim string (or a razor construct)
			if (!stream.eos()) {
				switch(stream.peekToken()) {
				case '"':
					stream.nextToken();
					return { nextState: new CSVerbatimString(this.getMode(), this) };
				case '*':
					stream.nextToken();
					return { nextState: new CSComment(this.getMode(), this, '@') };
				}
			}
		}
		if (/@?\w+/.test(token)) {
			return { type: 'ident.cs', nextState: nextStateAtEnd };
		}

		if (token === '"' || token === '\'') { // string or character
			return { nextState: new CSString(this.getMode(), this, token) };
		}
		if (brackets.stringIsBracket(token)) {

			var tr: Modes.ITokenizationResult = {
				bracket: brackets.bracketTypeFromString(token),
				type: brackets.tokenTypeFromString(token),
				nextState: nextStateAtEnd
			};

			if (this.razorMode) {
				if (token === '{') {
					this.expression = false;	// whenever we enter a block, we exit expression mode
					this.level++;
					if (this.level === 1) {
						tr.type = razorTokenTypes.EMBED_CS;
						tr.nextState = undefined;
					}
				}
				if (token === '}') {
					this.level--;
					if (this.level <= 0) {
						tr.type = razorTokenTypes.EMBED_CS;
						tr.nextState = this.parent;
					}
				}
				if (this.expression) {
					if (token === '(') {
						this.plevel++;
						if (this.plevel === 1) {
							tr.type = razorTokenTypes.EMBED_CS;
							tr.nextState = undefined;
						}
					}
					if (token === ')') {
						this.plevel--;
						if (this.expression && this.plevel <= 0) {	// we only leave csharp mode if we are in expression mode
							tr.type = razorTokenTypes.EMBED_CS;
							tr.nextState = this.parent;
						}
					}
					if (token === '[') {
						this.plevel++;
						tr.nextState = undefined;
					}
					if (token === ']') {
						this.plevel--;
					}
				}
			}
			return tr;
		}

		if (ispunctuation(token)) {
			return { type: 'punctuation.cs', nextState: nextStateAtEnd };
		}

		if (this.razorMode && this.expression && this.plevel <= 0) {	// in razor mode exit on non-keywords in expressions
			return { type: '', nextState: this.parent };
		}

		return { type: '', nextState: nextStateAtEnd };
	}
}

// list of empty elements - for performance reasons we won't open a bracket for them
var emptyElements:string[] = ['area','base','basefont','br','col','frame','hr','img','input','isindex','link','meta','param'];

// this state always returns to parent state if it leaves a html tag
class CSSimpleHTML extends CSState {
	private state:htmlMode.States;

	constructor(mode:Modes.IMode, parent:AbstractState, state:htmlMode.States) {
		super(mode, 'number', parent);
		this.state = state;
	}

	public makeClone():CSSimpleHTML {
		return new CSSimpleHTML(this.getMode(), this.parent ? <AbstractState>this.parent.clone() : null, this.state);
	}

	private nextName(stream:Modes.IStream):string {
		return stream.advanceIfRegExp(/^[_:\w][_:\w-.\d]*/);
	}

	private nextAttrValue(stream:Modes.IStream):string {
		return stream.advanceIfRegExp(/^('|').*?\1/);
	}

	public tokenize(stream:Modes.IStream):Modes.ITokenizationResult {

		switch (this.state) {

			case htmlMode.States.WithinComment:
				if (stream.advanceUntil('-->', false).length > 0) {
					return { type: htmlTokenTypes.COMMENT};
				}
				if (stream.advanceIfString('-->').length > 0) {
					this.state = htmlMode.States.Content;
					return { type: htmlTokenTypes.DELIM_COMMENT, bracket: Modes.Bracket.Close, nextState: this.parent };
				}
				break;

			case htmlMode.States.WithinDoctype:
				if (stream.advanceUntil('>', false).length > 0) {
					return { type: htmlTokenTypes.DOCTYPE };
				}
				if (stream.advanceIfString('>').length > 0) {
					this.state = htmlMode.States.Content;
					return { type: htmlTokenTypes.DELIM_DOCTYPE, bracket: Modes.Bracket.Close, nextState: this.parent };
				}
				break;

			case htmlMode.States.Content:
				if (stream.advanceIfString('!--').length > 0){
					this.state = htmlMode.States.WithinComment;
					return { type: htmlTokenTypes.DELIM_COMMENT, bracket: Modes.Bracket.Open };
				}
				if (stream.advanceIfRegExp(/!DOCTYPE/i).length > 0) {
					this.state = htmlMode.States.WithinDoctype;
					return { type: htmlTokenTypes.DELIM_DOCTYPE, bracket: Modes.Bracket.Open };
				}
				if (stream.advanceIfString('/').length > 0){
					this.state = htmlMode.States.OpeningEndTag;
					return { type: htmlTokenTypes.DELIM_END, bracket: Modes.Bracket.Open };
				}
				this.state = htmlMode.States.OpeningStartTag;
				return { type: htmlTokenTypes.DELIM_START, bracket: Modes.Bracket.Open };

J
Joao Moreno 已提交
535 536
			case htmlMode.States.OpeningEndTag: {
				let tagName = this.nextName(stream);
E
Erich Gamma 已提交
537 538 539 540 541 542 543 544 545 546 547 548
				if (tagName.length > 0) {
					return {
						type: htmlTokenTypes.getTag(tagName),
						bracket: emptyElements.indexOf(tagName) !== -1 ? -1 : Modes.Bracket.Close
					};
				}
				if (stream.advanceIfString('>').length > 0) {
					this.state = htmlMode.States.Content;
					return { type: htmlTokenTypes.DELIM_END, bracket: Modes.Bracket.Close, nextState: this.parent };
				}
				stream.advanceUntil('>', false);
				return { type: '' };
J
Joao Moreno 已提交
549
			}
E
Erich Gamma 已提交
550

J
Joao Moreno 已提交
551 552
			case htmlMode.States.OpeningStartTag: {
				let tagName = this.nextName(stream);
E
Erich Gamma 已提交
553 554 555 556 557 558 559 560
				if (tagName.length > 0) {
					this.state = htmlMode.States.WithinTag;
					return {
						type: htmlTokenTypes.getTag(tagName),
						bracket: emptyElements.indexOf(tagName) !== -1 ? -1 : Modes.Bracket.Open
					};
				}
				break;
J
Joao Moreno 已提交
561
			}
E
Erich Gamma 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

			case htmlMode.States.WithinTag:
				if (stream.skipWhitespace().length > 0) {
					return { type: '' };
				}
				var name:string = this.nextName(stream);
				if (name.length > 0) {
					this.state = htmlMode.States.AttributeName;
					return { type: htmlTokenTypes.ATTRIB_NAME };
				}
				if (stream.advanceIfRegExp(/^\/?>/).length > 0) {
					this.state = htmlMode.States.Content;
					return { type: htmlTokenTypes.DELIM_START, bracket: Modes.Bracket.Close, nextState: this.parent };
				}
				stream.next();
				return { type: '' };

			case htmlMode.States.AttributeName:
				if (stream.skipWhitespace().length > 0 || stream.eos()) {
					return { type: '' };
				}
				if (stream.peek() === '=') {
					stream.next();
					this.state = htmlMode.States.AttributeValue;
					return { type: '' };
				}
				this.state = htmlMode.States.WithinTag;
				return this.tokenize(stream); // no advance yet - jump to WithinTag

			case htmlMode.States.AttributeValue:
				if (stream.skipWhitespace().length > 0 || stream.eos()) {
					return { type: '' };
				}
				var value = this.nextAttrValue(stream);
				if (value.length > 0) {
					this.state = htmlMode.States.WithinTag;
					return { type: htmlTokenTypes.ATTRIB_VALUE };
				}
				this.state = htmlMode.States.WithinTag;
				return this.tokenize(stream); // no advance yet - jump to WithinTag
		}
		stream.next();
		this.state = htmlMode.States.Content;
		return { type: '', nextState: this.parent };
	}
}