-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer_ts.ts
More file actions
1325 lines (1269 loc) · 39.9 KB
/
Copy pathlexer_ts.ts
File metadata and controls
1325 lines (1269 loc) · 39.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
import {
advance_probe,
is_digit,
is_ident,
is_ident_start,
is_space,
is_upper,
scan_ident,
scan_to_line_end,
skip_quoted,
skip_space,
token_type,
trim_space_end,
words_map,
type Lexer,
type SyntaxLang
} from './lexer.ts';
/**
* Hand-written TypeScript/JavaScript lexer.
*
* Disambiguation rests on three rules: previous-token tracking separates a
* regex literal from division, template literals nest their `${…}`
* interpolations, and matching is position-major (a string wins over a comment
* that opens inside it).
*
* Nesting (template interpolations, generic argument lists, `: type`
* annotations) runs on an explicit pooled frame stack, so arbitrarily deep
* input tokenizes fully without touching the JS call stack.
*
* Resilience: unterminated strings extend to end of line; unterminated
* templates, block comments, and interpolations extend to end of window.
* Interpolation bodies discover their own closing `}` during real tokenization
* (nothing is prescanned), so constructs that contain a `}` — regex literals,
* strings, comments — never end an interpolation early. The tradeoff is that
* damage propagates rather than being contained: a malformed interior that
* consumes the closing `}` (say an unterminated block comment) extends the
* interpolation past it, editor-style.
*
* @module
*/
const T_COMMENT = token_type('comment');
const T_HASHBANG = token_type('hashbang', 'comment');
const T_STRING = token_type('string');
const T_STRING_PROPERTY = token_type('string_property', 'property');
const T_TEMPLATE_STRING = token_type('template_string');
const T_TEMPLATE_PUNCTUATION = token_type('template_punctuation', 'string');
const T_INTERPOLATION = token_type('interpolation');
const T_INTERPOLATION_PUNCTUATION = token_type('interpolation_punctuation', 'punctuation');
const T_REGEX = token_type('regex');
const T_REGEX_DELIMITER = token_type('regex_delimiter');
const T_REGEX_SOURCE = token_type('regex_source', 'lang_regex');
const T_REGEX_FLAGS = token_type('regex_flags');
const T_KEYWORD = token_type('keyword');
const T_SPECIAL_KEYWORD = token_type('special_keyword');
const T_IMPORT_TYPE_KEYWORD = token_type('import_type_keyword', 'special_keyword');
const T_CLASS_NAME = token_type('class_name');
const T_TYPE_NAME = token_type('type_name', 'class_name');
const T_TYPE_ASSERTION = token_type('type_assertion', 'class_name');
const T_FUNCTION = token_type('function');
const T_FUNCTION_VARIABLE = token_type('function_variable', 'function');
const T_GENERIC_FUNCTION = token_type('generic_function');
const T_GENERIC = token_type('generic', 'class_name');
const T_BUILTIN = token_type('builtin');
const T_BOOLEAN = token_type('boolean');
const T_NUMBER = token_type('number');
const T_OPERATOR = token_type('operator');
const T_PUNCTUATION = token_type('punctuation');
const T_CONSTANT = token_type('constant');
const T_CAPITALIZED = token_type('capitalized_identifier', 'class_name');
const T_DECORATOR = token_type('decorator');
const T_AT = token_type('at', 'operator');
const T_DECORATOR_NAME = token_type('function', 'decorator_name');
const T_TYPE_ANNOTATION = token_type('type_annotation');
const T_COLON = token_type(':');
const T_TYPE = token_type('type');
// word classification kinds
const K_KEYWORD = 1; // unconditional keyword
const K_SPECIAL = 2; // unconditional special_keyword
const K_TS = 3; // ts-only unconditional keyword
const K_ASYNC = 4; // keyword before `function`/`*`/`(`/ident
const K_GET_SET = 5; // keyword before ident/`#`/`[`
const K_ASSERT = 6; // keyword before `{`
const K_TYPE_WORD = 7; // `type` — import_type_keyword or keyword before ident/`{`/`*`
const K_TS_COND = 8; // ts keyword before ident/`{`
const K_BOOLEAN = 9;
const K_NUMBER_WORD = 10; // NaN/Infinity
const WORDS: Map<string, number> = words_map(
[
K_KEYWORD,
'class const debugger delete enum extends function implements in instanceof interface let ' +
'new null of package private protected public static super this typeof undefined var void with'
],
[
K_SPECIAL,
'as await break case catch continue default do else export finally for from if import ' +
'return switch throw try while yield'
],
[K_TS, 'abstract declare is keyof readonly require satisfies'],
[K_TS_COND, 'asserts infer module namespace'],
[K_ASYNC, 'async'],
[K_GET_SET, 'get set'],
[K_ASSERT, 'assert'],
[K_TYPE_WORD, 'type'],
[K_BOOLEAN, 'true false'],
[K_NUMBER_WORD, 'NaN Infinity']
);
// keywords that put the lexer in a class-name context for the next identifier
const CLASS_CTX_WORDS: Set<string> = new Set([
'class',
'extends',
'implements',
'instanceof',
'interface',
'new',
'type'
]);
// keywords after which the next identifier is a type assertion
const AS_WORDS: Set<string> = new Set(['as', 'satisfies']);
const IMPORT_WORDS: Set<string> = new Set(['import', 'export']);
// value-like keywords — division follows, not a regex literal
const VALUE_WORDS: Set<string> = new Set(['this', 'super', 'null', 'undefined']);
// lowercase-only builtins are reachable — capitalized ones are claimed by
// `capitalized_identifier` first in the classification order
const BUILTIN_WORDS: Set<string> = new Set([
'Array',
'Function',
'Promise',
'any',
'boolean',
'console',
'never',
'number',
'string',
'symbol',
'unknown'
]);
// previous-significant-token categories, for regex-vs-division and contexts
const P_NONE = 0; // start / after operator, `{`, `(`, `[`, `,`, `;` — regex allowed
const P_VALUE = 1; // after a value — `/` is division
const P_DOT = 2; // after `.` member access — next word is a property, not a keyword
// bounded lookahead for heuristic scans (generics, annotations, arrow params)
const MAX_SCAN = 600;
/**
* Monotonic next-occurrence caches for the heuristic-scan prechecks. Each
* bounded scan can only succeed if its success char (`=` for type
* annotations, `>` for generics, `)` for arrow params) occurs within its
* `MAX_SCAN` window, so a cached native `indexOf` probe skips scans that
* cannot succeed. The caches advance monotonically through the document, so
* total probe work is O(n) — this is what keeps colon/angle/paren-dense
* pathological inputs linear instead of paying `MAX_SCAN` per occurrence.
*/
interface TsScanCache {
next_eq: number;
next_gt: number;
next_rparen: number;
}
const create_ts_scan_cache = (): TsScanCache => ({
next_eq: -1,
next_gt: -1,
next_rparen: -1
});
/**
* Scans a `'` or `"` string from `i`, returning the exclusive end.
* Handles escapes and line continuations; unterminated stops at the newline.
*/
const scan_ts_string = (text: string, from: number, end: number, quote: number): number => {
let i = from + 1;
while (i < end) {
const c = text.charCodeAt(i);
if (c === 92) {
// escape; a `\` before a newline continues the string
i += text.charCodeAt(i + 1) === 13 && text.charCodeAt(i + 2) === 10 ? 3 : 2;
} else if (c === quote) {
return i + 1;
} else if (c === 10 || c === 13) {
return i;
} else {
i++;
}
}
return end;
};
/**
* Scans a numeric literal from `i` (at a digit, or `.` before a digit),
* returning the exclusive end. Handles hex/binary/octal, `_` separators,
* exponents, and bigint `n` suffixes.
*
* The per-call closures are a measured exception to the top-level-functions
* rule: V8 inlines them into specialized loops inside this function, and
* hoisted top-level variants (both a param'd helper and a decimal-specialized
* one) run ~1.2x slower on number-dense input.
*/
const scan_ts_number = (text: string, i: number, end: number): number => {
const scan_digits = (from: number, is_wanted: (c: number) => boolean): number => {
let j = from;
while (j < end) {
const c = text.charCodeAt(j);
if (is_wanted(c) || (c === 95 && is_wanted(text.charCodeAt(j + 1)))) j++;
else break;
}
return j;
};
const is_hex = (c: number): boolean =>
(c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70);
const is_binary = (c: number): boolean => c === 48 || c === 49;
const is_octal = (c: number): boolean => c >= 48 && c <= 55;
if (text.charCodeAt(i) === 48) {
const c2 = text.charCodeAt(i + 1);
if (c2 === 120 || c2 === 88) {
let j = scan_digits(i + 2, is_hex);
if (text.charCodeAt(j) === 110) j++; // n
return j;
}
if (c2 === 98 || c2 === 66) {
let j = scan_digits(i + 2, is_binary);
if (text.charCodeAt(j) === 110) j++;
return j;
}
if (c2 === 111 || c2 === 79) {
let j = scan_digits(i + 2, is_octal);
if (text.charCodeAt(j) === 110) j++;
return j;
}
}
let j = scan_digits(i, is_digit);
let is_integer = true;
if (text.charCodeAt(j) === 46 && is_digit(text.charCodeAt(j + 1))) {
is_integer = false;
j = scan_digits(j + 1, is_digit);
}
const e = text.charCodeAt(j);
if (e === 101 || e === 69) {
let k = j + 1;
const sign = text.charCodeAt(k);
if (sign === 43 || sign === 45) k++;
if (is_digit(text.charCodeAt(k))) {
j = scan_digits(k, is_digit);
is_integer = false;
}
}
if (is_integer && text.charCodeAt(j) === 110) j++; // bigint
return j;
};
/**
* Finds the matching `>` for the `<` at `i` (generic argument lists), skipping
* strings. Bounded by `MAX_SCAN`; returns -1 when unbalanced. Rejects at `;`
* and at any unbalanced `)`/`}`/`]` — a generic argument list can contain
* balanced groups (object types, tuples, parenthesized function types) but
* never a stray closer, and without this reject the scan would run across
* statement or interpolation boundaries and misread a later `>` as the match
* (e.g. two comparisons in `a < b} ${c > (d)`).
*/
const scan_balanced_angle = (text: string, i: number, end: number, cache: TsScanCache): number => {
const limit = i + MAX_SCAN < end ? i + MAX_SCAN : end;
// success needs a `>` within the window — skip the scan when there is none
cache.next_gt = advance_probe(text, cache.next_gt, i + 1, '>');
if (cache.next_gt >= limit) return -1;
let depth = 0;
let group = 0; // combined `(`/`{`/`[` nesting — valid input nests properly
let j = i;
while (j < limit) {
const c = text.charCodeAt(j);
if (c === 60) {
depth++;
j++;
} else if (c === 62) {
depth--;
if (depth === 0) return j;
j++;
} else if (c === 34 || c === 39 || c === 96) {
j = skip_quoted(text, j, end, c);
} else if (c === 40 || c === 123 || c === 91) {
group++;
j++;
} else if (c === 41 || c === 125 || c === 93) {
if (group === 0) return -1;
group--;
j++;
} else if (c === 59) {
return -1; // `;` never appears in a generic argument list
} else {
j++;
}
}
return -1;
};
/**
* Finds the matching `)` for the `(` at `i`, skipping strings and nested
* parens. Bounded by `MAX_SCAN`; returns -1 when unbalanced. Rejects at any
* unbalanced `}`/`]` — a parameter list can contain balanced destructuring
* groups but never a stray closer, so one marks a boundary the scan must not
* cross.
*/
const scan_balanced_parens = (text: string, i: number, end: number, cache: TsScanCache): number => {
const limit = i + MAX_SCAN < end ? i + MAX_SCAN : end;
// success needs a `)` within the window — skip the scan when there is none
cache.next_rparen = advance_probe(text, cache.next_rparen, i + 1, ')');
if (cache.next_rparen >= limit) return -1;
let depth = 0;
let group = 0; // combined `{`/`[` nesting — valid input nests properly
let j = i;
while (j < limit) {
const c = text.charCodeAt(j);
if (c === 40) {
depth++;
j++;
} else if (c === 41) {
depth--;
if (depth === 0) return j;
j++;
} else if (c === 34 || c === 39 || c === 96) {
j = skip_quoted(text, j, end, c);
} else if (c === 123 || c === 91) {
group++;
j++;
} else if (c === 125 || c === 93) {
if (group === 0) return -1;
group--;
j++;
} else {
j++;
}
}
return -1;
};
/**
* Detects whether an identifier is a function-valued variable: followed by
* `=` or `:` (`after` is the identifier's next significant position, already
* past whitespace), then optional `async`, then a `function` keyword,
* `(params) =>`, or `param =>`.
*/
const is_function_variable = (
text: string,
after: number,
end: number,
cache: TsScanCache
): boolean => {
const c = text.charCodeAt(after);
if (c === 61) {
// `=` — but not `==`/`=>`/`===`
const c2 = text.charCodeAt(after + 1);
if (c2 === 61 || c2 === 62) return false;
} else if (c !== 58) {
return false;
}
let j = skip_space(text, after + 1, end);
// optional `async`
if (text.startsWith('async', j)) {
const after = j + 5;
if (!is_ident(text.charCodeAt(after))) j = skip_space(text, after, end);
}
if (text.startsWith('function', j) && !is_ident(text.charCodeAt(j + 8))) return true;
const c3 = text.charCodeAt(j);
if (c3 === 40) {
// `(params)` then optional `: type` then `=>`
const close = scan_balanced_parens(text, j, end, cache);
if (close === -1) return false;
let k = skip_space(text, close + 1, end);
if (text.charCodeAt(k) === 58) {
// return type annotation — scan to `=>` before a terminator
const limit = k + MAX_SCAN < end ? k + MAX_SCAN : end;
k++;
while (k < limit) {
const c4 = text.charCodeAt(k);
if (c4 === 61 && text.charCodeAt(k + 1) === 62) break;
if (c4 === 59 || c4 === 61) return false;
k++;
}
}
return text.charCodeAt(k) === 61 && text.charCodeAt(k + 1) === 62;
}
if (is_ident_start(c3)) {
// `param =>`
const param_end = scan_ident(text, j, end);
const k = skip_space(text, param_end, end);
return text.charCodeAt(k) === 61 && text.charCodeAt(k + 1) === 62;
}
return false;
};
/**
* Heuristic for `: type =` annotations: from the `:` at `i`, scans over a type
* expression with balanced `<>`/`[]`/`{}`/`()`, succeeding at a top-level `=`
* (not `==`/`=>`). Returns the exclusive end of the type text, or -1.
*/
const scan_type_annotation = (text: string, i: number, end: number, cache: TsScanCache): number => {
const limit = i + MAX_SCAN < end ? i + MAX_SCAN : end;
// success needs a top-level `=` within the window — skip the scan when
// there is no `=` at all
cache.next_eq = advance_probe(text, cache.next_eq, i + 1, '=');
if (cache.next_eq >= limit) return -1;
let angle = 0;
let square = 0;
let j = i + 1;
while (j < limit) {
const c = text.charCodeAt(j);
if (c === 61) {
// `=`
if (angle === 0 && square === 0) {
const c2 = text.charCodeAt(j + 1);
if (c2 === 61 || c2 === 62) return -1;
const c0 = text.charCodeAt(j - 1);
if (c0 === 33 || c0 === 60 || c0 === 62) return -1; // != <= >=
return j;
}
j++;
} else if (c === 60) {
angle++;
j++;
} else if (c === 62) {
if (angle === 0) return -1;
angle--;
j++;
} else if (c === 91) {
square++;
j++;
} else if (c === 93) {
if (square === 0) return -1;
square--;
j++;
} else if (
angle === 0 &&
square === 0 &&
(c === 59 || c === 44 || c === 123 || c === 125 || c === 40 || c === 41)
) {
// top-level statement/grouping chars end the candidate type text —
// object/function types are not annotation targets here, which keeps
// the scan from running away across statement boundaries
return -1;
} else if (c === 34 || c === 39) {
j = skip_quoted(text, j, end, c);
} else {
j++;
}
}
return -1;
};
/**
* Scans a multi-char operator at `i`, returning its length.
*/
const scan_operator = (text: string, i: number, end: number): number => {
const c = text.charCodeAt(i);
const c2 = i + 1 < end ? text.charCodeAt(i + 1) : 0;
const c3 = i + 2 < end ? text.charCodeAt(i + 2) : 0;
const c4 = i + 3 < end ? text.charCodeAt(i + 3) : 0;
switch (c) {
case 43: // +
return c2 === 43 || c2 === 61 ? 2 : 1;
case 45: // -
return c2 === 45 || c2 === 61 ? 2 : 1;
case 42: // *
if (c2 === 42) return c3 === 61 ? 3 : 2;
return c2 === 61 ? 2 : 1;
case 37: // %
return c2 === 61 ? 2 : 1;
case 38: // &
if (c2 === 38) return c3 === 61 ? 3 : 2;
return c2 === 61 ? 2 : 1;
case 124: // |
if (c2 === 124) return c3 === 61 ? 3 : 2;
return c2 === 61 ? 2 : 1;
case 94: // ^
return c2 === 61 ? 2 : 1;
case 61: // =
if (c2 === 61) return c3 === 61 ? 3 : 2;
return c2 === 62 ? 2 : 1; // =>
case 33: // !
if (c2 === 61) return c3 === 61 ? 3 : 2;
return 1;
case 60: // <
if (c2 === 60) return c3 === 61 ? 3 : 2;
return c2 === 61 ? 2 : 1;
case 62: // >
if (c2 === 62) {
if (c3 === 62) return c4 === 61 ? 4 : 3;
return c3 === 61 ? 3 : 2;
}
return c2 === 61 ? 2 : 1;
case 63: // ?
if (c2 === 63) return c3 === 61 ? 3 : 2;
return c2 === 46 ? 2 : 1; // ?.
case 47: // /
return c2 === 61 ? 2 : 1;
default:
return 1; // ~ :
}
};
// Explicit-stack driver for nested constructs (template interpolations,
// generic argument lists, and `: type` annotations). Each construct pushes a
// frame rather than recursing on the JS call stack, so arbitrarily deep input
// tokenizes fully without overflowing — the deep-nesting tests exercise this
// to thousands of levels. Frames are pooled across a single `lex_ts` run
// (`stack` only grows, never shrinks) to keep deep nesting allocation-free
// after warmup.
const F_WINDOW = 0; // a window scan in progress
const F_TEMPLATE = 1; // a template-literal body scan in progress
// how a completed frame finalizes into the frame beneath it
const R_ROOT = 0; // top-level window — nothing beneath it
const R_INTERP = 1; // `${…}` body → close the interpolation, resume its template
const R_CLASS_GENERIC = 2; // `Foo<…>` in a class-name chain → advance the window
const R_GENERIC_CALL = 3; // `foo<…>(…)` args → close the generic, advance
const R_TYPE_ANNO = 4; // `: type =` body → close the type, advance past it
const R_TEMPLATE = 5; // a template literal in a window → advance past it
/**
* One suspended scan on the explicit stack. A window frame carries the full
* per-window scan state (cursor, previous-token category, contexts); a
* template frame carries its body-scan cursor. `ret`/`ret_a`/`ret_b` describe
* how the frame finalizes into the one beneath it when it completes.
*/
interface TsFrame {
kind: number;
to: number;
type_mode: boolean;
/** Scan cursor: the window position, or the template body position. */
i: number;
prev: number;
prev_code: number;
class_ctx: boolean;
as_ctx: boolean;
import_ctx: boolean;
/** Template only: start of the pending literal chunk. */
chunk_start: number;
/**
* Self-discovery terminator for the window: the char code that ends it
* (`}` for `${…}` interpolation bodies), or 0 when the window's end was
* known at push time. The frame finds its own end during real tokenization
* — strings, comments, and regexes consume their delimiter chars inside
* their token scans, so only a real closing delimiter terminates.
*/
term: number;
/**
* Open-delimiter depth for `term` windows. Nested constructs push their own
* frames, so this only counts the frame's own unclosed `{`s; the `term`
* char that would bring it to 0 terminates the window (recorded in
* `ret_a`).
*/
depth: number;
ret: number;
ret_a: number;
ret_b: number;
}
interface TsMachine {
l: Lexer;
cache: TsScanCache;
/** Frame pool doubling as the stack; frames above `sp` are dormant. */
stack: Array<TsFrame>;
sp: number;
}
const create_ts_frame = (): TsFrame => ({
kind: F_WINDOW,
to: 0,
type_mode: false,
i: 0,
prev: P_NONE,
prev_code: 0,
class_ctx: false,
as_ctx: false,
import_ctx: false,
chunk_start: 0,
term: 0,
depth: 0,
ret: R_ROOT,
ret_a: 0,
ret_b: 0
});
/**
* Pushes a window frame scanning `[from, to)`, reusing the pooled slot at the
* stack top. `ret`/`ret_a`/`ret_b` are applied when it completes. A nonzero
* `term` makes the window self-discovering: it terminates at the `term` char
* that brings `depth` to 0, writing the discovered position to `ret_a`.
*/
const mac_push_window = (
mac: TsMachine,
from: number,
to: number,
type_mode: boolean,
ret: number,
ret_a: number,
ret_b: number,
term: number,
depth: number
): void => {
const { stack, sp } = mac;
let f = stack[sp];
if (f === undefined) {
f = create_ts_frame();
stack[sp] = f;
}
f.kind = F_WINDOW;
f.to = to;
f.type_mode = type_mode;
f.i = from;
f.prev = P_NONE;
f.prev_code = 0;
f.class_ctx = false;
f.as_ctx = false;
f.import_ctx = false;
f.term = term;
f.depth = depth;
f.ret = ret;
f.ret_a = ret_a;
f.ret_b = ret_b;
mac.sp = sp + 1;
};
/**
* Pushes a template-literal frame resuming at the `${…}` found at `from`. The
* caller emitted the literal's opening events and scanned the leading chunk
* (which starts at `chunk_start`, past the opening backtick); the frame always
* finalizes by advancing the window beneath it past the literal.
*/
const mac_push_template = (mac: TsMachine, from: number, chunk_start: number, to: number): void => {
const { stack, sp } = mac;
let f = stack[sp];
if (f === undefined) {
f = create_ts_frame();
stack[sp] = f;
}
f.kind = F_TEMPLATE;
f.to = to;
f.i = from;
f.chunk_start = chunk_start;
f.ret = R_TEMPLATE;
f.ret_a = 0;
f.ret_b = 0;
mac.sp = sp + 1;
};
/**
* Scans a template-literal body from `from` (past the opening backtick).
* Returns the closing backtick's index, `to` when unterminated, or the bitwise
* complement of the position of a `${…}` interpolation — the fast path lets
* interpolation-free literals complete without a frame.
*/
const scan_ts_template_body = (text: string, from: number, to: number): number => {
let j = from;
while (j < to) {
const c = text.charCodeAt(j);
if (c === 92) {
j += 2;
} else if (c === 96) {
return j;
} else if (c === 36 && j + 1 < to && text.charCodeAt(j + 1) === 123) {
return ~j;
} else {
j++;
}
}
return to;
};
/**
* Runs (or resumes) a template-literal frame: scans literal chunks until the
* closing backtick or a `${…}` interpolation (the opening events were emitted
* before the push). An interpolation pushes a value-mode window frame and
* returns `false`; the driver's `R_INTERP` finalize closes the interpolation
* and resumes this frame past it. Returns `true` once the literal is complete
* (closed, or extended to the window end when unterminated).
*/
const run_ts_template = (mac: TsMachine, frame: TsFrame): boolean => {
const l = mac.l;
const { text } = l;
const to = frame.to;
let j = frame.i;
const chunk_start = frame.chunk_start;
while (j < to) {
const c = text.charCodeAt(j);
if (c === 92) {
j += 2;
} else if (c === 96) {
l.leaf(T_STRING, chunk_start, j);
l.leaf(T_TEMPLATE_PUNCTUATION, j, j + 1);
j++;
l.close(j); // close the template container
frame.i = j;
return true;
} else if (c === 36 && j + 1 < to && text.charCodeAt(j + 1) === 123) {
l.leaf(T_STRING, chunk_start, j);
l.open(T_INTERPOLATION, j);
l.leaf(T_INTERPOLATION_PUNCTUATION, j, j + 2);
// the interpolation body lexes in value mode and discovers its own
// closing `}` (terminator mode); the driver's R_INTERP finalize
// closes the interpolation and resumes this frame past it
mac_push_window(mac, j + 2, to, false, R_INTERP, -1, 0, 125, 1);
return false;
} else {
j++;
}
}
if (j > to) j = to;
l.leaf(T_STRING, chunk_start, j);
l.close(j);
frame.i = j;
return true;
};
/**
* Runs (or resumes) a window frame — the core per-token scan. `frame.type_mode`
* switches capitalized identifiers to `type_name` (generics, type annotations).
* Returns `true` when the window completes — fully consumed, or terminated at
* its self-discovered `frame.term` delimiter (position recorded in
* `frame.ret_a`) — or `false` after pushing a nested frame (interpolation,
* generics, or type annotation), which the driver runs before resuming this
* frame.
*/
const run_ts_window = (mac: TsMachine, frame: TsFrame): boolean => {
const l = mac.l;
const cache = mac.cache;
const { text } = l;
const to = frame.to;
const type_mode = frame.type_mode;
const term = frame.term;
let i = frame.i;
let prev = frame.prev;
let prev_code = frame.prev_code; // last significant punctuation char, for string-property detection
let class_ctx = frame.class_ctx;
let as_ctx = frame.as_ctx;
let import_ctx = frame.import_ctx;
while (i < to) {
const c = text.charCodeAt(i);
if (is_space(c)) {
i++;
continue;
}
// identifiers (including `#private`)
if (is_ident_start(c) || (c === 35 && i + 1 < to && is_ident_start(text.charCodeAt(i + 1)))) {
const start = i;
const ident_end = scan_ident(text, c === 35 ? i + 1 : i, to);
const was_class_ctx = class_ctx;
const was_as_ctx = as_ctx;
const was_import_ctx = import_ctx;
const was_dot = prev === P_DOT;
class_ctx = as_ctx = import_ctx = false;
prev = P_VALUE;
prev_code = 0;
i = ident_end;
const word = text.slice(start, ident_end);
const kind = c === 35 || was_dot ? undefined : WORDS.get(word);
if (was_class_ctx && kind === undefined && c !== 35) {
// class-name chain: `Foo`, `a.b.Foo`, optionally with generics
l.leaf(T_CLASS_NAME, start, ident_end);
while (i + 1 < to && text.charCodeAt(i) === 46 && is_ident_start(text.charCodeAt(i + 1))) {
l.leaf(T_PUNCTUATION, i, i + 1);
const seg_end = scan_ident(text, i + 1, to);
l.leaf(T_CLASS_NAME, i + 1, seg_end);
i = seg_end;
}
const angle_start = skip_space(text, i, to);
if (text.charCodeAt(angle_start) === 60) {
const angle_end = scan_balanced_angle(text, angle_start, to, cache);
if (angle_end !== -1) {
frame.i = i;
frame.prev = prev;
frame.prev_code = prev_code;
frame.class_ctx = class_ctx;
frame.as_ctx = as_ctx;
frame.import_ctx = import_ctx;
mac_push_window(
mac,
angle_start,
angle_end + 1,
true,
R_CLASS_GENERIC,
angle_end + 1,
0,
0,
0
);
return false;
}
}
continue;
}
if (was_as_ctx && kind === undefined && c !== 35 && !BUILTIN_WORDS.has(word)) {
// `x as Foo` — but `as unknown`/`as string` keep their builtin type
l.leaf(T_TYPE_ASSERTION, start, ident_end);
continue;
}
// keyword classification (with contextual lookaheads)
if (kind !== undefined) {
let keyword_id = 0;
switch (kind) {
case K_KEYWORD:
keyword_id = T_KEYWORD;
break;
case K_SPECIAL:
keyword_id = T_SPECIAL_KEYWORD;
break;
case K_TS:
keyword_id = T_KEYWORD;
break;
case K_ASYNC: {
const n = text.charCodeAt(skip_space(text, ident_end, to));
if (n === 40 || n === 42 || is_ident_start(n) || Number.isNaN(n)) {
keyword_id = T_KEYWORD;
}
break;
}
case K_GET_SET: {
const n = text.charCodeAt(skip_space(text, ident_end, to));
if (n === 35 || n === 91 || is_ident_start(n) || Number.isNaN(n)) {
keyword_id = T_KEYWORD;
}
break;
}
case K_ASSERT: {
if (text.charCodeAt(skip_space(text, ident_end, to)) === 123) {
keyword_id = T_KEYWORD;
}
break;
}
case K_TYPE_WORD: {
const n = text.charCodeAt(skip_space(text, ident_end, to));
// `import type {…}` / `export type * from …` — a type-only
// import/export modifier, not a type-alias declaration
if (was_import_ctx && (n === 123 || n === 42)) {
l.leaf(T_IMPORT_TYPE_KEYWORD, start, ident_end);
continue;
}
if (n === 123 || n === 42 || is_ident_start(n)) {
keyword_id = T_KEYWORD;
}
break;
}
case K_TS_COND: {
const n = text.charCodeAt(skip_space(text, ident_end, to));
if (n === 123 || is_ident_start(n) || Number.isNaN(n)) {
keyword_id = T_KEYWORD;
}
break;
}
case K_BOOLEAN:
l.leaf(T_BOOLEAN, start, ident_end);
continue;
case K_NUMBER_WORD:
l.leaf(T_NUMBER, start, ident_end);
continue;
}
if (keyword_id !== 0) {
l.leaf(keyword_id, start, ident_end);
if (CLASS_CTX_WORDS.has(word)) class_ctx = true;
if (AS_WORDS.has(word)) as_ctx = true;
if (IMPORT_WORDS.has(word)) import_ctx = true;
if (!VALUE_WORDS.has(word)) prev = P_NONE;
continue;
}
}
// one shared lookahead past the identifier — the classification checks
// below (function-variable, generic call, plain call) all probe the
// same next-significant position
const after_ident = skip_space(text, ident_end, to);
const after_c = text.charCodeAt(after_ident);
// function-valued variables: `f = () => …`, `f: async x => …`
if (!type_mode && c !== 35 && is_function_variable(text, after_ident, to, cache)) {
l.leaf(T_FUNCTION_VARIABLE, start, ident_end);
continue;
}
// SCREAMING_CASE constants, then capitalized identifiers — both
// classified before the call lookahead
if (is_upper(c)) {
let all_caps = true;
for (let k = start + 1; k < ident_end; k++) {
const cc = text.charCodeAt(k);
// `x` only after a digit (hex-ish constants like `A0x`)
if (
!is_upper(cc) &&
cc !== 95 &&
!is_digit(cc) &&
!(cc === 120 && is_digit(text.charCodeAt(k - 1)))
) {
all_caps = false;
break;
}
}
if (type_mode) {
l.leaf(T_TYPE_NAME, start, ident_end);
} else if (all_caps) {
l.leaf(T_CONSTANT, start, ident_end);
} else {
l.leaf(T_CAPITALIZED, start, ident_end);
}
continue;
}
// generic call: `foo<T>(…)`
if (after_c === 60) {
const angle_end = scan_balanced_angle(text, after_ident, to, cache);
if (angle_end !== -1 && text.charCodeAt(skip_space(text, angle_end + 1, to)) === 40) {
l.open(T_GENERIC_FUNCTION, start);
l.leaf(T_FUNCTION, start, ident_end);
l.open(T_GENERIC, after_ident);
frame.i = i;
frame.prev = prev;
frame.prev_code = prev_code;
frame.class_ctx = class_ctx;
frame.as_ctx = as_ctx;
frame.import_ctx = import_ctx;
mac_push_window(
mac,
after_ident,
angle_end + 1,
true,
R_GENERIC_CALL,
angle_end + 1,
0,
0,
0
);
return false;
}
}
// call: `foo(…)` (also `#private(…)`)
if (after_c === 40) {
l.leaf(T_FUNCTION, start, ident_end);
continue;
}
if (kind === undefined && !was_dot && c !== 35 && BUILTIN_WORDS.has(word)) {
l.leaf(T_BUILTIN, start, ident_end);
continue;
}
// plain identifier — no token
continue;
}
// `/` — comment, regex literal, or division
if (c === 47) {
const c2 = i + 1 < to ? text.charCodeAt(i + 1) : 0;
if (c2 === 47) {
const line_end = scan_to_line_end(text, i, to);
l.leaf(T_COMMENT, i, line_end);
i = line_end;
continue; // comments are transparent — contexts survive
}
if (c2 === 42) {
const close = text.indexOf('*/', i + 2);
const comment_end = close === -1 || close + 2 > to ? to : close + 2;
l.leaf(T_COMMENT, i, comment_end);
i = comment_end;
continue;
}
class_ctx = as_ctx = import_ctx = false;
if (prev !== P_VALUE && prev !== P_DOT) {
// regex literal position
const body_end = scan_regex_body(text, i, to);
if (body_end !== -1) {
let flags_end = body_end + 1;
while (flags_end < to) {
const f = text.charCodeAt(flags_end);
if (f >= 97 && f <= 122) flags_end++;
else break;
}
l.open(T_REGEX, i);
l.leaf(T_REGEX_DELIMITER, i, i + 1);
l.leaf(T_REGEX_SOURCE, i + 1, body_end);
l.leaf(T_REGEX_DELIMITER, body_end, body_end + 1);
if (flags_end > body_end + 1) l.leaf(T_REGEX_FLAGS, body_end + 1, flags_end);
l.close(flags_end);
i = flags_end;
prev = P_VALUE;
prev_code = 0;
continue;
}
}
const op_len = scan_operator(text, i, to);