forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.ts
More file actions
1721 lines (1427 loc) · 71.9 KB
/
Copy pathscanner.ts
File metadata and controls
1721 lines (1427 loc) · 71.9 KB
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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///<reference path='references.ts' />
module TypeScript.Scanner {
// Make sure we can encode a token's kind in 7 bits.
Debug.assert(SyntaxKind.LastToken <= 127);
// Fixed width tokens (keywords and punctuation) that have no trivia generally make up 30% of
// all the tokens in a program. We heavily optimize for that case with a token instance that
// just needs a parent pointer and a single 30bit int like so:
//
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0xxx xxxx <-- kind
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx xxxx x000 0000 <-- full start
// ^ ^ ^
// | | |
// Bit 64 Bit 30 Bit 1
//
// This gives us 23 bits for the start of the token. We don't need to store the width as it
// can be inferred from the 'kind' for a fixed width token.
//
// For small tokens, we encode the data in one 30bit int like so:
//
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0xxx xxxx <-- kind
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 xxxx x000 0000 <-- full width
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx 0000 0000 0000 <-- full start
// ^ ^ ^
// | | |
// Bit 64 Bit 30 Bit 1
//
// This allows for 5bits for teh width. i.e. tokens up to 31 chars in width. And 18 bits for
// the full start. This allows for tokens starting up to and including position 262,143.
//
// In practice, for codebases we have measured, these values are sufficient to cover ~85% of
// all tokens. If a token won't fit within those limits, we make a large token for it.
//
//
// For large tokens, we encode data with two 30 bit ints like so:
//
// _packedFullStartAndInfo:
//
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000x <-- has leading trivia
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00x0 <-- has leading comment (implies has leading trivia)
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0x00 <-- has trailing trivia
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 x000 <-- has trailing comment (implies has trailing trivia)
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx xxxx xxxx 0000 <-- full start
// ^ ^ ^
// | | |
// Bit 64 Bit 30 Bit 1
//
// This gives us 26 bits for the start of the token. At 64MB That's more than enough for
// any codebase.
//
// _packedFullWidthAndKind:
//
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0xxx xxxx <-- kind
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx xxxx x000 0000 <-- full width
// ^ ^ ^
// | | |
// Bit 64 Bit 30 Bit 1
//
// This gives us 23bit for width (or 8MB of width which should be enough for any codebase).
enum ScannerConstants {
LargeTokenFullWidthShift = 6,
LargeTokenLeadingTriviaShift = 3,
WhitespaceTrivia = 0x01, // 00000001
NewlineTrivia = 0x02, // 00000010
CommentTrivia = 0x04, // 00000100
TriviaMask = 0x07, // 00000111
KindMask = 0x7F, // 01111111
IsVariableWidthMask = 0x80, // 10000000
}
function largeTokenPackData(fullWidth: number, leadingTriviaInfo: number, trailingTriviaInfo: number) {
return (fullWidth << ScannerConstants.LargeTokenFullWidthShift) | (leadingTriviaInfo << ScannerConstants.LargeTokenLeadingTriviaShift) | trailingTriviaInfo;
}
function largeTokenUnpackFullWidth(packedFullWidthAndInfo: number): number {
return packedFullWidthAndInfo >> ScannerConstants.LargeTokenFullWidthShift;
}
function largeTokenUnpackLeadingTriviaInfo(packedFullWidthAndInfo: number): number {
return (packedFullWidthAndInfo >> ScannerConstants.LargeTokenLeadingTriviaShift) & ScannerConstants.TriviaMask;
}
function largeTokenUnpackTrailingTriviaInfo(packedFullWidthAndInfo: number): number {
return packedFullWidthAndInfo & ScannerConstants.TriviaMask;
}
function largeTokenUnpackHasLeadingTrivia(packed: number): boolean {
return largeTokenUnpackLeadingTriviaInfo(packed) !== 0;
}
function largeTokenUnpackHasTrailingTrivia(packed: number): boolean {
return largeTokenUnpackTrailingTriviaInfo(packed) !== 0;
}
function hasComment(info: number) {
return (info & ScannerConstants.CommentTrivia) !== 0;
}
function largeTokenUnpackHasLeadingComment(packed: number): boolean {
return hasComment(largeTokenUnpackLeadingTriviaInfo(packed));
}
function largeTokenUnpackHasTrailingComment(packed: number): boolean {
return hasComment(largeTokenUnpackTrailingTriviaInfo(packed));
}
var isKeywordStartCharacter: number[] = ArrayUtilities.createArray<number>(CharacterCodes.maxAsciiCharacter, 0);
var isIdentifierStartCharacter: boolean[] = ArrayUtilities.createArray<boolean>(CharacterCodes.maxAsciiCharacter, false);
var isIdentifierPartCharacter: boolean[] = ArrayUtilities.createArray<boolean>(CharacterCodes.maxAsciiCharacter, false);
for (var character = 0; character < CharacterCodes.maxAsciiCharacter; character++) {
if ((character >= CharacterCodes.a && character <= CharacterCodes.z) ||
(character >= CharacterCodes.A && character <= CharacterCodes.Z) ||
character === CharacterCodes._ || character === CharacterCodes.$) {
isIdentifierStartCharacter[character] = true;
isIdentifierPartCharacter[character] = true;
}
else if (character >= CharacterCodes._0 && character <= CharacterCodes._9) {
isIdentifierPartCharacter[character] = true;
}
}
for (var keywordKind = SyntaxKind.FirstKeyword; keywordKind <= SyntaxKind.LastKeyword; keywordKind++) {
var keyword = SyntaxFacts.getText(keywordKind);
isKeywordStartCharacter[keyword.charCodeAt(0)] = 1;
}
export function isContextualToken(token: ISyntaxToken): boolean {
// These tokens are contextually created based on parsing decisions. We can't reuse
// them in incremental scenarios as we may be in a context where the parser would not
// create them.
switch (token.kind) {
// Created by the parser when it sees / or /= in a location where it needs an expression.
case SyntaxKind.RegularExpressionLiteral:
// Created by the parser when it sees > in a binary expression operator context.
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
return true;
// Created by the parser when it sees } while parsing a template expression.
case SyntaxKind.TemplateMiddleToken:
case SyntaxKind.TemplateEndToken:
return true;
default:
return token.isKeywordConvertedToIdentifier();
}
}
var lastTokenInfo = { leadingTriviaWidth: -1, width: -1 };
var lastTokenInfoTokenID: number = -1;
var triviaScanner = createScannerInternal(ts.ScriptTarget.Latest, SimpleText.fromString(""), () => { });
interface IScannerToken extends ISyntaxToken {
}
function fillSizeInfo(token: IScannerToken, text: ISimpleText): void {
if (lastTokenInfoTokenID !== syntaxID(token)) {
triviaScanner.fillTokenInfo(token, text, lastTokenInfo);
lastTokenInfoTokenID = syntaxID(token);
}
}
function fullText(token: IScannerToken, text: ISimpleText): string {
return text.substr(token.fullStart(), token.fullWidth());
}
function leadingTrivia(token: IScannerToken, text: ISimpleText): ISyntaxTriviaList {
if (!token.hasLeadingTrivia()) {
return Syntax.emptyTriviaList;
}
return triviaScanner.scanTrivia(token, text, /*isTrailing:*/ false);
}
function trailingTrivia(token: IScannerToken, text: ISimpleText): ISyntaxTriviaList {
if (!token.hasTrailingTrivia()) {
return Syntax.emptyTriviaList;
}
return triviaScanner.scanTrivia(token, text, /*isTrailing:*/ true);
}
function leadingTriviaWidth(token: IScannerToken, text: ISimpleText): number {
if (!token.hasLeadingTrivia()) {
return 0;
}
fillSizeInfo(token, text);
return lastTokenInfo.leadingTriviaWidth;
}
function trailingTriviaWidth(token: IScannerToken, text: ISimpleText): number {
if (!token.hasTrailingTrivia()) {
return 0;
}
fillSizeInfo(token, text);
return token.fullWidth() - lastTokenInfo.leadingTriviaWidth - lastTokenInfo.width;
}
function tokenIsIncrementallyUnusable(token: IScannerToken): boolean {
// No scanner tokens make their *containing node* incrementally unusable.
// Note: several scanner tokens may themselves be unusable. i.e. if the parser asks
// for a full node, then that ndoe can be returned even if it contains parser generated
// tokens (like regexs and merged operator tokens). However, if the parser asks for a
// for a token, then those contextual tokens will not be reusable.
return false;
}
class FixedWidthTokenWithNoTrivia implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public childCount: number;
constructor(private _fullStart: number, public kind: SyntaxKind) {
}
public setFullStart(fullStart: number): void {
this._fullStart = fullStart;
}
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
public isIncrementallyUnusable(): boolean { return false; }
public isKeywordConvertedToIdentifier(): boolean { return false; }
public hasSkippedToken(): boolean { return false; }
public fullText(): string { return SyntaxFacts.getText(this.kind); }
public text(): string { return this.fullText(); }
public leadingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public trailingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public leadingTriviaWidth(): number { return 0; }
public trailingTriviaWidth(): number { return 0; }
public fullWidth(): number { return fixedWidthTokenLength(this.kind); }
public fullStart(): number { return this._fullStart; }
public hasLeadingTrivia(): boolean { return false; }
public hasTrailingTrivia(): boolean { return false; }
public hasLeadingComment(): boolean { return false; }
public hasTrailingComment(): boolean { return false; }
public clone(): ISyntaxToken { return new FixedWidthTokenWithNoTrivia(this._fullStart, this.kind); }
}
FixedWidthTokenWithNoTrivia.prototype.childCount = 0;
class LargeScannerToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public childCount: number;
private cachedText: string;
constructor(private _fullStart: number, public kind: SyntaxKind, private _packedFullWidthAndInfo: number, cachedText: string) {
if (cachedText !== undefined) {
this.cachedText = cachedText;
}
}
public setFullStart(fullStart: number): void {
this._fullStart = fullStart;
}
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
private syntaxTreeText(text: ISimpleText) {
var result = text || syntaxTree(this).text;
Debug.assert(result);
return result;
}
public isIncrementallyUnusable(): boolean { return tokenIsIncrementallyUnusable(this); }
public isKeywordConvertedToIdentifier(): boolean { return false; }
public hasSkippedToken(): boolean { return false; }
public fullText(text?: ISimpleText): string {
return fullText(this, this.syntaxTreeText(text));
}
public text(): string {
var cachedText = this.cachedText;
return cachedText !== undefined ? cachedText : SyntaxFacts.getText(this.kind);
}
public leadingTrivia(text?: ISimpleText): ISyntaxTriviaList { return leadingTrivia(this, this.syntaxTreeText(text)); }
public trailingTrivia(text?: ISimpleText): ISyntaxTriviaList { return trailingTrivia(this, this.syntaxTreeText(text)); }
public leadingTriviaWidth(text?: ISimpleText): number {
return leadingTriviaWidth(this, this.syntaxTreeText(text));
}
public trailingTriviaWidth(text?: ISimpleText): number {
return trailingTriviaWidth(this, this.syntaxTreeText(text));
}
public fullWidth(): number { return largeTokenUnpackFullWidth(this._packedFullWidthAndInfo); }
public fullStart(): number { return this._fullStart; }
public hasLeadingTrivia(): boolean { return largeTokenUnpackHasLeadingTrivia(this._packedFullWidthAndInfo); }
public hasTrailingTrivia(): boolean { return largeTokenUnpackHasTrailingTrivia(this._packedFullWidthAndInfo); }
public hasLeadingComment(): boolean { return largeTokenUnpackHasLeadingComment(this._packedFullWidthAndInfo); }
public hasTrailingComment(): boolean { return largeTokenUnpackHasTrailingComment(this._packedFullWidthAndInfo); }
public clone(): ISyntaxToken { return new LargeScannerToken(this._fullStart, this.kind, this._packedFullWidthAndInfo, this.cachedText); }
}
LargeScannerToken.prototype.childCount = 0;
export interface DiagnosticCallback {
(position: number, width: number, key: string, arguments: any[]): void;
}
interface TokenInfo {
leadingTriviaWidth: number;
width: number;
}
interface IScannerInternal extends IScanner {
fillTokenInfo(token: IScannerToken, text: ISimpleText, tokenInfo: TokenInfo): void;
scanTrivia(token: IScannerToken, text: ISimpleText, isTrailing: boolean): ISyntaxTriviaList;
}
export interface IScanner {
setIndex(index: number): void;
scan(allowContextualToken: boolean): ISyntaxToken;
}
export function createScanner(languageVersion: ts.ScriptTarget, text: ISimpleText, reportDiagnostic: DiagnosticCallback): IScanner {
var scanner = createScannerInternal(languageVersion, text, reportDiagnostic);
return {
setIndex: scanner.setIndex,
scan: scanner.scan,
};
}
function createScannerInternal(languageVersion: ts.ScriptTarget, text: ISimpleText, reportDiagnostic: DiagnosticCallback): IScannerInternal {
var str: string;
var index: number;
var start: number;
var end: number;
function setIndex(_index: number) {
index = _index;
}
function reset(_text: ISimpleText, _start: number, _end: number) {
var textLength = _text.length();
Debug.assert(_start <= textLength, "Token's start was not within the bounds of text.");
Debug.assert(_end <= textLength, "Token's end was not within the bounds of text:");
if (!str || text !== _text) {
text = _text;
str = _text.substr(0, textLength);
}
start = _start;
end = _end;
index = _start;
}
function scan(allowContextualToken: boolean): ISyntaxToken {
var fullStart = index;
var leadingTriviaInfo = scanTriviaInfo(/*isTrailing: */ false);
var start = index;
var kindAndIsVariableWidth = scanSyntaxKind(allowContextualToken);
var end = index;
var trailingTriviaInfo = scanTriviaInfo(/*isTrailing: */true);
var fullWidth = index - fullStart;
// If we have no trivia, and we are a fixed width token kind, and our size isn't too
// large, and we're a real fixed width token (and not something like "\u0076ar").
var kind = kindAndIsVariableWidth & ScannerConstants.KindMask;
var isFixedWidth = kind >= SyntaxKind.FirstFixedWidth && kind <= SyntaxKind.LastFixedWidth &&
((kindAndIsVariableWidth & ScannerConstants.IsVariableWidthMask) === 0);
if (isFixedWidth &&
leadingTriviaInfo === 0 && trailingTriviaInfo === 0) {
return new FixedWidthTokenWithNoTrivia(fullStart, kind);
}
else {
var packedFullWidthAndInfo = largeTokenPackData(fullWidth, leadingTriviaInfo, trailingTriviaInfo);
var cachedText = isFixedWidth ? undefined : text.substr(start, end - start);
return new LargeScannerToken(fullStart, kind, packedFullWidthAndInfo, cachedText);
}
}
function scanTrivia(parent: IScannerToken, text: ISimpleText, isTrailing: boolean): ISyntaxTriviaList {
var tokenFullStart = parent.fullStart();
var tokenStart = tokenFullStart + leadingTriviaWidth(parent, text)
if (isTrailing) {
reset(text, tokenStart + parent.text().length, tokenFullStart + parent.fullWidth());
}
else {
reset(text, tokenFullStart, tokenStart);
}
// Debug.assert(length > 0);
// Keep this exactly in sync with scanTriviaInfo
var trivia: ISyntaxTrivia[] = [];
while (true) {
if (index < end) {
var ch = str.charCodeAt(index);
switch (ch) {
// Unicode 3.0 space characters
case CharacterCodes.space:
case CharacterCodes.nonBreakingSpace:
case CharacterCodes.enQuad:
case CharacterCodes.emQuad:
case CharacterCodes.enSpace:
case CharacterCodes.emSpace:
case CharacterCodes.threePerEmSpace:
case CharacterCodes.fourPerEmSpace:
case CharacterCodes.sixPerEmSpace:
case CharacterCodes.figureSpace:
case CharacterCodes.punctuationSpace:
case CharacterCodes.thinSpace:
case CharacterCodes.hairSpace:
case CharacterCodes.zeroWidthSpace:
case CharacterCodes.narrowNoBreakSpace:
case CharacterCodes.ideographicSpace:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.byteOrderMark:
// Normal whitespace. Consume and continue.
trivia.push(scanWhitespaceTrivia());
continue;
case CharacterCodes.slash:
// Potential comment. Consume if so. Otherwise, break out and return.
var ch2 = str.charCodeAt(index + 1);
if (ch2 === CharacterCodes.slash) {
trivia.push(scanSingleLineCommentTrivia());
continue;
}
if (ch2 === CharacterCodes.asterisk) {
trivia.push(scanMultiLineCommentTrivia());
continue;
}
// Not a comment. Don't consume.
throw Errors.invalidOperation();
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
trivia.push(scanLineTerminatorSequenceTrivia(ch));
// If we're consuming leading trivia, then we will continue consuming more
// trivia (including newlines) up to the first token we see. If we're
// consuming trailing trivia, then we break after the first newline we see.
if (!isTrailing) {
continue;
}
break;
default:
throw Errors.invalidOperation();
}
}
// Debug.assert(trivia.length > 0);
var triviaList = Syntax.triviaList(trivia);
triviaList.parent = parent;
return triviaList;
}
}
// Returns 0 if there was no trivia, or 1 if there was trivia. Returned as an int instead
// of a boolean because we'll need a numerical value later on to store in our tokens.
function scanTriviaInfo(isTrailing: boolean): number {
// Keep this exactly in sync with scanTrivia
var result = 0;
var _end = end;
while (index < _end) {
var ch = str.charCodeAt(index);
switch (ch) {
case CharacterCodes.tab:
case CharacterCodes.space:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
index++;
// we have trivia
result |= ScannerConstants.WhitespaceTrivia;
continue;
case CharacterCodes.carriageReturn:
if ((index + 1) < end && str.charCodeAt(index + 1) === CharacterCodes.lineFeed) {
index++;
}
// fall through.
case CharacterCodes.lineFeed:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
index++;
// we have trivia
result |= ScannerConstants.NewlineTrivia;
// If we're consuming leading trivia, then we will continue consuming more
// trivia (including newlines) up to the first token we see. If we're
// consuming trailing trivia, then we break after the first newline we see.
if (isTrailing) {
return result;
}
continue;
case CharacterCodes.slash:
if ((index + 1) < _end) {
var ch2 = str.charCodeAt(index + 1);
if (ch2 === CharacterCodes.slash) {
// we have a comment, and we have trivia
result |= ScannerConstants.CommentTrivia;
skipSingleLineCommentTrivia();
continue;
}
if (ch2 === CharacterCodes.asterisk) {
// we have a comment, and we have trivia
result |= ScannerConstants.CommentTrivia;
skipMultiLineCommentTrivia();
continue;
}
}
// Not a comment. Don't consume.
return result;
default:
if (ch > CharacterCodes.maxAsciiCharacter && slowScanWhitespaceTriviaInfo(ch)) {
result |= ScannerConstants.WhitespaceTrivia;
continue;
}
return result;
}
}
return result;
}
function slowScanWhitespaceTriviaInfo(ch: number): boolean {
switch (ch) {
case CharacterCodes.nonBreakingSpace:
case CharacterCodes.enQuad:
case CharacterCodes.emQuad:
case CharacterCodes.enSpace:
case CharacterCodes.emSpace:
case CharacterCodes.threePerEmSpace:
case CharacterCodes.fourPerEmSpace:
case CharacterCodes.sixPerEmSpace:
case CharacterCodes.figureSpace:
case CharacterCodes.punctuationSpace:
case CharacterCodes.thinSpace:
case CharacterCodes.hairSpace:
case CharacterCodes.zeroWidthSpace:
case CharacterCodes.narrowNoBreakSpace:
case CharacterCodes.ideographicSpace:
case CharacterCodes.byteOrderMark:
index++;
return true;
default:
return false;
}
}
function isNewLineCharacter(ch: number): boolean {
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
return true;
default:
return false;
}
}
function scanWhitespaceTrivia(): ISyntaxTrivia {
// We're going to be extracting text out of sliding window. Make sure it can't move past
// this point.
var absoluteStartIndex = index;
while (true) {
var ch = str.charCodeAt(index);
switch (ch) {
// Unicode 3.0 space characters
case CharacterCodes.space:
case CharacterCodes.nonBreakingSpace:
case CharacterCodes.enQuad:
case CharacterCodes.emQuad:
case CharacterCodes.enSpace:
case CharacterCodes.emSpace:
case CharacterCodes.threePerEmSpace:
case CharacterCodes.fourPerEmSpace:
case CharacterCodes.sixPerEmSpace:
case CharacterCodes.figureSpace:
case CharacterCodes.punctuationSpace:
case CharacterCodes.thinSpace:
case CharacterCodes.hairSpace:
case CharacterCodes.zeroWidthSpace:
case CharacterCodes.narrowNoBreakSpace:
case CharacterCodes.ideographicSpace:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.byteOrderMark:
// Normal whitespace. Consume and continue.
index++;
continue;
}
break;
}
return createTrivia(SyntaxKind.WhitespaceTrivia, absoluteStartIndex);
}
function createTrivia(kind: SyntaxKind, absoluteStartIndex: number): ISyntaxTrivia {
var fullWidth = index - absoluteStartIndex;
return Syntax.deferredTrivia(kind, text, absoluteStartIndex, fullWidth);
}
function scanSingleLineCommentTrivia(): ISyntaxTrivia {
var absoluteStartIndex = index;
skipSingleLineCommentTrivia();
return createTrivia(SyntaxKind.SingleLineCommentTrivia, absoluteStartIndex);
}
function skipSingleLineCommentTrivia(): void {
index += 2;
// The '2' is for the "//" we consumed.
while (index < end) {
if (isNewLineCharacter(str.charCodeAt(index))) {
return;
}
index++;
}
}
function scanMultiLineCommentTrivia(): ISyntaxTrivia {
var absoluteStartIndex = index;
skipMultiLineCommentTrivia();
return createTrivia(SyntaxKind.MultiLineCommentTrivia, absoluteStartIndex);
}
function skipMultiLineCommentTrivia(): number {
// The '2' is for the "/*" we consumed.
index += 2;
while (true) {
if (index === end) {
reportDiagnostic(end, 0, DiagnosticCode._0_expected, ["*/"]);
return;
}
if ((index + 1) < end &&
str.charCodeAt(index) === CharacterCodes.asterisk &&
str.charCodeAt(index + 1) === CharacterCodes.slash) {
index += 2;
return;
}
index++;
}
}
function scanLineTerminatorSequenceTrivia(ch: number): ISyntaxTrivia {
var absoluteStartIndex = index;
skipLineTerminatorSequence(ch);
return createTrivia(SyntaxKind.NewLineTrivia, absoluteStartIndex);
}
function skipLineTerminatorSequence(ch: number): void {
// Consume the first of the line terminator we saw.
index++;
// If it happened to be a \r and there's a following \n, then consume both.
if (ch === CharacterCodes.carriageReturn && str.charCodeAt(index) === CharacterCodes.lineFeed) {
index++;
}
}
function scanSyntaxKind(allowContextualToken: boolean): SyntaxKind {
if (index >= end) {
return SyntaxKind.EndOfFileToken;
}
var character = str.charCodeAt(index);
index++;
switch (character) {
case CharacterCodes.exclamation/*33*/: return scanExclamationToken();
case CharacterCodes.doubleQuote/*34*/: return scanStringLiteral(character);
case CharacterCodes.percent/*37*/: return scanPercentToken();
case CharacterCodes.ampersand/*38*/: return scanAmpersandToken();
case CharacterCodes.singleQuote/*39*/: return scanStringLiteral(character);
case CharacterCodes.openParen/*40*/: return SyntaxKind.OpenParenToken;
case CharacterCodes.closeParen/*41*/: return SyntaxKind.CloseParenToken;
case CharacterCodes.asterisk/*42*/: return scanAsteriskToken();
case CharacterCodes.plus/*43*/: return scanPlusToken();
case CharacterCodes.comma/*44*/: return SyntaxKind.CommaToken;
case CharacterCodes.minus/*45*/: return scanMinusToken();
case CharacterCodes.dot/*46*/: return scanDotToken();
case CharacterCodes.slash/*47*/: return scanSlashToken(allowContextualToken);
case CharacterCodes._0/*48*/: case CharacterCodes._1: case CharacterCodes._2: case CharacterCodes._3:
case CharacterCodes._4: case CharacterCodes._5: case CharacterCodes._6: case CharacterCodes._7:
case CharacterCodes._8: case CharacterCodes._9/*57*/:
return scanNumericLiteral(character);
case CharacterCodes.colon/*58*/: return SyntaxKind.ColonToken;
case CharacterCodes.semicolon/*59*/: return SyntaxKind.SemicolonToken;
case CharacterCodes.lessThan/*60*/: return scanLessThanToken();
case CharacterCodes.equals/*61*/: return scanEqualsToken();
case CharacterCodes.greaterThan/*62*/: return scanGreaterThanToken(allowContextualToken);
case CharacterCodes.question/*63*/: return SyntaxKind.QuestionToken;
case CharacterCodes.openBracket/*91*/: return SyntaxKind.OpenBracketToken;
case CharacterCodes.closeBracket/*93*/: return SyntaxKind.CloseBracketToken;
case CharacterCodes.caret/*94*/: return scanCaretToken();
case CharacterCodes.backtick/*96*/: return scanTemplateToken(character);
case CharacterCodes.openBrace/*123*/: return SyntaxKind.OpenBraceToken;
case CharacterCodes.bar/*124*/: return scanBarToken();
case CharacterCodes.closeBrace/*125*/: return scanCloseBraceToken(allowContextualToken, character);
case CharacterCodes.tilde/*126*/: return SyntaxKind.TildeToken;
}
// We run into so many identifiers (and keywords) when scanning, that we want the code to
// be as fast as possible. To that end, we have an extremely fast path for scanning that
// handles the 99.9% case of no-unicode characters and no unicode escapes.
if (isIdentifierStartCharacter[character]) {
var result = tryFastScanIdentifierOrKeyword(character);
if (result !== SyntaxKind.None) {
return result;
}
}
// Move the index back one and try the slow path.
index--;
if (isIdentifierStart(peekCharOrUnicodeEscape())) {
return slowScanIdentifierOrKeyword();
}
// Was nothing that we could understand. Report the issue and keep moving on.
var text = String.fromCharCode(character);
var messageText = getErrorMessageText(text);
reportDiagnostic(index, 1, DiagnosticCode.Unexpected_character_0, [messageText]);
index++;
return SyntaxKind.ErrorToken;
}
function isIdentifierStart(interpretedChar: number): boolean {
if (isIdentifierStartCharacter[interpretedChar]) {
return true;
}
return interpretedChar > CharacterCodes.maxAsciiCharacter && Unicode.isIdentifierStart(interpretedChar, languageVersion);
}
function isIdentifierPart(interpretedChar: number): boolean {
if (isIdentifierPartCharacter[interpretedChar]) {
return true;
}
return interpretedChar > CharacterCodes.maxAsciiCharacter && Unicode.isIdentifierPart(interpretedChar, languageVersion);
}
function tryFastScanIdentifierOrKeyword(firstCharacter: number): SyntaxKind {
var startIndex = index;
var character = firstCharacter;
// Note that we go up to the windowCount-1 so that we can read the character at the end
// of the window and check if it's *not* an identifier part character.
while (index < end) {
character = str.charCodeAt(index);
if (!isIdentifierPartCharacter[character]) {
break;
}
index++;
}
if (index < end && (character === CharacterCodes.backslash || character > CharacterCodes.maxAsciiCharacter)) {
// We saw a \ (which could start a unicode escape), or we saw a unicode character.
// This can't be scanned quickly. Don't update the window position and just bail out
// to the slow path.
index = startIndex;
return SyntaxKind.None;
}
else {
// Saw an ascii character that wasn't a backslash and wasn't an identifier
// character. Or we hit the end of the file This identifier is done.
// Also check if it a keyword if it started with a keyword start char.
if (isKeywordStartCharacter[firstCharacter]) {
return ScannerUtilities.identifierKind(str, startIndex - 1, index - startIndex + 1);
}
else {
return SyntaxKind.IdentifierName;
}
}
}
// A slow path for scanning identifiers. Called when we run into a unicode character or
// escape sequence while processing the fast path.
function slowScanIdentifierOrKeyword(): SyntaxKind {
var startIndex = index;
do {
scanCharOrUnicodeEscape();
}
while (isIdentifierPart(peekCharOrUnicodeEscape()));
// From ES6 specification.
// The ReservedWord definitions are specified as literal sequences of Unicode
// characters.However, any Unicode character in a ReservedWord can also be
// expressed by a \ UnicodeEscapeSequence that expresses that same Unicode
// character's code point.Use of such escape sequences does not change the meaning
// of the ReservedWord.
//
// i.e. "\u0076ar" is the keyword 'var'. Check for that here.
var length = index - startIndex;
var text = str.substr(startIndex, length);
var valueText = massageEscapes(text);
var keywordKind = SyntaxFacts.getTokenKind(valueText);
if (keywordKind >= SyntaxKind.FirstKeyword && keywordKind <= SyntaxKind.LastKeyword) {
// We have a keyword, but it is also variable width. We can't put represent this
// width a fixed width token.
return keywordKind | ScannerConstants.IsVariableWidthMask;
}
return SyntaxKind.IdentifierName;
}
function scanNumericLiteral(ch: number): SyntaxKind {
if (isHexNumericLiteral(ch)) {
scanHexNumericLiteral();
}
else if (isOctalNumericLiteral(ch)) {
scanOctalNumericLiteral();
}
else {
scanDecimalNumericLiteral();
}
return SyntaxKind.NumericLiteral;
}
function isOctalNumericLiteral(ch: number): boolean {
return ch === CharacterCodes._0 &&
CharacterInfo.isOctalDigit(str.charCodeAt(index));
}
function scanOctalNumericLiteral(): void {
var start = index - 1;
while (CharacterInfo.isOctalDigit(str.charCodeAt(index))) {
index++;
}
if (languageVersion >= ts.ScriptTarget.ES5) {
reportDiagnostic(
start, index - start, DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, undefined);
}
}
function scanDecimalDigits(): void {
while (CharacterInfo.isDecimalDigit(str.charCodeAt(index))) {
index++;
}
}
function scanDecimalNumericLiteral(): void {
scanDecimalDigits();
if (str.charCodeAt(index) === CharacterCodes.dot) {
index++;
}
scanDecimalNumericLiteralAfterDot();
}
function scanDecimalNumericLiteralAfterDot() {
scanDecimalDigits();
// If we see an 'e' or 'E' we should only consume it if its of the form:
// e<number> or E<number>
// e+<number> E+<number>
// e-<number> E-<number>
var ch = str.charCodeAt(index);
if (ch === CharacterCodes.e || ch === CharacterCodes.E) {
// Ok, we've got 'e' or 'E'. Make sure it's followed correctly.
var nextChar1 = str.charCodeAt(index + 1);
if (CharacterInfo.isDecimalDigit(nextChar1)) {
// e<number> or E<number>
// Consume 'e' or 'E' and the number portion.
index++;
scanDecimalDigits();
}
else if (nextChar1 === CharacterCodes.minus || nextChar1 === CharacterCodes.plus) {
// e+ or E+ or e- or E-
var nextChar2 = str.charCodeAt(index + 2);
if (CharacterInfo.isDecimalDigit(nextChar2)) {
// e+<number> or E+<number> or e-<number> or E-<number>
// Consume first two characters and the number portion.
index += 2;
scanDecimalDigits();
}
}
}
}
function scanHexNumericLiteral(): void {
// Move past the x.
index++;
while (CharacterInfo.isHexDigit(str.charCodeAt(index))) {
index++;
}
}
function isHexNumericLiteral(ch: number): boolean {
if (ch === CharacterCodes._0) {
var ch = str.charCodeAt(index);
if (ch === CharacterCodes.x || ch === CharacterCodes.X) {
return CharacterInfo.isHexDigit(str.charCodeAt(index + 1));
}
}
return false;
}
function scanLessThanToken(): SyntaxKind {
var ch0 = str.charCodeAt(index);
if (ch0 === CharacterCodes.equals) {
index++;
return SyntaxKind.LessThanEqualsToken;
}
else if (ch0 === CharacterCodes.lessThan) {
index++;
if (str.charCodeAt(index) === CharacterCodes.equals) {
index++;
return SyntaxKind.LessThanLessThanEqualsToken;
}
else {
return SyntaxKind.LessThanLessThanToken;
}
}
else {
return SyntaxKind.LessThanToken;
}
}
function scanGreaterThanToken(allowContextualToken: boolean): SyntaxKind {
if (allowContextualToken) {
var ch0 = str.charCodeAt(index);
if (ch0 === CharacterCodes.greaterThan) {
// >>
index++;
var ch1 = str.charCodeAt(index);
if (ch1 === CharacterCodes.greaterThan) {
// >>>
index++;