-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
parser.go
8458 lines (7277 loc) · 250 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 (
"fmt"
"math"
"reflect"
"sort"
"strings"
"unsafe"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/lexer"
"github.com/evanw/esbuild/internal/logging"
"github.com/evanw/esbuild/internal/runtime"
)
// 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 {
config.Options
log logging.Log
source logging.Source
lexer lexer.Lexer
allowIn bool
allowPrivateIdentifiers bool
hasTopLevelReturn bool
currentFnOpts fnOpts
latestReturnHadSemicolon bool
hasImportMeta bool
allocatedNames []string
latestArrowArgLoc ast.Loc
currentScope *ast.Scope
symbols []ast.Symbol
tsUseCounts []uint32
exportsRef ast.Ref
requireRef ast.Ref
moduleRef ast.Ref
importMetaRef ast.Ref
findSymbolHelper config.FindSymbol
symbolUses map[ast.Ref]ast.SymbolUse
declaredSymbols []ast.DeclaredSymbol
runtimeImports map[string]ast.Ref
// For lowering private methods
weakMapRef ast.Ref
weakSetRef ast.Ref
privateGetters map[ast.Ref]ast.Ref
privateSetters map[ast.Ref]ast.Ref
// These are for TypeScript
shouldFoldNumericConstants bool
enclosingNamespaceRef *ast.Ref
emittedNamespaceVars map[ast.Ref]bool
isExportedInsideNamespace map[ast.Ref]ast.Ref
knownEnumValues map[ast.Ref]map[string]float64
// Imports (both ES6 and CommonJS) are tracked at the top level
importRecords []ast.ImportRecord
importRecordsForCurrentPart []uint32
exportStarImportRecords []uint32
// These are for handling ES6 imports and exports
hasES6ImportSyntax bool
hasES6ExportSyntax bool
importItemsForNamespace map[ast.Ref]map[string]ast.LocRef
isImportItem map[ast.Ref]bool
namedImports map[ast.Ref]ast.NamedImport
namedExports map[string]ast.Ref
topLevelSymbolToParts map[ast.Ref][]uint32
// 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.
isThisCaptured bool
argumentsRef *ast.Ref
callTarget ast.E
moduleScope *ast.Scope
isControlFlowDead bool
// These are for recognizing "typeof require == 'function' && require". This
// is a workaround for code that browserify generates that looks like this:
//
// (function e(t, n, r) {
// function s(o2, u) {
// if (!n[o2]) {
// if (!t[o2]) {
// var a = typeof require == "function" && require;
// if (!u && a)
// return a(o2, true);
// if (i)
// return i(o2, true);
// throw new Error("Cannot find module '" + o2 + "'");
// }
// var f = n[o2] = {exports: {}};
// t[o2][0].call(f.exports, function(e2) {
// var n2 = t[o2][1][e2];
// return s(n2 ? n2 : e2);
// }, f, f.exports, e, t, n, r);
// }
// return n[o2].exports;
// }
// var i = typeof require == "function" && require;
// for (var o = 0; o < r.length; o++)
// s(r[o]);
// return s;
// });
//
// It's checking to see if the environment it's running in has a "require"
// function before calling it. However, esbuild's bundling environment has a
// bundle-time require function because it's a bundler. So in this case
// "typeof require == 'function'" is true and the "&&" expression just
// becomes a single "require" identifier, which will then crash at run time.
//
// The workaround is to explicitly pattern-match for the exact expression
// "typeof require == 'function' && require" and replace it with "false" if
// we're targeting the browser.
//
// Note that we can't just leave "typeof require == 'function'" alone because
// there is other code in the wild that legitimately does need it to become
// "true" when bundling. Specifically, the package "@dagrejs/graphlib" has
// code that looks like this:
//
// if (typeof require === "function") {
// try {
// lodash = {
// clone: require("lodash/clone"),
// constant: require("lodash/constant"),
// each: require("lodash/each"),
// // ... more calls to require() here ...
// };
// } catch (e) {
// // continue regardless of error
// }
// }
//
// That library will crash later on during startup if that branch isn't
// taken because "typeof require === 'function'" is false at run time.
typeofTarget ast.E
typeofRequire ast.E
typeofRequireEqualsFn ast.E
typeofRequireEqualsFnTarget ast.E
// This is used to silence references to "require" inside a try/catch
// statement. The assumption is that the try/catch statement is there to
// handle the case where the reference to "require" crashes. Specifically,
// the workaround handles the "moment" library which contains code that
// looks like this:
//
// try {
// oldLocale = globalLocale._abbr;
// var aliasedRequire = require;
// aliasedRequire('./locale/' + name);
// getSetGlobalLocale(oldLocale);
// } catch (e) {}
//
tryBodyCount int
// Temporary variables used for lowering
tempRefsToDeclare []ast.Ref
tempRefCount int
}
const (
locModuleScope = -1
)
type scopeOrder struct {
loc ast.Loc
scope *ast.Scope
}
type fnOpts struct {
asyncRange ast.Range
isOutsideFn bool
allowAwait bool
allowYield bool
allowSuperCall bool
// In TypeScript, forward declarations of functions have no bodies
allowMissingBodyForTypeScript bool
// Allow TypeScript decorators in function arguments
allowTSDecorators bool
}
func isJumpStatement(data ast.S) bool {
switch data.(type) {
case *ast.SBreak, *ast.SContinue, *ast.SReturn, *ast.SThrow:
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))
}
}
// Copy down function arguments into the function body scope. That way we get
// errors if a statement in the function body tries to re-declare any of the
// arguments.
if kind == ast.ScopeFunctionBody {
if scope.Parent.Kind != ast.ScopeFunctionArgs {
panic("Internal error")
}
for name, ref := range scope.Parent.Members {
// Don't copy down the optional function expression name. Re-declaring
// the name of a function expression is allowed.
if p.symbols[ref.InnerIndex].Kind != ast.SymbolHoistedFunction {
scope.Members[name] = ref
}
}
}
// 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() {
// We cannot rename anything inside a scope containing a direct eval() call
if p.currentScope.ContainsDirectEval {
for _, ref := range p.currentScope.Members {
p.symbols[ref.InnerIndex].MustNotBeRenamed = true
}
}
p.currentScope = p.currentScope.Parent
}
func (p *parser) popAndDiscardScope(scopeIndex int) {
// Move up to the parent scope
toDiscard := p.currentScope
parent := toDiscard.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] != toDiscard {
panic("Internal error")
}
parent.Children = parent.Children[:last]
}
func (p *parser) popAndFlattenScope(scopeIndex int) {
// Move up to the parent scope
toFlatten := p.currentScope
parent := toFlatten.Parent
p.currentScope = parent
// Erase this scope from the order. This will shift over the indices of all
// the scopes that were created after us. However, we shouldn't have to
// worry about other code with outstanding scope indices for these scopes.
// These scopes were all created in between this scope's push and pop
// operations, so they should all be child scopes and should all be popped
// by the time we get here.
copy(p.scopesInOrder[scopeIndex:], p.scopesInOrder[scopeIndex+1:])
p.scopesInOrder = p.scopesInOrder[:len(p.scopesInOrder)-1]
// Remove the last child from the parent scope
last := len(parent.Children) - 1
if parent.Children[last] != toFlatten {
panic("Internal error")
}
parent.Children = parent.Children[:last]
// Reparent our child scopes into our parent
for _, scope := range toFlatten.Children {
scope.Parent = parent
parent.Children = append(parent.Children, scope)
}
}
// Undo all scopes pushed and popped after this scope index. This assumes that
// the scope stack is at the same level now as it was at the given scope index.
func (p *parser) discardScopesUpTo(scopeIndex int) {
// Remove any direct children from their parent
children := p.currentScope.Children
for _, child := range p.scopesInOrder[scopeIndex:] {
if child.scope.Parent == p.currentScope {
for i := len(children) - 1; i >= 0; i-- {
if children[i] == child.scope {
children = append(children[:i], children[i+1:]...)
break
}
}
}
}
p.currentScope.Children = children
// Truncate the scope order where we started to pretend we never saw this scope
p.scopesInOrder = p.scopesInOrder[:scopeIndex]
}
func (p *parser) newSymbol(kind ast.SymbolKind, name string) ast.Ref {
ref := ast.Ref{OuterIndex: p.source.Index, InnerIndex: 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
mergeBecomePrivateGetSetPair
)
func (p *parser) canMergeSymbols(existing ast.SymbolKind, new ast.SymbolKind) mergeResult {
if existing == ast.SymbolUnbound {
return mergeReplaceWithNew
}
// In TypeScript, imports are allowed to silently collide with symbols within
// the module. Presumably this is because the imports may be type-only:
//
// import {Foo} from 'bar'
// class Foo {}
//
if p.TS.Parse && existing == ast.SymbolImport {
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
}
// "get #foo() {} set #foo() {}"
// "set #foo() {} get #foo() {}"
if (existing == ast.SymbolPrivateGet && new == ast.SymbolPrivateSet) ||
(existing == ast.SymbolPrivateSet && new == ast.SymbolPrivateGet) {
return mergeBecomePrivateGetSetPair
}
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.StopsHoisting() {
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 merge the existing symbol
// into this one. The merging will happen later on after the new
// symbol exists.
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 p.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:
symbol.Link = ref
case mergeBecomePrivateGetSetPair:
ref = existing
symbol.Kind = ast.SymbolPrivateGetSetPair
}
}
// Hoist "var" symbols up to the enclosing function scope
if kind.IsHoisted() {
for s := p.currentScope; !s.Kind.StopsHoisting(); s = s.Parent {
// Variable declarations hoisted past a "with" statement may actually end
// up overwriting a property on the target of the "with" statement instead
// of initializing the variable. We must not rename them or we risk
// causing a behavior change.
//
// var obj = { foo: 1 }
// with (obj) { var foo = 2 }
// assert(foo === undefined)
// assert(obj.foo === 2)
//
if s.Kind == ast.ScopeWith {
p.symbols[ref.InnerIndex].MustNotBeRenamed = true
}
if existing, ok := s.Members[name]; ok {
symbol := p.symbols[existing.InnerIndex]
// See "VariableStatements in Catch blocks" in the spec for why we
// special-case catch identifiers here:
//
// http://www.ecma-international.org/ecma-262/6.0/#sec-variablestatements-in-catch-blocks
//
if symbol.Kind == ast.SymbolUnbound || symbol.Kind == ast.SymbolCatchIdentifier {
p.symbols[existing.InnerIndex].Link = ref
}
}
// Add the symbol to all parent scopes, not just the one it's declared
// in. This prevents us from later on declaring a symbol that would
// interfere with the hoisting:
//
// {
// {
// var x;
// }
// let x; // SyntaxError: Identifier 'x' has already been declared
// }
//
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 b := binding.Data.(type) {
case *ast.BMissing:
case *ast.BIdentifier:
name := p.loadNameFromRef(b.Ref)
if !opts.isTypeScriptDeclare {
b.Ref = p.declareSymbol(kind, binding.Loc, name)
if opts.isExport && p.enclosingNamespaceRef == nil {
p.recordExport(binding.Loc, name, b.Ref)
}
}
case *ast.BArray:
for _, i := range b.Items {
p.declareBinding(kind, i.Binding, opts)
}
case *ast.BObject:
for _, property := range b.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, ref ast.Ref) {
// This is only an ES6 export if we're not inside a TypeScript namespace
if p.enclosingNamespaceRef == nil {
if _, ok := p.namedExports[alias]; ok {
// 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.namedExports[alias] = ref
}
}
}
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++
use := p.symbolUses[ref]
use.CountEstimate++
p.symbolUses[ref] = use
}
// 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) ignoreUsage(ref ast.Ref) {
// Roll back the use count increment in recordUsage()
if !p.isControlFlowDead {
p.symbols[ref.InnerIndex].UseCountEstimate--
use := p.symbolUses[ref]
use.CountEstimate--
if use.CountEstimate == 0 {
delete(p.symbolUses, ref)
} else {
p.symbolUses[ref] = use
}
}
// Don't roll back the "tsUseCounts" increment. This must be counted even if
// the value is ignored because that's what the TypeScript compiler does.
}
func (p *parser) callRuntime(loc ast.Loc, name string, args []ast.Expr) ast.Expr {
ref, ok := p.runtimeImports[name]
if !ok {
ref = p.newSymbol(ast.SymbolOther, name)
p.runtimeImports[name] = ref
}
p.recordUsage(ref)
return ast.Expr{Loc: loc, Data: &ast.ECall{
Target: ast.Expr{Loc: loc, Data: &ast.EIdentifier{Ref: ref}},
Args: args,
}}
}
// 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{OuterIndex: -uint32(n.Len), InnerIndex: 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{OuterIndex: 0x80000000, InnerIndex: 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)]
}
}
// Due to ES6 destructuring patterns, there are many cases where it's
// impossible to distinguish between an array or object literal and a
// destructuring assignment until we hit the "=" operator later on.
// This object defers errors about being in one state or the other
// until we discover which state we're in.
type deferredErrors struct {
// These are errors for expressions
invalidExprDefaultValue ast.Range
invalidExprAfterQuestion ast.Range
// These are errors for destructuring patterns
invalidBindingCommaAfterSpread ast.Range
}
func (from *deferredErrors) mergeInto(to *deferredErrors) {
if from.invalidExprDefaultValue.Len > 0 {
to.invalidExprDefaultValue = from.invalidExprDefaultValue
}
if from.invalidExprAfterQuestion.Len > 0 {
to.invalidExprAfterQuestion = from.invalidExprAfterQuestion
}
if from.invalidBindingCommaAfterSpread.Len > 0 {
to.invalidBindingCommaAfterSpread = from.invalidBindingCommaAfterSpread
}
}
func (p *parser) logExprErrors(errors *deferredErrors) {
if errors.invalidExprDefaultValue.Len > 0 {
p.log.AddRangeError(&p.source, errors.invalidExprDefaultValue, "Unexpected \"=\"")
}
if errors.invalidExprAfterQuestion.Len > 0 {
r := errors.invalidExprAfterQuestion
p.log.AddRangeError(&p.source, r, fmt.Sprintf("Unexpected %q", p.source.Contents[r.Loc.Start:r.Loc.Start+r.Len]))
}
}
func (p *parser) logBindingErrors(errors *deferredErrors) {
if errors.invalidBindingCommaAfterSpread.Len > 0 {
p.log.AddRangeError(&p.source, errors.invalidBindingCommaAfterSpread, "Unexpected \",\" after rest pattern")
}
}
type propertyOpts struct {
asyncRange ast.Range
isAsync bool
isGenerator bool
// Class-related options
isStatic bool
isClass bool
classHasExtends bool
allowTSDecorators bool
tsDecorators []ast.Expr
}
func (p *parser) parseProperty(
kind ast.PropertyKind, opts propertyOpts, errors *deferredErrors,
) (ast.Property, bool) {
var key ast.Expr
keyRange := p.lexer.Range()
isComputed := false
switch p.lexer.Token {
case lexer.TNumericLiteral:
key = ast.Expr{Loc: p.lexer.Loc(), Data: &ast.ENumber{Value: p.lexer.Number}}
p.lexer.Next()
case lexer.TStringLiteral:
key = ast.Expr{Loc: p.lexer.Loc(), Data: &ast.EString{Value: p.lexer.StringLiteral}}
p.lexer.Next()
case lexer.TPrivateIdentifier:
if !opts.isClass || len(opts.tsDecorators) > 0 {
p.lexer.Expected(lexer.TIdentifier)
}
key = ast.Expr{Loc: p.lexer.Loc(), Data: &ast.EPrivateIdentifier{Ref: p.storeNameInRef(p.lexer.Identifier)}}
p.lexer.Next()
case lexer.TOpenBracket:
isComputed = true
p.lexer.Next()
wasIdentifier := p.lexer.Token == lexer.TIdentifier
expr := p.parseExpr(ast.LComma)
// Handle index signatures
if p.TS.Parse && p.lexer.Token == lexer.TColon && wasIdentifier && opts.isClass {
if _, ok := expr.Data.(*ast.EIdentifier); ok {
// "[key: string]: any;"
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
p.lexer.Expect(lexer.TCloseBracket)
p.lexer.Expect(lexer.TColon)
p.skipTypeScriptType(ast.LLowest)
p.lexer.ExpectOrInsertSemicolon()
// Skip this property entirely
return ast.Property{}, false
}
}
p.lexer.Expect(lexer.TCloseBracket)
key = expr
case lexer.TAsterisk:
if kind != ast.PropertyNormal || opts.isGenerator {
p.lexer.Unexpected()
}
p.lexer.Next()
opts.isGenerator = true
return p.parseProperty(ast.PropertyNormal, opts, errors)
default:
name := p.lexer.Identifier
nameRange := p.lexer.Range()
if !p.lexer.IsIdentifierOrKeyword() {
p.lexer.Expect(lexer.TIdentifier)
}
p.lexer.Next()
// Support contextual keywords
if kind == ast.PropertyNormal && !opts.isGenerator {
// Does the following token look like a key?
couldBeModifierKeyword := p.lexer.IsIdentifierOrKeyword()
if !couldBeModifierKeyword {
switch p.lexer.Token {
case lexer.TOpenBracket, lexer.TNumericLiteral, lexer.TStringLiteral,
lexer.TAsterisk, lexer.TPrivateIdentifier:
couldBeModifierKeyword = true
}
}
// If so, check for a modifier keyword
if couldBeModifierKeyword {
switch name {
case "get":
if !opts.isAsync {
return p.parseProperty(ast.PropertyGet, opts, nil)
}
case "set":
if !opts.isAsync {
return p.parseProperty(ast.PropertySet, opts, nil)
}
case "async":
if !opts.isAsync {
opts.isAsync = true
opts.asyncRange = nameRange
return p.parseProperty(kind, opts, nil)
}
case "static":
if !opts.isStatic && !opts.isAsync && opts.isClass {
opts.isStatic = true
return p.parseProperty(kind, opts, nil)
}
case "private", "protected", "public", "readonly", "abstract", "declare":
// Skip over TypeScript keywords
if opts.isClass && p.TS.Parse {
return p.parseProperty(kind, opts, nil)
}
}
}
}
key = ast.Expr{Loc: nameRange.Loc, Data: &ast.EString{Value: lexer.StringToUTF16(name)}}
// Parse a shorthand property
if !opts.isClass && kind == ast.PropertyNormal && p.lexer.Token != lexer.TColon &&
p.lexer.Token != lexer.TOpenParen && p.lexer.Token != lexer.TLessThan && !opts.isGenerator {
ref := p.storeNameInRef(name)
value := ast.Expr{Loc: key.Loc, Data: &ast.EIdentifier{Ref: ref}}
// Destructuring patterns have an optional default value
var initializer *ast.Expr = nil
if errors != nil && p.lexer.Token == lexer.TEquals {
errors.invalidExprDefaultValue = p.lexer.Range()
p.lexer.Next()
value := p.parseExpr(ast.LComma)
initializer = &value
}
return ast.Property{
Kind: kind,
Key: key,
Value: &value,
Initializer: initializer,
}, true
}
}
if p.TS.Parse {
// "class X { foo?: number }"
// "class X { foo!: number }"
if opts.isClass && (p.lexer.Token == lexer.TQuestion || p.lexer.Token == lexer.TExclamation) {
p.lexer.Next()
}
// "class X { foo?<T>(): T }"
// "const x = { foo<T>(): T {} }"
p.skipTypeScriptTypeParameters()
}
// Parse a class field with an optional initial value
if opts.isClass && kind == ast.PropertyNormal && !opts.isAsync &&
!opts.isGenerator && p.lexer.Token != lexer.TOpenParen {
var initializer *ast.Expr
// Forbid the names "constructor" and "prototype" in some cases
if !isComputed {
if str, ok := key.Data.(*ast.EString); ok && (lexer.UTF16EqualsString(str.Value, "constructor") ||
(opts.isStatic && lexer.UTF16EqualsString(str.Value, "prototype"))) {
p.log.AddRangeError(&p.source, keyRange, fmt.Sprintf("Invalid field name %q", lexer.UTF16ToString(str.Value)))
}
}
// Skip over types
if p.TS.Parse && p.lexer.Token == lexer.TColon {
p.lexer.Next()
p.skipTypeScriptType(ast.LLowest)
}
if p.lexer.Token == lexer.TEquals {
p.lexer.Next()
value := p.parseExpr(ast.LComma)
initializer = &value
}
// Special-case private identifiers
if private, ok := key.Data.(*ast.EPrivateIdentifier); ok {
name := p.loadNameFromRef(private.Ref)