-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
parser.go
10182 lines (8817 loc) · 307 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/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/lexer"
"github.com/evanw/esbuild/internal/logging"
"github.com/evanw/esbuild/internal/renamer"
"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
fnOptsParse fnOptsParse
fnOptsVisit fnOptsVisit
latestReturnHadSemicolon bool
hasImportMeta bool
allocatedNames []string
latestArrowArgLoc ast.Loc
currentScope *ast.Scope
scopesForCurrentPart []*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
duplicateCaseChecker duplicateCaseChecker
// 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
localTypeNames map[string]bool
// 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
deleteTarget 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
// Temporary variables used for lowering
tempRefsToDeclare []ast.Ref
tempRefCount int
}
const (
locModuleScope = -1
)
type scopeOrder struct {
loc ast.Loc
scope *ast.Scope
}
// This is function-specific information used during parsing. It is saved and
// restored on the call stack around code that parses nested functions.
type fnOptsParse struct {
asyncRange ast.Range
arrowArgErrors *deferredArrowArgErrors
isOutsideFn bool
allowAwait bool
allowYield bool
allowSuperCall bool
isTopLevel bool
isConstructor bool
// In TypeScript, forward declarations of functions have no bodies
allowMissingBodyForTypeScript bool
// Allow TypeScript decorators in function arguments
allowTSDecorators bool
}
// This is function-specific information used during visiting. It is saved and
// restored on the call stack around code that parses nested functions.
type fnOptsVisit struct {
isInsideLoop bool
isInsideSwitch bool
// 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
}
const bloomFilterSize = 251
type duplicateCaseValue struct {
hash uint32
value ast.Expr
}
type duplicateCaseChecker struct {
bloomFilter [(bloomFilterSize + 7) / 8]byte
cases []duplicateCaseValue
}
func (dc *duplicateCaseChecker) reset() {
// Preserve capacity
dc.cases = dc.cases[:0]
// This should be optimized by the compiler. See this for more information:
// https://github.com/golang/go/issues/5373
bytes := dc.bloomFilter
for i := range bytes {
bytes[i] = 0
}
}
func (dc *duplicateCaseChecker) check(p *parser, expr ast.Expr) {
if hash, ok := duplicateCaseHash(expr); ok {
bucket := hash % bloomFilterSize
entry := &dc.bloomFilter[bucket/8]
mask := byte(1) << (bucket % 8)
// Check for collisions
if (*entry & mask) != 0 {
for _, c := range dc.cases {
if c.hash == hash {
if equals, couldBeIncorrect := duplicateCaseEquals(c.value, expr); equals {
index := strings.LastIndex(p.source.Contents[:expr.Loc.Start], "case")
r := lexer.RangeOfIdentifier(p.source, ast.Loc{Start: int32(index)})
if couldBeIncorrect {
p.log.AddRangeWarning(&p.source, r,
"This case clause may never be evaluated because it likely duplicates an earlier case clause")
} else {
p.log.AddRangeWarning(&p.source, r,
"This case clause will never be evaluated because it duplicates an earlier case clause")
}
}
return
}
}
}
*entry |= mask
dc.cases = append(dc.cases, duplicateCaseValue{hash: hash, value: expr})
}
}
func hashCombine(seed uint32, hash uint32) uint32 {
return seed ^ (hash + 0x9e3779b9 + (seed << 6) + (seed >> 2))
}
func duplicateCaseHash(expr ast.Expr) (uint32, bool) {
switch e := expr.Data.(type) {
case *ast.ENull:
return 0, true
case *ast.EUndefined:
return 1, true
case *ast.EBoolean:
if e.Value {
return hashCombine(2, 1), true
}
return hashCombine(2, 0), true
case *ast.ENumber:
bits := math.Float64bits(e.Value)
return hashCombine(hashCombine(3, uint32(bits)), uint32(bits>>32)), true
case *ast.EString:
hash := uint32(4)
for _, c := range e.Value {
hash = hashCombine(hash, uint32(c))
}
return hash, true
case *ast.EBigInt:
hash := uint32(5)
for _, c := range e.Value {
hash = hashCombine(hash, uint32(c))
}
return hash, true
case *ast.EIdentifier:
return hashCombine(6, e.Ref.InnerIndex), true
case *ast.EDot:
if target, ok := duplicateCaseHash(e.Target); ok {
hash := hashCombine(7, target)
for _, c := range e.Name {
hash = hashCombine(hash, uint32(c))
}
return hash, true
}
case *ast.EIndex:
if target, ok := duplicateCaseHash(e.Target); ok {
if index, ok := duplicateCaseHash(e.Index); ok {
return hashCombine(hashCombine(8, target), index), true
}
}
}
return 0, false
}
func duplicateCaseEquals(left ast.Expr, right ast.Expr) (equals bool, couldBeIncorrect bool) {
switch a := left.Data.(type) {
case *ast.ENull:
_, ok := right.Data.(*ast.ENull)
return ok, false
case *ast.EUndefined:
_, ok := right.Data.(*ast.EUndefined)
return ok, false
case *ast.EBoolean:
b, ok := right.Data.(*ast.EBoolean)
return ok && a.Value == b.Value, false
case *ast.ENumber:
b, ok := right.Data.(*ast.ENumber)
return ok && a.Value == b.Value, false
case *ast.EString:
b, ok := right.Data.(*ast.EString)
return ok && lexer.UTF16EqualsUTF16(a.Value, b.Value), false
case *ast.EBigInt:
b, ok := right.Data.(*ast.EBigInt)
return ok && a.Value == b.Value, false
case *ast.EIdentifier:
b, ok := right.Data.(*ast.EIdentifier)
return ok && a.Ref == b.Ref, false
case *ast.EDot:
if b, ok := right.Data.(*ast.EDot); ok && a.OptionalChain == b.OptionalChain && a.Name == b.Name {
equals, _ := duplicateCaseEquals(a.Target, b.Target)
return equals, true
}
case *ast.EIndex:
if b, ok := right.Data.(*ast.EIndex); ok && a.OptionalChain == b.OptionalChain {
if equals, _ := duplicateCaseEquals(a.Index, b.Index); equals {
equals, _ := duplicateCaseEquals(a.Target, b.Target)
return equals, true
}
}
}
return false, false
}
func isJumpStatement(data ast.S) bool {
switch data.(type) {
case *ast.SBreak, *ast.SContinue, *ast.SReturn, *ast.SThrow:
return true
}
return false
}
func isPrimitiveToReorder(e ast.E) bool {
switch e.(type) {
case *ast.ENull, *ast.EUndefined, *ast.EString, *ast.EBoolean, *ast.ENumber, *ast.EBigInt:
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
}
// Returns "equal, ok". If "ok" is false, then nothing is known about the two
// values. If "ok" is true, the equality or inequality of the two values is
// stored in "equal".
func checkEqualityIfNoSideEffects(left ast.E, right ast.E) (bool, bool) {
switch l := left.(type) {
case *ast.ENull:
_, ok := right.(*ast.ENull)
return ok, ok
case *ast.EUndefined:
_, ok := right.(*ast.EUndefined)
return ok, ok
case *ast.EBoolean:
r, ok := right.(*ast.EBoolean)
return ok && l.Value == r.Value, ok
case *ast.ENumber:
r, ok := right.(*ast.ENumber)
return ok && l.Value == r.Value, ok
case *ast.EBigInt:
r, ok := right.(*ast.EBigInt)
return ok && l.Value == r.Value, ok
case *ast.EString:
r, ok := right.(*ast.EString)
return ok && lexer.UTF16EqualsUTF16(l.Value, r.Value), ok
}
return false, false
}
func valuesLookTheSame(left ast.E, right ast.E) bool {
switch a := left.(type) {
case *ast.EIdentifier:
if b, ok := right.(*ast.EIdentifier); ok && a.Ref == b.Ref {
return true
}
case *ast.EDot:
if b, ok := right.(*ast.EDot); ok && a.HasSameFlagsAs(b) &&
a.Name == b.Name && valuesLookTheSame(a.Target.Data, b.Target.Data) {
return true
}
case *ast.EIndex:
if b, ok := right.(*ast.EIndex); ok && a.HasSameFlagsAs(b) &&
valuesLookTheSame(a.Target.Data, b.Target.Data) && valuesLookTheSame(a.Index.Data, b.Index.Data) {
return true
}
case *ast.EIf:
if b, ok := right.(*ast.EIf); ok && valuesLookTheSame(a.Test.Data, b.Test.Data) &&
valuesLookTheSame(a.Yes.Data, b.Yes.Data) && valuesLookTheSame(a.No.Data, b.No.Data) {
return true
}
case *ast.EUnary:
if b, ok := right.(*ast.EUnary); ok && a.Op == b.Op && valuesLookTheSame(a.Value.Data, b.Value.Data) {
return true
}
case *ast.EBinary:
if b, ok := right.(*ast.EBinary); ok && a.Op == b.Op && valuesLookTheSame(a.Left.Data, b.Left.Data) &&
valuesLookTheSame(a.Right.Data, b.Right.Data) {
return true
}
case *ast.ECall:
if b, ok := right.(*ast.ECall); ok && a.HasSameFlagsAs(b) &&
len(a.Args) == len(b.Args) && valuesLookTheSame(a.Target.Data, b.Target.Data) {
for i := range a.Args {
if !valuesLookTheSame(a.Args[i].Data, b.Args[i].Data) {
return false
}
}
return true
}
}
equal, ok := checkEqualityIfNoSideEffects(left, right)
return ok && equal
}
func hasValueForThisInCall(expr ast.Expr) bool {
switch expr.Data.(type) {
case *ast.EDot, *ast.EIndex:
return true
default:
return 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.ScopeMember),
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, member := range scope.Parent.Members {
// Don't copy down the optional function expression name. Re-declaring
// the name of a function expression is allowed.
kind := p.symbols[member.Ref.InnerIndex].Kind
if kind != ast.SymbolHoistedFunction {
scope.Members[name] = member
}
}
}
// 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 _, member := range p.currentScope.Members {
p.symbols[member.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,
OriginalName: name,
Link: ast.InvalidRef,
})
if p.TS.Parse {
p.tsUseCounts = append(p.tsUseCounts, 0)
}
return ref
}
type mergeResult int
const (
mergeForbidden = iota
mergeReplaceWithNew
mergeOverwriteWithNew
mergeKeepExisting
mergeBecomePrivateGetSetPair
mergeBecomePrivateStaticGetSetPair
)
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 {
switch existing {
case ast.SymbolTSNamespace, ast.SymbolHoistedFunction, ast.SymbolGeneratorOrAsyncFunction, ast.SymbolTSEnum, ast.SymbolClass:
return mergeKeepExisting
}
}
// "var foo; var foo;"
// "var foo; function foo() {}"
// "function foo() {} var foo;"
if new.IsHoistedOrFunction() && existing.IsHoistedOrFunction() {
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
}
if (existing == ast.SymbolPrivateStaticGet && new == ast.SymbolPrivateStaticSet) ||
(existing == ast.SymbolPrivateStaticSet && new == ast.SymbolPrivateStaticGet) {
return mergeBecomePrivateStaticGetSetPair
}
// "try {} catch (e) { var e }"
if existing == ast.SymbolCatchIdentifier && new == ast.SymbolHoisted {
return mergeReplaceWithNew
}
// "function() { var arguments }"
if existing == ast.SymbolArguments && new == ast.SymbolHoisted {
return mergeKeepExisting
}
// "function() { let arguments }"
if existing == ast.SymbolArguments && new != ast.SymbolHoisted {
return mergeOverwriteWithNew
}
return mergeForbidden
}
func (p *parser) declareSymbol(kind ast.SymbolKind, loc ast.Loc, name string) ast.Ref {
// Allocate a new symbol
ref := p.newSymbol(kind, name)
// Check for a collision in the declaring scope
if existing, ok := p.currentScope.Members[name]; ok {
symbol := &p.symbols[existing.Ref.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.Ref
case mergeKeepExisting:
ref = existing.Ref
case mergeReplaceWithNew:
symbol.Link = ref
case mergeBecomePrivateGetSetPair:
ref = existing.Ref
symbol.Kind = ast.SymbolPrivateGetSetPair
case mergeBecomePrivateStaticGetSetPair:
ref = existing.Ref
symbol.Kind = ast.SymbolPrivateStaticGetSetPair
case mergeOverwriteWithNew:
}
}
// Overwrite this name in the declaring scope
p.currentScope.Members[name] = ast.ScopeMember{Ref: ref, Loc: loc}
return ref
}
func (p *parser) hoistSymbols(scope *ast.Scope) {
nextMember:
for _, member := range scope.Members {
symbol := &p.symbols[member.Ref.InnerIndex]
// Check for collisions that would prevent to hoisting "var" symbols up to the enclosing function scope
if symbol.Kind.IsHoisted() && !scope.Kind.StopsHoisting() {
s := scope.Parent
for {
// 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 {
symbol.MustNotBeRenamed = true
}
if existingMember, ok := s.Members[symbol.OriginalName]; ok {
existingSymbol := &p.symbols[existingMember.Ref.InnerIndex]
switch existingSymbol.Kind {
case ast.SymbolUnbound, ast.SymbolHoisted, ast.SymbolHoistedFunction:
// Silently merge this symbol into the existing symbol
symbol.Link = existingMember.Ref
s.Members[symbol.OriginalName] = existingMember
continue nextMember
case ast.SymbolCatchIdentifier:
// Silently merge the existing symbol into this symbol
existingSymbol.Link = member.Ref
s.Members[symbol.OriginalName] = member
default:
// An identifier binding from a catch statement and a function
// declaration can both silently shadow another hoisted symbol
if symbol.Kind != ast.SymbolCatchIdentifier && symbol.Kind != ast.SymbolHoistedFunction {
r := lexer.RangeOfIdentifier(p.source, member.Loc)
p.log.AddRangeError(&p.source, r, fmt.Sprintf("%q has already been declared", symbol.OriginalName))
}
continue nextMember
}
}
if s.Kind.StopsHoisting() {
// Declare the member in the scope that stopped the hoisting
s.Members[symbol.OriginalName] = member
break
}
s = s.Parent
}
}
}
for _, child := range scope.Children {
p.hoistSymbols(child)
}
}
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 || (opts.isNamespaceScope && opts.isExport) {
b.Ref = p.declareSymbol(kind, binding.Loc, name)
if opts.isExport {
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("Internal error")
}
}
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