-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
7956 lines (6788 loc) · 215 KB
/
parser.go
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
package parser
import (
"github.com/amasad/esparse/ast"
"github.com/amasad/esparse/lexer"
"github.com/amasad/esparse/logging"
"fmt"
"math"
"reflect"
"strings"
"unsafe"
)
// This parser does two passes:
//
// 1. Parse the source into an AST, create the scope tree, and declare symbols.
//
// 2. Visit each node in the AST, bind identifiers to declared symbols, do
// constant folding, substitute compile-time variable definitions, and
// lower certain syntactic constructs as appropriate given the language
// target.
//
// So many things have been put in so few passes because we want to minimize
// the number of full-tree passes to improve performance. However, we need
// to have at least two separate passes to handle variable hoisting. See the
// comment about scopesInOrder below for more information.
type parser struct {
log logging.Log
source logging.Source
lexer lexer.Lexer
importPaths []ast.ImportPath
omitWarnings bool
allowIn bool
hasTopLevelReturn bool
currentFnOpts fnOpts
target LanguageTarget
ts TypeScriptOptions
jsx JSXOptions
latestReturnHadSemicolon bool
allocatedNames []string
latestArrowArgLoc ast.Loc
currentScope *ast.Scope
symbols []ast.Symbol
tsUseCounts []uint32
exportsRef ast.Ref
requireRef ast.Ref
moduleRef ast.Ref
// These are for TypeScript
exportEqualsStmt *ast.Stmt
shouldFoldNumericConstants bool
enclosingNamespaceRef *ast.Ref
emittedNamespaceVars map[ast.Ref]bool
isExportedInsideNamespace map[ast.Ref]ast.Ref
knownEnumValues map[ast.Ref]map[string]float64
// These are for handling ES6 imports and exports
importItemsForNamespace map[ast.Ref]map[string]ast.Ref
isImportItem map[ast.Ref]bool
exportAliases map[string]bool
// The parser does two passes and we need to pass the scope tree information
// from the first pass to the second pass. That's done by tracking the calls
// to pushScopeForParsePass() and popScope() during the first pass in
// scopesInOrder.
//
// Then, when the second pass calls pushScopeForVisitPass() and popScope(),
// we consume entries from scopesInOrder and make sure they are in the same
// order. This way the second pass can efficiently use the same scope tree
// as the first pass without having to attach the scope tree to the AST.
//
// We need to split this into two passes because the pass that declares the
// symbols must be separate from the pass that binds identifiers to declared
// symbols to handle declaring a hoisted "var" symbol in a nested scope and
// binding a name to it in a parent or sibling scope.
scopesInOrder []scopeOrder
// These properties are for the visit pass, which runs after the parse pass.
// The visit pass binds identifiers to declared symbols, does constant
// folding, substitutes compile-time variable definitions, and lowers certain
// syntactic constructs as appropriate.
mangleSyntax bool
isBundling bool
tryBodyCount int
isThisCaptured bool
callTarget ast.E
typeofTarget ast.E
moduleScope *ast.Scope
isControlFlowDead bool
tempRefs []ast.Ref // Temporary variables used for lowering
identifierDefines map[string]DefineFunc
dotDefines map[string]dotDefine
}
const (
locModuleScope = -1
// Offset ScopeFunction for EFunction to come after ScopeFunctionName
locOffsetFunctionExpr = 1
)
type scopeOrder struct {
loc ast.Loc
scope *ast.Scope
}
type fnOpts struct {
isOutsideFn bool
allowAwait bool
allowYield bool
// In TypeScript, forward declarations of functions have no bodies
allowMissingBodyForTypeScript bool
}
func isJumpStatement(data ast.S) bool {
switch data.(type) {
case *ast.SBreak, *ast.SContinue, *ast.SReturn, *ast.SThrow:
return true
}
return false
}
func hasNoSideEffects(data ast.E) bool {
switch data.(type) {
case *ast.ENull, *ast.EUndefined, *ast.EBoolean, *ast.ENumber, *ast.EBigInt,
*ast.EString, *ast.EThis, *ast.ERegExp, *ast.EFunction, *ast.EArrow:
return true
}
return false
}
func toBooleanWithoutSideEffects(data ast.E) (bool, bool) {
switch e := data.(type) {
case *ast.ENull, *ast.EUndefined:
return false, true
case *ast.EBoolean:
return e.Value, true
case *ast.ENumber:
return e.Value != 0 && !math.IsNaN(e.Value), true
case *ast.EBigInt:
return e.Value != "0", true
case *ast.EString:
return len(e.Value) > 0, true
case *ast.EFunction, *ast.EArrow:
return true, true
}
return false, false
}
func toNumberWithoutSideEffects(data ast.E) (float64, bool) {
switch e := data.(type) {
case *ast.ENull:
return 0, true
case *ast.EUndefined:
return math.NaN(), true
case *ast.EBoolean:
if e.Value {
return 1, true
} else {
return 0, true
}
case *ast.ENumber:
return e.Value, true
}
return 0, false
}
func typeofWithoutSideEffects(data ast.E) (string, bool) {
switch data.(type) {
case *ast.ENull:
return "object", true
case *ast.EUndefined:
return "undefined", true
case *ast.EBoolean:
return "boolean", true
case *ast.ENumber:
return "number", true
case *ast.EBigInt:
return "bigint", true
case *ast.EString:
return "string", true
case *ast.EFunction, *ast.EArrow:
return "function", true
}
return "", false
}
func checkEqualityIfNoSideEffects(left ast.E, right ast.E) (bool, bool) {
switch l := left.(type) {
case *ast.ENull:
if _, ok := right.(*ast.ENull); ok {
return true, true
}
case *ast.EUndefined:
if _, ok := right.(*ast.EUndefined); ok {
return true, true
}
case *ast.EBoolean:
if r, ok := right.(*ast.EBoolean); ok {
return l.Value == r.Value, true
}
case *ast.ENumber:
if r, ok := right.(*ast.ENumber); ok {
return l.Value == r.Value, true
}
case *ast.EBigInt:
if r, ok := right.(*ast.EBigInt); ok {
return l.Value == r.Value, true
}
case *ast.EString:
if r, ok := right.(*ast.EString); ok {
lv := l.Value
rv := r.Value
if len(lv) != len(rv) {
return false, true
}
for i := 0; i < len(lv); i++ {
if lv[i] != rv[i] {
return false, true
}
}
return true, true
}
}
return false, false
}
func (p *parser) pushScopeForParsePass(kind ast.ScopeKind, loc ast.Loc) int {
parent := p.currentScope
scope := &ast.Scope{
Kind: kind,
Parent: parent,
Members: make(map[string]ast.Ref),
LabelRef: ast.InvalidRef,
}
if parent != nil {
parent.Children = append(parent.Children, scope)
}
p.currentScope = scope
// Enforce that scope locations are strictly increasing to help catch bugs
// where the pushed scopes are mistmatched between the first and second passes
if len(p.scopesInOrder) > 0 {
prevStart := p.scopesInOrder[len(p.scopesInOrder)-1].loc.Start
if prevStart >= loc.Start {
panic(fmt.Sprintf("Scope location %d must be greater than %d", loc.Start, prevStart))
}
}
// Remember the length in case we call popAndDiscardScope() later
scopeIndex := len(p.scopesInOrder)
p.scopesInOrder = append(p.scopesInOrder, scopeOrder{loc, scope})
return scopeIndex
}
func (p *parser) popScope() {
p.currentScope = p.currentScope.Parent
}
func (p *parser) popAndDiscardScope(scopeIndex int) {
// Move up to the parent scope
child := p.currentScope
parent := child.Parent
p.currentScope = parent
// Truncate the scope order where we started to pretend we never saw this scope
p.scopesInOrder = p.scopesInOrder[:scopeIndex]
// Remove the last child from the parent scope
last := len(parent.Children) - 1
if parent.Children[last] != child {
panic("Internal error")
}
parent.Children = parent.Children[:last]
}
func (p *parser) newSymbol(kind ast.SymbolKind, name string) ast.Ref {
ref := ast.Ref{p.source.Index, uint32(len(p.symbols))}
p.symbols = append(p.symbols, ast.Symbol{
Kind: kind,
Name: name,
Link: ast.InvalidRef,
})
if p.ts.Parse {
p.tsUseCounts = append(p.tsUseCounts, 0)
}
return ref
}
type mergeResult int
const (
mergeForbidden = iota
mergeReplaceWithNew
mergeKeepExisting
)
func canMergeSymbols(existing ast.SymbolKind, new ast.SymbolKind) mergeResult {
if existing == ast.SymbolUnbound {
return mergeReplaceWithNew
}
// "import {Foo} from 'bar'; class Foo {}"
if existing == ast.SymbolTSImport {
return mergeReplaceWithNew
}
// "enum Foo {} enum Foo {}"
// "namespace Foo { ... } enum Foo {}"
if new == ast.SymbolTSEnum && (existing == ast.SymbolTSEnum || existing == ast.SymbolTSNamespace) {
return mergeReplaceWithNew
}
// "namespace Foo { ... } namespace Foo { ... }"
// "function Foo() {} namespace Foo { ... }"
// "enum Foo {} namespace Foo { ... }"
if new == ast.SymbolTSNamespace && (existing == ast.SymbolTSNamespace ||
existing == ast.SymbolHoistedFunction || existing == ast.SymbolTSEnum || existing == ast.SymbolClass) {
return mergeKeepExisting
}
// "var foo; var foo;"
// "var foo; function foo() {}"
// "function foo() {} var foo;"
if new.IsHoisted() && existing.IsHoisted() {
return mergeKeepExisting
}
return mergeForbidden
}
func (p *parser) declareSymbol(kind ast.SymbolKind, loc ast.Loc, name string) ast.Ref {
scope := p.currentScope
// Check for collisions that would prevent to hoisting "var" symbols up to the enclosing function scope
if kind.IsHoisted() {
for scope.Kind != ast.ScopeEntry {
if existing, ok := scope.Members[name]; ok {
symbol := p.symbols[existing.InnerIndex]
switch symbol.Kind {
case ast.SymbolUnbound, ast.SymbolHoisted, ast.SymbolHoistedFunction:
// Continue on to the parent scope
case ast.SymbolCatchIdentifier:
// This is a weird special case. Silently reuse this symbol.
return existing
default:
r := lexer.RangeOfIdentifier(p.source, loc)
p.log.AddRangeError(p.source, r, fmt.Sprintf("%q has already been declared", name))
return existing
}
}
scope = scope.Parent
}
}
// Allocate a new symbol
ref := p.newSymbol(kind, name)
// Check for a collision in the declaring scope
if existing, ok := scope.Members[name]; ok {
symbol := p.symbols[existing.InnerIndex]
switch canMergeSymbols(symbol.Kind, kind) {
case mergeForbidden:
r := lexer.RangeOfIdentifier(p.source, loc)
p.log.AddRangeError(p.source, r, fmt.Sprintf("%q has already been declared", name))
return existing
case mergeKeepExisting:
ref = existing
case mergeReplaceWithNew:
p.symbols[existing.InnerIndex].Link = ref
}
}
// Hoist "var" symbols up to the enclosing function scope
if kind.IsHoisted() {
for s := p.currentScope; s.Kind != ast.ScopeEntry; s = s.Parent {
if existing, ok := s.Members[name]; ok {
symbol := p.symbols[existing.InnerIndex]
if symbol.Kind == ast.SymbolUnbound {
p.symbols[existing.InnerIndex].Link = ref
}
}
s.Members[name] = ref
}
}
// Overwrite this name in the declaring scope
scope.Members[name] = ref
return ref
}
func (p *parser) declareBinding(kind ast.SymbolKind, binding ast.Binding, opts parseStmtOpts) {
switch d := binding.Data.(type) {
case *ast.BMissing:
case *ast.BIdentifier:
name := p.loadNameFromRef(d.Ref)
if !opts.isTypeScriptDeclare {
d.Ref = p.declareSymbol(kind, binding.Loc, name)
if opts.isExport && p.enclosingNamespaceRef == nil {
p.recordExport(binding.Loc, name)
}
}
case *ast.BArray:
for _, i := range d.Items {
p.declareBinding(kind, i.Binding, opts)
}
case *ast.BObject:
for _, property := range d.Properties {
p.declareBinding(kind, property.Value, opts)
}
default:
panic(fmt.Sprintf("Unexpected binding of type %T", binding.Data))
}
}
func (p *parser) recordExport(loc ast.Loc, alias string) {
// This is only an ES6 export if we're not inside a TypeScript namespace
if p.enclosingNamespaceRef == nil {
if p.exportAliases[alias] {
// Warn about duplicate exports
p.log.AddRangeError(p.source, lexer.RangeOfIdentifier(p.source, loc),
fmt.Sprintf("Multiple exports with the same name %q", alias))
} else {
p.exportAliases[alias] = true
}
}
}
func (p *parser) recordUsage(ref ast.Ref) {
// The use count stored in the symbol is used for generating symbol names
// during minification. These counts shouldn't include references inside dead
// code regions since those will be culled.
if !p.isControlFlowDead {
p.symbols[ref.InnerIndex].UseCountEstimate++
}
// The correctness of TypeScript-to-JavaScript conversion relies on accurate
// symbol use counts for the whole file, including dead code regions. This is
// tracked separately in a parser-only data structure.
if p.ts.Parse {
p.tsUseCounts[ref.InnerIndex]++
}
}
func (p *parser) addError(loc ast.Loc, text string) {
p.log.AddError(p.source, loc, text)
}
func (p *parser) addRangeError(r ast.Range, text string) {
p.log.AddRangeError(p.source, r, text)
}
// The name is temporarily stored in the ref until the scope traversal pass
// happens, at which point a symbol will be generated and the ref will point
// to the symbol instead.
//
// The scope traversal pass will reconstruct the name using one of two methods.
// In the common case, the name is a slice of the file itself. In that case we
// can just store the slice and not need to allocate any extra memory. In the
// rare case, the name is an externally-allocated string. In that case we store
// an index to the string and use that index during the scope traversal pass.
func (p *parser) storeNameInRef(name string) ast.Ref {
c := (*reflect.StringHeader)(unsafe.Pointer(&p.source.Contents))
n := (*reflect.StringHeader)(unsafe.Pointer(&name))
// Is the data in "name" a subset of the data in "p.source.Contents"?
if n.Data >= c.Data && n.Data+uintptr(n.Len) < c.Data+uintptr(c.Len) {
// The name is a slice of the file contents, so we can just reference it by
// length and don't have to allocate anything. This is the common case.
//
// It's stored as a negative value so we'll crash if we try to use it. That
// way we'll catch cases where we've forgetten to call loadNameFromRef().
// The length is the negative part because we know it's non-zero.
return ast.Ref{-uint32(n.Len), uint32(n.Data - c.Data)}
} else {
// The name is some memory allocated elsewhere. This is either an inline
// string constant in the parser or an identifier with escape sequences
// in the source code, which is very unusual. Stash it away for later.
// This uses allocations but it should hopefully be very uncommon.
ref := ast.Ref{0x80000000, uint32(len(p.allocatedNames))}
p.allocatedNames = append(p.allocatedNames, name)
return ref
}
}
// This is the inverse of storeNameInRef() above
func (p *parser) loadNameFromRef(ref ast.Ref) string {
if ref.OuterIndex == 0x80000000 {
return p.allocatedNames[ref.InnerIndex]
} else {
if (ref.OuterIndex & 0x80000000) == 0 {
panic("Internal error: invalid symbol reference")
}
return p.source.Contents[ref.InnerIndex : int32(ref.InnerIndex)-int32(ref.OuterIndex)]
}
}
func (p *parser) skipTypeScriptBinding() {
switch p.lexer.Token {
case lexer.TIdentifier, lexer.TThis:
p.lexer.Next()
case lexer.TOpenBracket:
p.lexer.Next()
// "[, , a]"
for p.lexer.Token == lexer.TComma {
p.lexer.Next()
}
// "[a, b]"
for p.lexer.Token != lexer.TCloseBracket {
p.skipTypeScriptBinding()
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
p.lexer.Expect(lexer.TCloseBracket)
case lexer.TOpenBrace:
p.lexer.Next()
for p.lexer.Token != lexer.TCloseBrace {
foundIdentifier := false
switch p.lexer.Token {
case lexer.TIdentifier:
// "{x}"
// "{x: y}"
foundIdentifier = true
p.lexer.Next()
// "{1: y}"
// "{'x': y}"
case lexer.TStringLiteral, lexer.TNumericLiteral:
p.lexer.Next()
default:
if p.lexer.IsIdentifierOrKeyword() {
// "{if: x}"
p.lexer.Next()
} else {
p.lexer.Unexpected()
}
}
if p.lexer.Token == lexer.TColon || !foundIdentifier {
p.lexer.Expect(lexer.TColon)
p.skipTypeScriptBinding()
}
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
p.lexer.Expect(lexer.TCloseBrace)
default:
p.lexer.Unexpected()
}
}
func (p *parser) skipTypeScriptFnArgs() {
p.lexer.Expect(lexer.TOpenParen)
for p.lexer.Token != lexer.TCloseParen {
// "(...a)"
if p.lexer.Token == lexer.TDotDotDot {
p.lexer.Next()
}
p.skipTypeScriptBinding()
// "(a?)"
if p.lexer.Token == lexer.TQuestion {
p.lexer.Next()
}
// "(a: any)"
if p.lexer.Token == lexer.TColon {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
// "(a, b)"
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
p.lexer.Expect(lexer.TCloseParen)
}
// This is a spot where the TypeScript grammar is highly ambiguous. Here are
// some cases that are valid:
//
// let x = (y: any): (() => {}) => { };
// let x = (y: any): () => {} => { };
// let x = (y: any): (y) => {} => { };
// let x = (y: any): (y[]) => {};
// let x = (y: any): (a | b) => {};
//
// Here are some cases that aren't valid:
//
// let x = (y: any): (y) => {};
// let x = (y: any): (y) => {return 0};
// let x = (y: any): asserts y is (y) => {};
//
func (p *parser) skipTypeScriptParenOrFnType() {
if p.trySkipTypeScriptArrowArgsWithBacktracking() {
p.skipTypeScriptReturnType()
} else {
p.lexer.Expect(lexer.TOpenParen)
p.skipTypeScriptType(ast.LLowest)
p.lexer.Expect(lexer.TCloseParen)
}
}
func (p *parser) skipTypeScriptReturnType() {
// Skip over "function assert(x: boolean): asserts x"
if p.lexer.IsContextualKeyword("asserts") {
p.lexer.Next()
// "function assert(x: boolean): asserts" is also valid
if p.lexer.Token != lexer.TIdentifier && p.lexer.Token != lexer.TThis {
return
}
p.lexer.Next()
// Continue on to the "is" check below to handle something like
// "function assert(x: any): asserts x is boolean"
} else {
p.skipTypeScriptType(ast.LLowest)
}
if p.lexer.IsContextualKeyword("is") && !p.lexer.HasNewlineBefore {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
}
func (p *parser) skipTypeScriptType(level ast.L) {
p.skipTypeScriptTypePrefix()
p.skipTypeScriptTypeSuffix(level)
}
func (p *parser) skipTypeScriptTypePrefix() {
switch p.lexer.Token {
case lexer.TNumericLiteral, lexer.TBigIntegerLiteral, lexer.TStringLiteral,
lexer.TNoSubstitutionTemplateLiteral, lexer.TThis, lexer.TTrue, lexer.TFalse,
lexer.TNull, lexer.TVoid, lexer.TConst:
p.lexer.Next()
case lexer.TMinus:
p.lexer.Next()
if p.lexer.Token == lexer.TBigIntegerLiteral {
p.lexer.Next()
} else {
p.lexer.Expect(lexer.TNumericLiteral)
}
case lexer.TAmpersand:
case lexer.TBar:
// Support things like "type Foo = | A | B" and "type Foo = & A & B"
p.lexer.Next()
p.skipTypeScriptTypePrefix()
case lexer.TImport:
// "import('fs')"
p.lexer.Next()
p.lexer.Expect(lexer.TOpenParen)
p.lexer.Expect(lexer.TStringLiteral)
p.lexer.Expect(lexer.TCloseParen)
case lexer.TNew:
// "new () => Foo"
// "new <T>() => Foo<T>"
p.lexer.Next()
p.skipTypeScriptTypeParameters()
p.skipTypeScriptParenOrFnType()
case lexer.TLessThan:
// "<T>() => Foo<T>"
p.skipTypeScriptTypeParameters()
p.skipTypeScriptParenOrFnType()
case lexer.TOpenParen:
p.skipTypeScriptParenOrFnType()
case lexer.TIdentifier:
switch p.lexer.Identifier {
case "keyof", "readonly", "infer":
p.lexer.Next()
p.skipTypeScriptType(ast.LPrefix)
case "unique":
p.lexer.Next()
if p.lexer.IsContextualKeyword("symbol") {
p.lexer.Next()
}
default:
p.lexer.Next()
}
case lexer.TTypeof:
p.lexer.Next()
p.skipTypeScriptType(ast.LPrefix)
case lexer.TOpenBracket:
p.lexer.Next()
for p.lexer.Token != lexer.TCloseBracket {
if p.lexer.Token == lexer.TDotDotDot {
p.lexer.Next()
}
p.skipTypeScriptType(ast.LLowest)
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
p.lexer.Expect(lexer.TCloseBracket)
case lexer.TOpenBrace:
p.skipTypeScriptObjectType()
default:
p.lexer.Unexpected()
}
}
func (p *parser) skipTypeScriptTypeSuffix(level ast.L) {
for {
switch p.lexer.Token {
case lexer.TBar:
if level >= ast.LBitwiseOr {
return
}
p.lexer.Next()
p.skipTypeScriptType(ast.LBitwiseOr)
case lexer.TAmpersand:
if level >= ast.LBitwiseAnd {
return
}
p.lexer.Next()
p.skipTypeScriptType(ast.LBitwiseAnd)
case lexer.TDot:
p.lexer.Next()
if !p.lexer.IsIdentifierOrKeyword() {
p.lexer.Expect(lexer.TIdentifier)
}
p.lexer.Next()
case lexer.TOpenBracket:
// "{ ['x']: string \n ['y']: string }" must not become a single type
if p.lexer.HasNewlineBefore {
return
}
p.lexer.Next()
if p.lexer.Token != lexer.TCloseBracket {
p.skipTypeScriptType(ast.LLowest)
}
p.lexer.Expect(lexer.TCloseBracket)
case lexer.TLessThan, lexer.TLessThanEquals,
lexer.TLessThanLessThan, lexer.TLessThanLessThanEquals:
// "let foo: any \n <number>foo" must not become a single type
if p.lexer.HasNewlineBefore {
return
}
p.lexer.ExpectLessThan(false /* isInsideJSXElement */)
for {
p.skipTypeScriptType(ast.LLowest)
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
p.lexer.ExpectGreaterThan(false /* isInsideJSXElement */)
case lexer.TExtends:
// "{ x: number \n extends: boolean }" must not become a single type
if p.lexer.HasNewlineBefore {
return
}
p.lexer.Next()
p.skipTypeScriptType(ast.LCompare)
case lexer.TQuestion:
if level >= ast.LConditional {
return
}
p.lexer.Next()
switch p.lexer.Token {
// Stop now if we're parsing one of these:
// "(a?: b) => void"
// "(a?, b?) => void"
// "(a?) => void"
// "[string?]"
case lexer.TColon, lexer.TComma, lexer.TCloseParen, lexer.TCloseBracket:
return
}
p.skipTypeScriptType(ast.LLowest)
p.lexer.Expect(lexer.TColon)
p.skipTypeScriptType(ast.LLowest)
default:
return
}
}
}
func (p *parser) skipTypeScriptObjectType() {
p.lexer.Expect(lexer.TOpenBrace)
for p.lexer.Token != lexer.TCloseBrace {
// "{ -readonly [K in keyof T]: T[K] }"
// "{ +readonly [K in keyof T]: T[K] }"
if p.lexer.Token == lexer.TPlus || p.lexer.Token == lexer.TMinus {
p.lexer.Next()
}
// Skip over modifiers and the property identifier
foundKey := false
for p.lexer.IsIdentifierOrKeyword() ||
p.lexer.Token == lexer.TStringLiteral ||
p.lexer.Token == lexer.TNumericLiteral {
p.lexer.Next()
foundKey = true
}
if p.lexer.Token == lexer.TOpenBracket {
// Index signature or computed property
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
// "{ [key: string]: number }"
// "{ readonly [K in keyof T]: T[K] }"
if p.lexer.Token == lexer.TColon || p.lexer.Token == lexer.TIn {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
p.lexer.Expect(lexer.TCloseBracket)
// "{ [K in keyof T]+?: T[K] }"
// "{ [K in keyof T]-?: T[K] }"
if p.lexer.Token == lexer.TPlus || p.lexer.Token == lexer.TMinus {
p.lexer.Next()
}
foundKey = true
}
// "?" indicates an optional property
// "!" indicates an initialization assertion
if foundKey && (p.lexer.Token == lexer.TQuestion || p.lexer.Token == lexer.TExclamation) {
p.lexer.Next()
}
// Type parameters come right after the optional mark
p.skipTypeScriptTypeParameters()
switch p.lexer.Token {
case lexer.TColon:
// Regular property
if !foundKey {
p.lexer.Expect(lexer.TIdentifier)
}
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
case lexer.TOpenParen:
// Method signature
p.skipTypeScriptFnArgs()
if p.lexer.Token == lexer.TColon {
p.lexer.Next()
p.skipTypeScriptReturnType()
}
default:
if !foundKey {
p.lexer.Unexpected()
}
}
switch p.lexer.Token {
case lexer.TCloseBrace:
case lexer.TComma, lexer.TSemicolon:
p.lexer.Next()
default:
if !p.lexer.HasNewlineBefore {
p.lexer.Unexpected()
}
}
}
p.lexer.Expect(lexer.TCloseBrace)
}
// This is the type parameter declarations that go with other symbol
// declarations (class, function, type, etc.)
func (p *parser) skipTypeScriptTypeParameters() {
if p.lexer.Token == lexer.TLessThan {
p.lexer.Next()
for {
p.lexer.Expect(lexer.TIdentifier)
// "class Foo<T extends number> {}"
if p.lexer.Token == lexer.TExtends {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
// "class Foo<T = void> {}"
if p.lexer.Token == lexer.TEquals {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
if p.lexer.Token == lexer.TGreaterThan {
break
}
}
p.lexer.ExpectGreaterThan(false /* isInsideJSXElement */)
}
}
func (p *parser) skipTypeScriptTypeArguments(isInsideJSXElement bool) bool {
if p.lexer.Token != lexer.TLessThan {
return false
}
p.lexer.Next()
for {
p.skipTypeScriptType(ast.LLowest)
if p.lexer.Token != lexer.TComma {
break
}
p.lexer.Next()
}
// This type argument list must end with a ">"
p.lexer.ExpectGreaterThan(isInsideJSXElement)
return true
}
func (p *parser) trySkipTypeScriptTypeArgumentsWithBacktracking() bool {
oldLexer := p.lexer