-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathjs_ast_helpers.go
2973 lines (2560 loc) · 86.1 KB
/
js_ast_helpers.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 js_ast
import (
"math"
"strconv"
"strings"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/logger"
)
type HelperContext struct {
isUnbound func(ast.Ref) bool
}
func MakeHelperContext(isUnbound func(ast.Ref) bool) HelperContext {
return HelperContext{
isUnbound: isUnbound,
}
}
// If this returns true, then calling this expression captures the target of
// the property access as "this" when calling the function in the property.
func IsPropertyAccess(expr Expr) bool {
switch expr.Data.(type) {
case *EDot, *EIndex:
return true
}
return false
}
func IsOptionalChain(value Expr) bool {
switch e := value.Data.(type) {
case *EDot:
return e.OptionalChain != OptionalChainNone
case *EIndex:
return e.OptionalChain != OptionalChainNone
case *ECall:
return e.OptionalChain != OptionalChainNone
}
return false
}
func Assign(a Expr, b Expr) Expr {
return Expr{Loc: a.Loc, Data: &EBinary{Op: BinOpAssign, Left: a, Right: b}}
}
func AssignStmt(a Expr, b Expr) Stmt {
return Stmt{Loc: a.Loc, Data: &SExpr{Value: Assign(a, b)}}
}
// Wraps the provided expression in the "!" prefix operator. The expression
// will potentially be simplified to avoid generating unnecessary extra "!"
// operators. For example, calling this with "!!x" will return "!x" instead
// of returning "!!!x".
func Not(expr Expr) Expr {
if result, ok := MaybeSimplifyNot(expr); ok {
return result
}
return Expr{Loc: expr.Loc, Data: &EUnary{Op: UnOpNot, Value: expr}}
}
// The given "expr" argument should be the operand of a "!" prefix operator
// (i.e. the "x" in "!x"). This returns a simplified expression for the
// whole operator (i.e. the "!x") if it can be simplified, or false if not.
// It's separate from "Not()" above to avoid allocation on failure in case
// that is undesired.
//
// This function intentionally avoids mutating the input AST so it can be
// called after the AST has been frozen (i.e. after parsing ends).
func MaybeSimplifyNot(expr Expr) (Expr, bool) {
switch e := expr.Data.(type) {
case *EAnnotation:
return MaybeSimplifyNot(e.Value)
case *EInlinedEnum:
if value, ok := MaybeSimplifyNot(e.Value); ok {
return value, true
}
case *ENull, *EUndefined:
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: true}}, true
case *EBoolean:
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: !e.Value}}, true
case *ENumber:
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: e.Value == 0 || math.IsNaN(e.Value)}}, true
case *EBigInt:
if equal, ok := CheckEqualityBigInt(e.Value, "0"); ok {
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: equal}}, true
}
case *EString:
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: len(e.Value) == 0}}, true
case *EFunction, *EArrow, *ERegExp:
return Expr{Loc: expr.Loc, Data: &EBoolean{Value: false}}, true
case *EUnary:
// "!!!a" => "!a"
if e.Op == UnOpNot && KnownPrimitiveType(e.Value.Data) == PrimitiveBoolean {
return e.Value, true
}
case *EBinary:
// Make sure that these transformations are all safe for special values.
// For example, "!(a < b)" is not the same as "a >= b" if a and/or b are
// NaN (or undefined, or null, or possibly other problem cases too).
switch e.Op {
case BinOpLooseEq:
// "!(a == b)" => "a != b"
return Expr{Loc: expr.Loc, Data: &EBinary{Op: BinOpLooseNe, Left: e.Left, Right: e.Right}}, true
case BinOpLooseNe:
// "!(a != b)" => "a == b"
return Expr{Loc: expr.Loc, Data: &EBinary{Op: BinOpLooseEq, Left: e.Left, Right: e.Right}}, true
case BinOpStrictEq:
// "!(a === b)" => "a !== b"
return Expr{Loc: expr.Loc, Data: &EBinary{Op: BinOpStrictNe, Left: e.Left, Right: e.Right}}, true
case BinOpStrictNe:
// "!(a !== b)" => "a === b"
return Expr{Loc: expr.Loc, Data: &EBinary{Op: BinOpStrictEq, Left: e.Left, Right: e.Right}}, true
case BinOpComma:
// "!(a, b)" => "a, !b"
return Expr{Loc: expr.Loc, Data: &EBinary{Op: BinOpComma, Left: e.Left, Right: Not(e.Right)}}, true
}
}
return Expr{}, false
}
// This function intentionally avoids mutating the input AST so it can be
// called after the AST has been frozen (i.e. after parsing ends).
func MaybeSimplifyEqualityComparison(loc logger.Loc, e *EBinary, unsupportedFeatures compat.JSFeature) (Expr, bool) {
value, primitive := e.Left, e.Right
// Detect when the primitive comes first and flip the order of our checks
if IsPrimitiveLiteral(value.Data) {
value, primitive = primitive, value
}
// "!x === true" => "!x"
// "!x === false" => "!!x"
// "!x !== true" => "!!x"
// "!x !== false" => "!x"
if boolean, ok := primitive.Data.(*EBoolean); ok && KnownPrimitiveType(value.Data) == PrimitiveBoolean {
if boolean.Value == (e.Op == BinOpLooseNe || e.Op == BinOpStrictNe) {
return Not(value), true
} else {
return value, true
}
}
// "typeof x != 'undefined'" => "typeof x < 'u'"
// "typeof x == 'undefined'" => "typeof x > 'u'"
if !unsupportedFeatures.Has(compat.TypeofExoticObjectIsObject) {
// Only do this optimization if we know that the "typeof" operator won't
// return something random. The only case of this happening was Internet
// Explorer returning "unknown" for some objects, which messes with this
// optimization. So we don't do this when targeting Internet Explorer.
if typeof, ok := value.Data.(*EUnary); ok && typeof.Op == UnOpTypeof {
if str, ok := primitive.Data.(*EString); ok && helpers.UTF16EqualsString(str.Value, "undefined") {
flip := value == e.Right
op := BinOpLt
if (e.Op == BinOpLooseEq || e.Op == BinOpStrictEq) != flip {
op = BinOpGt
}
primitive.Data = &EString{Value: []uint16{'u'}}
if flip {
value, primitive = primitive, value
}
return Expr{Loc: loc, Data: &EBinary{Op: op, Left: value, Right: primitive}}, true
}
}
}
return Expr{}, false
}
func IsSymbolInstance(data E) bool {
switch e := data.(type) {
case *EDot:
return e.IsSymbolInstance
case *EIndex:
return e.IsSymbolInstance
}
return false
}
func IsPrimitiveLiteral(data E) bool {
switch e := data.(type) {
case *EAnnotation:
return IsPrimitiveLiteral(e.Value.Data)
case *EInlinedEnum:
return IsPrimitiveLiteral(e.Value.Data)
case *ENull, *EUndefined, *EString, *EBoolean, *ENumber, *EBigInt:
return true
}
return false
}
type PrimitiveType uint8
const (
PrimitiveUnknown PrimitiveType = iota
PrimitiveMixed
PrimitiveNull
PrimitiveUndefined
PrimitiveBoolean
PrimitiveNumber
PrimitiveString
PrimitiveBigInt
)
// This can be used when the returned type is either one or the other
func MergedKnownPrimitiveTypes(a Expr, b Expr) PrimitiveType {
x := KnownPrimitiveType(a.Data)
if x == PrimitiveUnknown {
return PrimitiveUnknown
}
y := KnownPrimitiveType(b.Data)
if y == PrimitiveUnknown {
return PrimitiveUnknown
}
if x == y {
return x
}
return PrimitiveMixed // Definitely some kind of primitive
}
// Note: This function does not say whether the expression is side-effect free
// or not. For example, the expression "++x" always returns a primitive.
func KnownPrimitiveType(expr E) PrimitiveType {
switch e := expr.(type) {
case *EAnnotation:
return KnownPrimitiveType(e.Value.Data)
case *EInlinedEnum:
return KnownPrimitiveType(e.Value.Data)
case *ENull:
return PrimitiveNull
case *EUndefined:
return PrimitiveUndefined
case *EBoolean:
return PrimitiveBoolean
case *ENumber:
return PrimitiveNumber
case *EString:
return PrimitiveString
case *EBigInt:
return PrimitiveBigInt
case *ETemplate:
if e.TagOrNil.Data == nil {
return PrimitiveString
}
case *EIf:
return MergedKnownPrimitiveTypes(e.Yes, e.No)
case *EUnary:
switch e.Op {
case UnOpVoid:
return PrimitiveUndefined
case UnOpTypeof:
return PrimitiveString
case UnOpNot, UnOpDelete:
return PrimitiveBoolean
case UnOpPos:
return PrimitiveNumber // Cannot be bigint because that throws an exception
case UnOpNeg, UnOpCpl:
value := KnownPrimitiveType(e.Value.Data)
if value == PrimitiveBigInt {
return PrimitiveBigInt
}
if value != PrimitiveUnknown && value != PrimitiveMixed {
return PrimitiveNumber
}
return PrimitiveMixed // Can be number or bigint
case UnOpPreDec, UnOpPreInc, UnOpPostDec, UnOpPostInc:
return PrimitiveMixed // Can be number or bigint
}
case *EBinary:
switch e.Op {
case BinOpStrictEq, BinOpStrictNe, BinOpLooseEq, BinOpLooseNe,
BinOpLt, BinOpGt, BinOpLe, BinOpGe,
BinOpInstanceof, BinOpIn:
return PrimitiveBoolean
case BinOpLogicalOr, BinOpLogicalAnd:
return MergedKnownPrimitiveTypes(e.Left, e.Right)
case BinOpNullishCoalescing:
left := KnownPrimitiveType(e.Left.Data)
right := KnownPrimitiveType(e.Right.Data)
if left == PrimitiveNull || left == PrimitiveUndefined {
return right
}
if left != PrimitiveUnknown {
if left != PrimitiveMixed {
return left // Definitely not null or undefined
}
if right != PrimitiveUnknown {
return PrimitiveMixed // Definitely some kind of primitive
}
}
case BinOpAdd:
left := KnownPrimitiveType(e.Left.Data)
right := KnownPrimitiveType(e.Right.Data)
if left == PrimitiveString || right == PrimitiveString {
return PrimitiveString
}
if left == PrimitiveBigInt && right == PrimitiveBigInt {
return PrimitiveBigInt
}
if left != PrimitiveUnknown && left != PrimitiveMixed && left != PrimitiveBigInt &&
right != PrimitiveUnknown && right != PrimitiveMixed && right != PrimitiveBigInt {
return PrimitiveNumber
}
return PrimitiveMixed // Can be number or bigint or string (or an exception)
case BinOpAddAssign:
right := KnownPrimitiveType(e.Right.Data)
if right == PrimitiveString {
return PrimitiveString
}
return PrimitiveMixed // Can be number or bigint or string (or an exception)
case
BinOpSub, BinOpSubAssign,
BinOpMul, BinOpMulAssign,
BinOpDiv, BinOpDivAssign,
BinOpRem, BinOpRemAssign,
BinOpPow, BinOpPowAssign,
BinOpBitwiseAnd, BinOpBitwiseAndAssign,
BinOpBitwiseOr, BinOpBitwiseOrAssign,
BinOpBitwiseXor, BinOpBitwiseXorAssign,
BinOpShl, BinOpShlAssign,
BinOpShr, BinOpShrAssign,
BinOpUShr, BinOpUShrAssign:
return PrimitiveMixed // Can be number or bigint (or an exception)
case BinOpAssign, BinOpComma:
return KnownPrimitiveType(e.Right.Data)
}
}
return PrimitiveUnknown
}
func CanChangeStrictToLoose(a Expr, b Expr) bool {
x := KnownPrimitiveType(a.Data)
y := KnownPrimitiveType(b.Data)
return x == y && x != PrimitiveUnknown && x != PrimitiveMixed
}
// Returns true if the result of the "typeof" operator on this expression is
// statically determined and this expression has no side effects (i.e. can be
// removed without consequence).
func TypeofWithoutSideEffects(data E) (string, bool) {
switch e := data.(type) {
case *EAnnotation:
if e.Flags.Has(CanBeRemovedIfUnusedFlag) {
return TypeofWithoutSideEffects(e.Value.Data)
}
case *EInlinedEnum:
return TypeofWithoutSideEffects(e.Value.Data)
case *ENull:
return "object", true
case *EUndefined:
return "undefined", true
case *EBoolean:
return "boolean", true
case *ENumber:
return "number", true
case *EBigInt:
return "bigint", true
case *EString:
return "string", true
case *EFunction, *EArrow:
return "function", true
}
return "", false
}
// The goal of this function is to "rotate" the AST if it's possible to use the
// left-associative property of the operator to avoid unnecessary parentheses.
//
// When using this, make absolutely sure that the operator is actually
// associative. For example, the "+" operator is not associative for
// floating-point numbers.
//
// This function intentionally avoids mutating the input AST so it can be
// called after the AST has been frozen (i.e. after parsing ends).
func JoinWithLeftAssociativeOp(op OpCode, a Expr, b Expr) Expr {
// "(a, b) op c" => "a, b op c"
if comma, ok := a.Data.(*EBinary); ok && comma.Op == BinOpComma {
// Don't mutate the original AST
clone := *comma
clone.Right = JoinWithLeftAssociativeOp(op, clone.Right, b)
return Expr{Loc: a.Loc, Data: &clone}
}
// "a op (b op c)" => "(a op b) op c"
// "a op (b op (c op d))" => "((a op b) op c) op d"
for {
if binary, ok := b.Data.(*EBinary); ok && binary.Op == op {
a = JoinWithLeftAssociativeOp(op, a, binary.Left)
b = binary.Right
} else {
break
}
}
// "a op b" => "a op b"
// "(a op b) op c" => "(a op b) op c"
return Expr{Loc: a.Loc, Data: &EBinary{Op: op, Left: a, Right: b}}
}
func JoinWithComma(a Expr, b Expr) Expr {
if a.Data == nil {
return b
}
if b.Data == nil {
return a
}
return Expr{Loc: a.Loc, Data: &EBinary{Op: BinOpComma, Left: a, Right: b}}
}
func JoinAllWithComma(all []Expr) (result Expr) {
for _, value := range all {
result = JoinWithComma(result, value)
}
return
}
func ConvertBindingToExpr(binding Binding, wrapIdentifier func(logger.Loc, ast.Ref) Expr) Expr {
loc := binding.Loc
switch b := binding.Data.(type) {
case *BMissing:
return Expr{Loc: loc, Data: &EMissing{}}
case *BIdentifier:
if wrapIdentifier != nil {
return wrapIdentifier(loc, b.Ref)
}
return Expr{Loc: loc, Data: &EIdentifier{Ref: b.Ref}}
case *BArray:
exprs := make([]Expr, len(b.Items))
for i, item := range b.Items {
expr := ConvertBindingToExpr(item.Binding, wrapIdentifier)
if b.HasSpread && i+1 == len(b.Items) {
expr = Expr{Loc: expr.Loc, Data: &ESpread{Value: expr}}
} else if item.DefaultValueOrNil.Data != nil {
expr = Assign(expr, item.DefaultValueOrNil)
}
exprs[i] = expr
}
return Expr{Loc: loc, Data: &EArray{
Items: exprs,
IsSingleLine: b.IsSingleLine,
}}
case *BObject:
properties := make([]Property, len(b.Properties))
for i, property := range b.Properties {
value := ConvertBindingToExpr(property.Value, wrapIdentifier)
kind := PropertyField
if property.IsSpread {
kind = PropertySpread
}
var flags PropertyFlags
if property.IsComputed {
flags |= PropertyIsComputed
}
properties[i] = Property{
Kind: kind,
Flags: flags,
Key: property.Key,
ValueOrNil: value,
InitializerOrNil: property.DefaultValueOrNil,
}
}
return Expr{Loc: loc, Data: &EObject{
Properties: properties,
IsSingleLine: b.IsSingleLine,
}}
default:
panic("Internal error")
}
}
// This will return a nil expression if the expression can be totally removed.
//
// This function intentionally avoids mutating the input AST so it can be
// called after the AST has been frozen (i.e. after parsing ends).
func (ctx HelperContext) SimplifyUnusedExpr(expr Expr, unsupportedFeatures compat.JSFeature) Expr {
switch e := expr.Data.(type) {
case *EAnnotation:
if e.Flags.Has(CanBeRemovedIfUnusedFlag) {
return Expr{}
}
case *EInlinedEnum:
return ctx.SimplifyUnusedExpr(e.Value, unsupportedFeatures)
case *ENull, *EUndefined, *EMissing, *EBoolean, *ENumber, *EBigInt,
*EString, *EThis, *ERegExp, *EFunction, *EArrow, *EImportMeta:
return Expr{}
case *EDot:
if e.CanBeRemovedIfUnused {
return Expr{}
}
case *EIdentifier:
if e.MustKeepDueToWithStmt {
break
}
if e.CanBeRemovedIfUnused || !ctx.isUnbound(e.Ref) {
return Expr{}
}
case *ETemplate:
if e.TagOrNil.Data == nil {
var comma Expr
var templateLoc logger.Loc
var template *ETemplate
for _, part := range e.Parts {
// If we know this value is some kind of primitive, then we know that
// "ToString" has no side effects and can be avoided.
if KnownPrimitiveType(part.Value.Data) != PrimitiveUnknown {
if template != nil {
comma = JoinWithComma(comma, Expr{Loc: templateLoc, Data: template})
template = nil
}
comma = JoinWithComma(comma, ctx.SimplifyUnusedExpr(part.Value, unsupportedFeatures))
continue
}
// Make sure "ToString" is still evaluated on the value. We can't use
// string addition here because that may evaluate "ValueOf" instead.
if template == nil {
template = &ETemplate{}
templateLoc = part.Value.Loc
}
template.Parts = append(template.Parts, TemplatePart{Value: part.Value})
}
if template != nil {
comma = JoinWithComma(comma, Expr{Loc: templateLoc, Data: template})
}
return comma
} else if e.CanBeUnwrappedIfUnused {
// If the function call was annotated as being able to be removed if the
// result is unused, then we can remove it and just keep the arguments.
// Note that there are no implicit "ToString" operations for tagged
// template literals.
var comma Expr
for _, part := range e.Parts {
comma = JoinWithComma(comma, ctx.SimplifyUnusedExpr(part.Value, unsupportedFeatures))
}
return comma
}
case *EArray:
// Arrays with "..." spread expressions can't be unwrapped because the
// "..." triggers code evaluation via iterators. In that case, just trim
// the other items instead and leave the array expression there.
for _, spread := range e.Items {
if _, ok := spread.Data.(*ESpread); ok {
items := make([]Expr, 0, len(e.Items))
for _, item := range e.Items {
item = ctx.SimplifyUnusedExpr(item, unsupportedFeatures)
if item.Data != nil {
items = append(items, item)
}
}
// Don't mutate the original AST
clone := *e
clone.Items = items
return Expr{Loc: expr.Loc, Data: &clone}
}
}
// Otherwise, the array can be completely removed. We only need to keep any
// array items with side effects. Apply this simplification recursively.
var result Expr
for _, item := range e.Items {
result = JoinWithComma(result, ctx.SimplifyUnusedExpr(item, unsupportedFeatures))
}
return result
case *EObject:
// Objects with "..." spread expressions can't be unwrapped because the
// "..." triggers code evaluation via getters. In that case, just trim
// the other items instead and leave the object expression there.
for _, spread := range e.Properties {
if spread.Kind == PropertySpread {
properties := make([]Property, 0, len(e.Properties))
for _, property := range e.Properties {
// Spread properties must always be evaluated
if property.Kind != PropertySpread {
value := ctx.SimplifyUnusedExpr(property.ValueOrNil, unsupportedFeatures)
if value.Data != nil {
// Keep the value
property.ValueOrNil = value
} else if !property.Flags.Has(PropertyIsComputed) {
// Skip this property if the key doesn't need to be computed
continue
} else {
// Replace values without side effects with "0" because it's short
property.ValueOrNil.Data = &ENumber{}
}
}
properties = append(properties, property)
}
// Don't mutate the original AST
clone := *e
clone.Properties = properties
return Expr{Loc: expr.Loc, Data: &clone}
}
}
// Otherwise, the object can be completely removed. We only need to keep any
// object properties with side effects. Apply this simplification recursively.
var result Expr
for _, property := range e.Properties {
if property.Flags.Has(PropertyIsComputed) {
// Make sure "ToString" is still evaluated on the key
result = JoinWithComma(result, Expr{Loc: property.Key.Loc, Data: &EBinary{
Op: BinOpAdd,
Left: property.Key,
Right: Expr{Loc: property.Key.Loc, Data: &EString{}},
}})
}
result = JoinWithComma(result, ctx.SimplifyUnusedExpr(property.ValueOrNil, unsupportedFeatures))
}
return result
case *EIf:
yes := ctx.SimplifyUnusedExpr(e.Yes, unsupportedFeatures)
no := ctx.SimplifyUnusedExpr(e.No, unsupportedFeatures)
// "foo() ? 1 : 2" => "foo()"
if yes.Data == nil && no.Data == nil {
return ctx.SimplifyUnusedExpr(e.Test, unsupportedFeatures)
}
// "foo() ? 1 : bar()" => "foo() || bar()"
if yes.Data == nil {
return JoinWithLeftAssociativeOp(BinOpLogicalOr, e.Test, no)
}
// "foo() ? bar() : 2" => "foo() && bar()"
if no.Data == nil {
return JoinWithLeftAssociativeOp(BinOpLogicalAnd, e.Test, yes)
}
if yes != e.Yes || no != e.No {
return Expr{Loc: expr.Loc, Data: &EIf{Test: e.Test, Yes: yes, No: no}}
}
case *EUnary:
switch e.Op {
// These operators must not have any type conversions that can execute code
// such as "toString" or "valueOf". They must also never throw any exceptions.
case UnOpVoid, UnOpNot:
return ctx.SimplifyUnusedExpr(e.Value, unsupportedFeatures)
case UnOpTypeof:
if _, ok := e.Value.Data.(*EIdentifier); ok && e.WasOriginallyTypeofIdentifier {
// "typeof x" must not be transformed into if "x" since doing so could
// cause an exception to be thrown. Instead we can just remove it since
// "typeof x" is special-cased in the standard to never throw.
return Expr{}
}
return ctx.SimplifyUnusedExpr(e.Value, unsupportedFeatures)
}
case *EBinary:
left := e.Left
right := e.Right
switch e.Op {
// These operators must not have any type conversions that can execute code
// such as "toString" or "valueOf". They must also never throw any exceptions.
case BinOpStrictEq, BinOpStrictNe, BinOpComma:
return JoinWithComma(ctx.SimplifyUnusedExpr(left, unsupportedFeatures), ctx.SimplifyUnusedExpr(right, unsupportedFeatures))
// We can simplify "==" and "!=" even though they can call "toString" and/or
// "valueOf" if we can statically determine that the types of both sides are
// primitives. In that case there won't be any chance for user-defined
// "toString" and/or "valueOf" to be called.
case BinOpLooseEq, BinOpLooseNe:
if MergedKnownPrimitiveTypes(left, right) != PrimitiveUnknown {
return JoinWithComma(ctx.SimplifyUnusedExpr(left, unsupportedFeatures), ctx.SimplifyUnusedExpr(right, unsupportedFeatures))
}
case BinOpLogicalAnd, BinOpLogicalOr, BinOpNullishCoalescing:
// If this is a boolean logical operation and the result is unused, then
// we know the left operand will only be used for its boolean value and
// can be simplified under that assumption
if e.Op != BinOpNullishCoalescing {
left = ctx.SimplifyBooleanExpr(left)
}
// Preserve short-circuit behavior: the left expression is only unused if
// the right expression can be completely removed. Otherwise, the left
// expression is important for the branch.
right = ctx.SimplifyUnusedExpr(right, unsupportedFeatures)
if right.Data == nil {
return ctx.SimplifyUnusedExpr(left, unsupportedFeatures)
}
// Try to take advantage of the optional chain operator to shorten code
if !unsupportedFeatures.Has(compat.OptionalChain) {
if binary, ok := left.Data.(*EBinary); ok {
// "a != null && a.b()" => "a?.b()"
// "a == null || a.b()" => "a?.b()"
if (binary.Op == BinOpLooseNe && e.Op == BinOpLogicalAnd) || (binary.Op == BinOpLooseEq && e.Op == BinOpLogicalOr) {
var test Expr
if _, ok := binary.Right.Data.(*ENull); ok {
test = binary.Left
} else if _, ok := binary.Left.Data.(*ENull); ok {
test = binary.Right
}
// Note: Technically unbound identifiers can refer to a getter on
// the global object and that getter can have side effects that can
// be observed if we run that getter once instead of twice. But this
// seems like terrible coding practice and very unlikely to come up
// in real software, so we deliberately ignore this possibility and
// optimize for size instead of for this obscure edge case.
//
// If this is ever changed, then we must also pessimize the lowering
// of "foo?.bar" to save the value of "foo" to ensure that it's only
// evaluated once. Specifically "foo?.bar" would have to expand to:
//
// var _a;
// (_a = foo) == null ? void 0 : _a.bar;
//
// instead of:
//
// foo == null ? void 0 : foo.bar;
//
// Babel does the first one while TypeScript does the second one.
// Since TypeScript doesn't handle this extreme edge case and
// TypeScript is very widely used, I think it's fine for us to not
// handle this edge case either.
if id, ok := test.Data.(*EIdentifier); ok && !id.MustKeepDueToWithStmt && TryToInsertOptionalChain(test, right) {
return right
}
}
}
}
case BinOpAdd:
if result, isStringAddition := simplifyUnusedStringAdditionChain(expr); isStringAddition {
return result
}
}
if left != e.Left || right != e.Right {
return Expr{Loc: expr.Loc, Data: &EBinary{Op: e.Op, Left: left, Right: right}}
}
case *ECall:
// A call that has been marked "__PURE__" can be removed if all arguments
// can be removed. The annotation causes us to ignore the target.
if e.CanBeUnwrappedIfUnused {
var result Expr
for _, arg := range e.Args {
if _, ok := arg.Data.(*ESpread); ok {
arg.Data = &EArray{Items: []Expr{arg}, IsSingleLine: true}
}
result = JoinWithComma(result, ctx.SimplifyUnusedExpr(arg, unsupportedFeatures))
}
return result
}
// Attempt to shorten IIFEs
if len(e.Args) == 0 {
switch target := e.Target.Data.(type) {
case *EFunction:
if len(target.Fn.Args) != 0 {
break
}
// Just delete "(function() {})()" completely
if len(target.Fn.Body.Block.Stmts) == 0 {
return Expr{}
}
case *EArrow:
if len(target.Args) != 0 {
break
}
// Just delete "(() => {})()" completely
if len(target.Body.Block.Stmts) == 0 {
return Expr{}
}
if len(target.Body.Block.Stmts) == 1 {
switch s := target.Body.Block.Stmts[0].Data.(type) {
case *SExpr:
if !target.IsAsync {
// Replace "(() => { foo() })()" with "foo()"
return s.Value
} else {
// Replace "(async () => { foo() })()" with "(async () => foo())()"
clone := *target
clone.Body.Block.Stmts[0].Data = &SReturn{ValueOrNil: s.Value}
clone.PreferExpr = true
return Expr{Loc: expr.Loc, Data: &ECall{Target: Expr{Loc: e.Target.Loc, Data: &clone}}}
}
case *SReturn:
if !target.IsAsync {
// Replace "(() => foo())()" with "foo()"
return s.ValueOrNil
}
}
}
}
}
case *ENew:
// A constructor call that has been marked "__PURE__" can be removed if all
// arguments can be removed. The annotation causes us to ignore the target.
if e.CanBeUnwrappedIfUnused {
var result Expr
for _, arg := range e.Args {
if _, ok := arg.Data.(*ESpread); ok {
arg.Data = &EArray{Items: []Expr{arg}, IsSingleLine: true}
}
result = JoinWithComma(result, ctx.SimplifyUnusedExpr(arg, unsupportedFeatures))
}
return result
}
}
return expr
}
// This function intentionally avoids mutating the input AST so it can be
// called after the AST has been frozen (i.e. after parsing ends).
func simplifyUnusedStringAdditionChain(expr Expr) (Expr, bool) {
switch e := expr.Data.(type) {
case *EString:
// "'x' + y" => "'' + y"
return Expr{Loc: expr.Loc, Data: &EString{}}, true
case *EBinary:
if e.Op == BinOpAdd {
left, leftIsStringAddition := simplifyUnusedStringAdditionChain(e.Left)
if right, rightIsString := e.Right.Data.(*EString); rightIsString {
// "('' + x) + 'y'" => "'' + x"
if leftIsStringAddition {
return left, true
}
// "x + 'y'" => "x + ''"
if !leftIsStringAddition && len(right.Value) > 0 {
return Expr{Loc: expr.Loc, Data: &EBinary{
Op: BinOpAdd,
Left: left,
Right: Expr{Loc: e.Right.Loc, Data: &EString{}},
}}, true
}
}
// Don't mutate the original AST
if left != e.Left {
expr.Data = &EBinary{Op: BinOpAdd, Left: left, Right: e.Right}
}
return expr, leftIsStringAddition
}
}
return expr, false
}
func ToInt32(f float64) int32 {
// The easy way
i := int32(f)
if float64(i) == f {
return i
}
// Special-case non-finite numbers (casting them is unspecified behavior in Go)
if math.IsNaN(f) || math.IsInf(f, 0) {
return 0
}
// The hard way
i = int32(uint32(math.Mod(math.Abs(f), 4294967296)))
if math.Signbit(f) {
return -i
}
return i
}
func ToUint32(f float64) uint32 {
return uint32(ToInt32(f))
}
func isInt32OrUint32(data E) bool {
switch e := data.(type) {
case *EUnary:
return e.Op == UnOpCpl
case *EBinary:
switch e.Op {
case BinOpBitwiseAnd, BinOpBitwiseOr, BinOpBitwiseXor, BinOpShl, BinOpShr, BinOpUShr:
return true
case BinOpLogicalOr, BinOpLogicalAnd:
return isInt32OrUint32(e.Left.Data) && isInt32OrUint32(e.Right.Data)
}
case *EIf:
return isInt32OrUint32(e.Yes.Data) && isInt32OrUint32(e.No.Data)
}
return false
}
func ToNumberWithoutSideEffects(data E) (float64, bool) {
switch e := data.(type) {
case *EAnnotation:
return ToNumberWithoutSideEffects(e.Value.Data)
case *EInlinedEnum:
return ToNumberWithoutSideEffects(e.Value.Data)
case *ENull:
return 0, true
case *EUndefined, *ERegExp:
return math.NaN(), true
case *EArray:
if len(e.Items) == 0 {
// "+[]" => "0"
return 0, true
}
case *EObject:
if len(e.Properties) == 0 {
// "+{}" => "NaN"
return math.NaN(), true
}
case *EBoolean:
if e.Value {
return 1, true
} else {
return 0, true
}