-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
js_parser_lower_class.go
1824 lines (1668 loc) · 66.7 KB
/
js_parser_lower_class.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_parser
import (
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/logger"
)
func (p *parser) privateSymbolNeedsToBeLowered(private *js_ast.EPrivateIdentifier) bool {
symbol := &p.symbols[private.Ref.InnerIndex]
return p.options.unsupportedJSFeatures.Has(compat.SymbolFeature(symbol.Kind)) || symbol.Flags.Has(ast.PrivateSymbolMustBeLowered)
}
func (p *parser) lowerPrivateBrandCheck(target js_ast.Expr, loc logger.Loc, private *js_ast.EPrivateIdentifier) js_ast.Expr {
// "#field in this" => "__privateIn(#field, this)"
return p.callRuntime(loc, "__privateIn", []js_ast.Expr{
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
target,
})
}
func (p *parser) lowerPrivateGet(target js_ast.Expr, loc logger.Loc, private *js_ast.EPrivateIdentifier) js_ast.Expr {
switch p.symbols[private.Ref.InnerIndex].Kind {
case ast.SymbolPrivateMethod, ast.SymbolPrivateStaticMethod:
// "this.#method" => "__privateMethod(this, #method, method_fn)"
fnRef := p.privateGetters[private.Ref]
p.recordUsage(fnRef)
return p.callRuntime(target.Loc, "__privateMethod", []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
{Loc: loc, Data: &js_ast.EIdentifier{Ref: fnRef}},
})
case ast.SymbolPrivateGet, ast.SymbolPrivateStaticGet,
ast.SymbolPrivateGetSetPair, ast.SymbolPrivateStaticGetSetPair:
// "this.#getter" => "__privateGet(this, #getter, getter_get)"
fnRef := p.privateGetters[private.Ref]
p.recordUsage(fnRef)
return p.callRuntime(target.Loc, "__privateGet", []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
{Loc: loc, Data: &js_ast.EIdentifier{Ref: fnRef}},
})
default:
// "this.#field" => "__privateGet(this, #field)"
return p.callRuntime(target.Loc, "__privateGet", []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
})
}
}
func (p *parser) lowerPrivateSet(
target js_ast.Expr,
loc logger.Loc,
private *js_ast.EPrivateIdentifier,
value js_ast.Expr,
) js_ast.Expr {
switch p.symbols[private.Ref.InnerIndex].Kind {
case ast.SymbolPrivateSet, ast.SymbolPrivateStaticSet,
ast.SymbolPrivateGetSetPair, ast.SymbolPrivateStaticGetSetPair:
// "this.#setter = 123" => "__privateSet(this, #setter, 123, setter_set)"
fnRef := p.privateSetters[private.Ref]
p.recordUsage(fnRef)
return p.callRuntime(target.Loc, "__privateSet", []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
value,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: fnRef}},
})
default:
// "this.#field = 123" => "__privateSet(this, #field, 123)"
return p.callRuntime(target.Loc, "__privateSet", []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
value,
})
}
}
func (p *parser) lowerPrivateSetUnOp(target js_ast.Expr, loc logger.Loc, private *js_ast.EPrivateIdentifier, op js_ast.OpCode) js_ast.Expr {
kind := p.symbols[private.Ref.InnerIndex].Kind
// Determine the setter, if any
var setter js_ast.Expr
switch kind {
case ast.SymbolPrivateSet, ast.SymbolPrivateStaticSet,
ast.SymbolPrivateGetSetPair, ast.SymbolPrivateStaticGetSetPair:
ref := p.privateSetters[private.Ref]
p.recordUsage(ref)
setter = js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{Ref: ref}}
}
// Determine the getter, if any
var getter js_ast.Expr
switch kind {
case ast.SymbolPrivateGet, ast.SymbolPrivateStaticGet,
ast.SymbolPrivateGetSetPair, ast.SymbolPrivateStaticGetSetPair:
ref := p.privateGetters[private.Ref]
p.recordUsage(ref)
getter = js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{Ref: ref}}
}
// Only include necessary arguments
args := []js_ast.Expr{
target,
{Loc: loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
}
if setter.Data != nil {
args = append(args, setter)
}
if getter.Data != nil {
if setter.Data == nil {
args = append(args, js_ast.Expr{Loc: loc, Data: js_ast.ENullShared})
}
args = append(args, getter)
}
// "target.#private++" => "__privateWrapper(target, #private, private_set, private_get)._++"
return js_ast.Expr{Loc: loc, Data: &js_ast.EUnary{
Op: op,
Value: js_ast.Expr{Loc: target.Loc, Data: &js_ast.EDot{
Target: p.callRuntime(target.Loc, "__privateWrapper", args),
NameLoc: target.Loc,
Name: "_",
}},
}}
}
func (p *parser) lowerPrivateSetBinOp(target js_ast.Expr, loc logger.Loc, private *js_ast.EPrivateIdentifier, op js_ast.OpCode, value js_ast.Expr) js_ast.Expr {
// "target.#private += 123" => "__privateSet(target, #private, __privateGet(target, #private) + 123)"
targetFunc, targetWrapFunc := p.captureValueWithPossibleSideEffects(target.Loc, 2, target, valueDefinitelyNotMutated)
return targetWrapFunc(p.lowerPrivateSet(targetFunc(), loc, private, js_ast.Expr{Loc: value.Loc, Data: &js_ast.EBinary{
Op: op,
Left: p.lowerPrivateGet(targetFunc(), loc, private),
Right: value,
}}))
}
// Returns valid data if target is an expression of the form "foo.#bar" and if
// the language target is such that private members must be lowered
func (p *parser) extractPrivateIndex(target js_ast.Expr) (js_ast.Expr, logger.Loc, *js_ast.EPrivateIdentifier) {
if index, ok := target.Data.(*js_ast.EIndex); ok {
if private, ok := index.Index.Data.(*js_ast.EPrivateIdentifier); ok && p.privateSymbolNeedsToBeLowered(private) {
return index.Target, index.Index.Loc, private
}
}
return js_ast.Expr{}, logger.Loc{}, nil
}
// Returns a valid property if target is an expression of the form "super.bar"
// or "super[bar]" and if the situation is such that it must be lowered
func (p *parser) extractSuperProperty(target js_ast.Expr) js_ast.Expr {
switch e := target.Data.(type) {
case *js_ast.EDot:
if p.shouldLowerSuperPropertyAccess(e.Target) {
return js_ast.Expr{Loc: e.NameLoc, Data: &js_ast.EString{Value: helpers.StringToUTF16(e.Name)}}
}
case *js_ast.EIndex:
if p.shouldLowerSuperPropertyAccess(e.Target) {
return e.Index
}
}
return js_ast.Expr{}
}
func (p *parser) lowerSuperPropertyOrPrivateInAssign(expr js_ast.Expr) (js_ast.Expr, bool) {
didLower := false
switch e := expr.Data.(type) {
case *js_ast.ESpread:
if value, ok := p.lowerSuperPropertyOrPrivateInAssign(e.Value); ok {
e.Value = value
didLower = true
}
case *js_ast.EDot:
// "[super.foo] = [bar]" => "[__superWrapper(this, 'foo')._] = [bar]"
if p.shouldLowerSuperPropertyAccess(e.Target) {
key := js_ast.Expr{Loc: e.NameLoc, Data: &js_ast.EString{Value: helpers.StringToUTF16(e.Name)}}
expr = p.callSuperPropertyWrapper(expr.Loc, key)
didLower = true
}
case *js_ast.EIndex:
// "[super[foo]] = [bar]" => "[__superWrapper(this, foo)._] = [bar]"
if p.shouldLowerSuperPropertyAccess(e.Target) {
expr = p.callSuperPropertyWrapper(expr.Loc, e.Index)
didLower = true
break
}
// "[a.#b] = [c]" => "[__privateWrapper(a, #b)._] = [c]"
if private, ok := e.Index.Data.(*js_ast.EPrivateIdentifier); ok && p.privateSymbolNeedsToBeLowered(private) {
var target js_ast.Expr
switch p.symbols[private.Ref.InnerIndex].Kind {
case ast.SymbolPrivateSet, ast.SymbolPrivateStaticSet,
ast.SymbolPrivateGetSetPair, ast.SymbolPrivateStaticGetSetPair:
// "this.#setter" => "__privateWrapper(this, #setter, setter_set)"
fnRef := p.privateSetters[private.Ref]
p.recordUsage(fnRef)
target = p.callRuntime(expr.Loc, "__privateWrapper", []js_ast.Expr{
e.Target,
{Loc: expr.Loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
{Loc: expr.Loc, Data: &js_ast.EIdentifier{Ref: fnRef}},
})
default:
// "this.#field" => "__privateWrapper(this, #field)"
target = p.callRuntime(expr.Loc, "__privateWrapper", []js_ast.Expr{
e.Target,
{Loc: expr.Loc, Data: &js_ast.EIdentifier{Ref: private.Ref}},
})
}
// "__privateWrapper(this, #field)" => "__privateWrapper(this, #field)._"
expr.Data = &js_ast.EDot{Target: target, Name: "_", NameLoc: expr.Loc}
didLower = true
}
case *js_ast.EArray:
for i, item := range e.Items {
if item, ok := p.lowerSuperPropertyOrPrivateInAssign(item); ok {
e.Items[i] = item
didLower = true
}
}
case *js_ast.EObject:
for i, property := range e.Properties {
if property.ValueOrNil.Data != nil {
if value, ok := p.lowerSuperPropertyOrPrivateInAssign(property.ValueOrNil); ok {
e.Properties[i].ValueOrNil = value
didLower = true
}
}
}
}
return expr, didLower
}
func (p *parser) shouldLowerSuperPropertyAccess(expr js_ast.Expr) bool {
if p.fnOrArrowDataVisit.shouldLowerSuperPropertyAccess {
_, isSuper := expr.Data.(*js_ast.ESuper)
return isSuper
}
return false
}
func (p *parser) callSuperPropertyWrapper(loc logger.Loc, key js_ast.Expr) js_ast.Expr {
ref := *p.fnOnlyDataVisit.innerClassNameRef
p.recordUsage(ref)
class := js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{Ref: ref}}
this := js_ast.Expr{Loc: loc, Data: js_ast.EThisShared}
// Handle "this" in lowered static class field initializers
if p.fnOnlyDataVisit.shouldReplaceThisWithInnerClassNameRef {
p.recordUsage(ref)
this.Data = &js_ast.EIdentifier{Ref: ref}
}
if !p.fnOnlyDataVisit.isInStaticClassContext {
// "super.foo" => "__superWrapper(Class.prototype, this, 'foo')._"
// "super[foo]" => "__superWrapper(Class.prototype, this, foo)._"
class.Data = &js_ast.EDot{Target: class, NameLoc: loc, Name: "prototype"}
}
return js_ast.Expr{Loc: loc, Data: &js_ast.EDot{Target: p.callRuntime(loc, "__superWrapper", []js_ast.Expr{
class,
this,
key,
}), Name: "_", NameLoc: loc}}
}
func (p *parser) lowerSuperPropertyGet(loc logger.Loc, key js_ast.Expr) js_ast.Expr {
ref := *p.fnOnlyDataVisit.innerClassNameRef
p.recordUsage(ref)
class := js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{Ref: ref}}
this := js_ast.Expr{Loc: loc, Data: js_ast.EThisShared}
// Handle "this" in lowered static class field initializers
if p.fnOnlyDataVisit.shouldReplaceThisWithInnerClassNameRef {
p.recordUsage(ref)
this.Data = &js_ast.EIdentifier{Ref: ref}
}
if !p.fnOnlyDataVisit.isInStaticClassContext {
// "super.foo" => "__superGet(Class.prototype, this, 'foo')"
// "super[foo]" => "__superGet(Class.prototype, this, foo)"
class.Data = &js_ast.EDot{Target: class, NameLoc: loc, Name: "prototype"}
}
return p.callRuntime(loc, "__superGet", []js_ast.Expr{
class,
this,
key,
})
}
func (p *parser) lowerSuperPropertySet(loc logger.Loc, key js_ast.Expr, value js_ast.Expr) js_ast.Expr {
// "super.foo = bar" => "__superSet(Class, this, 'foo', bar)"
// "super[foo] = bar" => "__superSet(Class, this, foo, bar)"
ref := *p.fnOnlyDataVisit.innerClassNameRef
p.recordUsage(ref)
class := js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{Ref: ref}}
this := js_ast.Expr{Loc: loc, Data: js_ast.EThisShared}
// Handle "this" in lowered static class field initializers
if p.fnOnlyDataVisit.shouldReplaceThisWithInnerClassNameRef {
p.recordUsage(ref)
this.Data = &js_ast.EIdentifier{Ref: ref}
}
if !p.fnOnlyDataVisit.isInStaticClassContext {
// "super.foo = bar" => "__superSet(Class.prototype, this, 'foo', bar)"
// "super[foo] = bar" => "__superSet(Class.prototype, this, foo, bar)"
class.Data = &js_ast.EDot{Target: class, NameLoc: loc, Name: "prototype"}
}
return p.callRuntime(loc, "__superSet", []js_ast.Expr{
class,
this,
key,
value,
})
}
func (p *parser) lowerSuperPropertySetBinOp(loc logger.Loc, property js_ast.Expr, op js_ast.OpCode, value js_ast.Expr) js_ast.Expr {
// "super.foo += bar" => "__superSet(Class, this, 'foo', __superGet(Class, this, 'foo') + bar)"
// "super[foo] += bar" => "__superSet(Class, this, foo, __superGet(Class, this, foo) + bar)"
// "super[foo()] += bar" => "__superSet(Class, this, _a = foo(), __superGet(Class, this, _a) + bar)"
targetFunc, targetWrapFunc := p.captureValueWithPossibleSideEffects(property.Loc, 2, property, valueDefinitelyNotMutated)
return targetWrapFunc(p.lowerSuperPropertySet(loc, targetFunc(), js_ast.Expr{Loc: value.Loc, Data: &js_ast.EBinary{
Op: op,
Left: p.lowerSuperPropertyGet(loc, targetFunc()),
Right: value,
}}))
}
func (p *parser) maybeLowerSuperPropertyGetInsideCall(call *js_ast.ECall) {
var key js_ast.Expr
switch e := call.Target.Data.(type) {
case *js_ast.EDot:
// Lower "super.prop" if necessary
if !p.shouldLowerSuperPropertyAccess(e.Target) {
return
}
key = js_ast.Expr{Loc: e.NameLoc, Data: &js_ast.EString{Value: helpers.StringToUTF16(e.Name)}}
case *js_ast.EIndex:
// Lower "super[prop]" if necessary
if !p.shouldLowerSuperPropertyAccess(e.Target) {
return
}
key = e.Index
default:
return
}
// "super.foo(a, b)" => "__superGet(Class, this, 'foo').call(this, a, b)"
call.Target.Data = &js_ast.EDot{
Target: p.lowerSuperPropertyGet(call.Target.Loc, key),
NameLoc: key.Loc,
Name: "call",
}
thisExpr := js_ast.Expr{Loc: call.Target.Loc, Data: js_ast.EThisShared}
call.Args = append([]js_ast.Expr{thisExpr}, call.Args...)
}
type classLoweringInfo struct {
lowerAllInstanceFields bool
lowerAllStaticFields bool
shimSuperCtorCalls bool
}
func (p *parser) computeClassLoweringInfo(class *js_ast.Class) (result classLoweringInfo) {
// Name keeping for classes is implemented with a static block. So we need to
// lower all static fields if static blocks are unsupported so that the name
// keeping comes first before other static initializers.
if p.options.keepNames && p.options.unsupportedJSFeatures.Has(compat.ClassStaticBlocks) {
result.lowerAllStaticFields = true
}
// TypeScript's "experimentalDecorators" feature replaces all references of
// the class name with the decorated class after class decorators have run.
// This cannot be done by only reassigning to the class symbol in JavaScript
// because it's shadowed by the class name within the class body. Instead,
// we need to hoist all code in static contexts out of the class body so
// that it's no longer shadowed:
//
// const decorate = x => ({ x })
// @decorate
// class Foo {
// static oldFoo = Foo
// static newFoo = () => Foo
// }
// console.log('This must be false:', Foo.x.oldFoo === Foo.x.newFoo())
//
if p.options.ts.Parse && p.options.ts.Config.ExperimentalDecorators == config.True && len(class.Decorators) > 0 {
result.lowerAllStaticFields = true
}
// Conservatively lower fields of a given type (instance or static) when any
// member of that type needs to be lowered. This must be done to preserve
// evaluation order. For example:
//
// class Foo {
// #foo = 123
// bar = this.#foo
// }
//
// It would be bad if we transformed that into something like this:
//
// var _foo;
// class Foo {
// constructor() {
// _foo.set(this, 123);
// }
// bar = __privateGet(this, _foo);
// }
// _foo = new WeakMap();
//
// That evaluates "bar" then "foo" instead of "foo" then "bar" like the
// original code. We need to do this instead:
//
// var _foo;
// class Foo {
// constructor() {
// _foo.set(this, 123);
// __publicField(this, "bar", __privateGet(this, _foo));
// }
// }
// _foo = new WeakMap();
//
for _, prop := range class.Properties {
if prop.Kind == js_ast.PropertyClassStaticBlock {
if p.options.unsupportedJSFeatures.Has(compat.ClassStaticBlocks) {
result.lowerAllStaticFields = true
}
continue
}
if private, ok := prop.Key.Data.(*js_ast.EPrivateIdentifier); ok {
if prop.Flags.Has(js_ast.PropertyIsStatic) {
if p.privateSymbolNeedsToBeLowered(private) {
result.lowerAllStaticFields = true
}
} else {
if p.privateSymbolNeedsToBeLowered(private) {
result.lowerAllInstanceFields = true
// We can't transform this:
//
// class Foo {
// #foo = 123
// static bar = new Foo().#foo
// }
//
// into this:
//
// var _foo;
// const _Foo = class {
// constructor() {
// _foo.set(this, 123);
// }
// static bar = __privateGet(new _Foo(), _foo);
// };
// let Foo = _Foo;
// _foo = new WeakMap();
//
// because "_Foo" won't be initialized in the initializer for "bar".
// So we currently lower all static fields in this case too. This
// isn't great and it would be good to find a way to avoid this.
// The inner class name symbol substitution mechanism should probably
// be rethought.
result.lowerAllStaticFields = true
}
}
continue
}
if prop.Kind == js_ast.PropertyAutoAccessor {
if prop.Flags.Has(js_ast.PropertyIsStatic) {
if p.options.unsupportedJSFeatures.Has(compat.ClassPrivateStaticField) {
result.lowerAllStaticFields = true
}
} else {
if p.options.unsupportedJSFeatures.Has(compat.ClassPrivateField) {
result.lowerAllInstanceFields = true
result.lowerAllStaticFields = true
}
}
continue
}
// This doesn't come before the private member check above because
// unsupported private methods must also trigger field lowering:
//
// class Foo {
// bar = this.#foo()
// #foo() {}
// }
//
// It would be bad if we transformed that to something like this:
//
// var _foo, foo_fn;
// class Foo {
// constructor() {
// _foo.add(this);
// }
// bar = __privateMethod(this, _foo, foo_fn).call(this);
// }
// _foo = new WeakSet();
// foo_fn = function() {
// };
//
// In that case the initializer of "bar" would fail to call "#foo" because
// it's only added to the instance in the body of the constructor.
if prop.Flags.Has(js_ast.PropertyIsMethod) {
// We need to shim "super()" inside the constructor if this is a derived
// class and the constructor has any parameter properties, since those
// use "this" and we can only access "this" after "super()" is called
if class.ExtendsOrNil.Data != nil {
if key, ok := prop.Key.Data.(*js_ast.EString); ok && helpers.UTF16EqualsString(key.Value, "constructor") {
if fn, ok := prop.ValueOrNil.Data.(*js_ast.EFunction); ok {
for _, arg := range fn.Fn.Args {
if arg.IsTypeScriptCtorField {
result.shimSuperCtorCalls = true
break
}
}
}
}
}
continue
}
if prop.Flags.Has(js_ast.PropertyIsStatic) {
// Static fields must be lowered if the target doesn't support them
if p.options.unsupportedJSFeatures.Has(compat.ClassStaticField) {
result.lowerAllStaticFields = true
}
// Convert static fields to assignment statements if the TypeScript
// setting for this is enabled. I don't think this matters for private
// fields because there's no way for this to call a setter in the base
// class, so this isn't done for private fields.
//
// If class static blocks are supported, then we can do this inline
// without needing to move the initializers outside of the class body.
// Otherwise, we need to lower all static class fields.
if p.options.ts.Parse && !class.UseDefineForClassFields && p.options.unsupportedJSFeatures.Has(compat.ClassStaticBlocks) {
result.lowerAllStaticFields = true
}
} else {
// Instance fields must be lowered if the target doesn't support them
if p.options.unsupportedJSFeatures.Has(compat.ClassField) {
result.lowerAllInstanceFields = true
}
// Convert instance fields to assignment statements if the TypeScript
// setting for this is enabled. I don't think this matters for private
// fields because there's no way for this to call a setter in the base
// class, so this isn't done for private fields.
if p.options.ts.Parse && !class.UseDefineForClassFields {
result.lowerAllInstanceFields = true
}
}
}
// We need to shim "super()" inside the constructor if this is a derived
// class and there are any instance fields that need to be lowered, since
// those use "this" and we can only access "this" after "super()" is called
if result.lowerAllInstanceFields && class.ExtendsOrNil.Data != nil {
result.shimSuperCtorCalls = true
}
return
}
// Apply all relevant transforms to a class object (either a statement or an
// expression) including:
//
// - Transforming class fields for older environments
// - Transforming static blocks for older environments
// - Transforming TypeScript experimental decorators into JavaScript
// - Transforming TypeScript class fields into assignments for "useDefineForClassFields"
//
// Note that this doesn't transform any nested AST subtrees inside the class
// body (e.g. the contents of initializers, methods, and static blocks). Those
// have already been transformed by "visitClass" by this point. It's done that
// way for performance so that we don't need to do another AST pass.
func (p *parser) lowerClass(stmt js_ast.Stmt, expr js_ast.Expr, result visitClassResult) ([]js_ast.Stmt, js_ast.Expr) {
type classKind uint8
const (
classKindExpr classKind = iota
classKindStmt
classKindExportStmt
classKindExportDefaultStmt
)
// Unpack the class from the statement or expression
var kind classKind
var class *js_ast.Class
var classLoc logger.Loc
var defaultName ast.LocRef
if stmt.Data == nil {
e, _ := expr.Data.(*js_ast.EClass)
class = &e.Class
kind = classKindExpr
if class.Name != nil {
symbol := &p.symbols[class.Name.Ref.InnerIndex]
// The inner class name inside the class expression should be the same as
// the class expression name itself
if result.innerClassNameRef != ast.InvalidRef {
p.mergeSymbols(result.innerClassNameRef, class.Name.Ref)
}
// Remove unused class names when minifying. Check this after we merge in
// the inner class name above since that will adjust the use count.
if p.options.minifySyntax && symbol.UseCountEstimate == 0 {
class.Name = nil
}
}
} else if s, ok := stmt.Data.(*js_ast.SClass); ok {
class = &s.Class
if s.IsExport {
kind = classKindExportStmt
} else {
kind = classKindStmt
}
} else {
s, _ := stmt.Data.(*js_ast.SExportDefault)
s2, _ := s.Value.Data.(*js_ast.SClass)
class = &s2.Class
defaultName = s.DefaultName
kind = classKindExportDefaultStmt
}
if stmt.Data == nil {
classLoc = expr.Loc
} else {
classLoc = stmt.Loc
}
var ctor *js_ast.EFunction
var parameterFields []js_ast.Stmt
var instanceMembers []js_ast.Stmt
var instancePrivateMethods []js_ast.Stmt
// These expressions are generated after the class body, in this order
var computedPropertyCache js_ast.Expr
var privateMembers []js_ast.Expr
var staticMembers []js_ast.Expr
var staticPrivateMethods []js_ast.Expr
var instanceDecorators []js_ast.Expr
var staticDecorators []js_ast.Expr
// These are only for class expressions that need to be captured
var nameFunc func() js_ast.Expr
var wrapFunc func(js_ast.Expr) js_ast.Expr
didCaptureClassExpr := false
// Class statements can be missing a name if they are in an
// "export default" statement:
//
// export default class {
// static foo = 123
// }
//
nameFunc = func() js_ast.Expr {
if kind == classKindExpr {
// If this is a class expression, capture and store it. We have to
// do this even if it has a name since the name isn't exposed
// outside the class body.
classExpr := &js_ast.EClass{Class: *class}
class = &classExpr.Class
nameFunc, wrapFunc = p.captureValueWithPossibleSideEffects(classLoc, 2, js_ast.Expr{Loc: classLoc, Data: classExpr}, valueDefinitelyNotMutated)
expr = nameFunc()
didCaptureClassExpr = true
name := nameFunc()
// If we're storing the class expression in a variable, remove the class
// name and rewrite all references to the class name with references to
// the temporary variable holding the class expression. This ensures that
// references to the class expression by name in any expressions that end
// up being pulled outside of the class body still work. For example:
//
// let Bar = class Foo {
// static foo = 123
// static bar = Foo.foo
// }
//
// This might be converted into the following:
//
// var _a;
// let Bar = (_a = class {
// }, _a.foo = 123, _a.bar = _a.foo, _a);
//
if class.Name != nil {
p.mergeSymbols(class.Name.Ref, name.Data.(*js_ast.EIdentifier).Ref)
class.Name = nil
}
return name
} else {
// If anything referenced the inner class name, then we should use that
// name for any automatically-generated initialization code, since it
// will come before the outer class name is initialized.
if result.innerClassNameRef != ast.InvalidRef {
p.recordUsage(result.innerClassNameRef)
return js_ast.Expr{Loc: class.Name.Loc, Data: &js_ast.EIdentifier{Ref: result.innerClassNameRef}}
}
// Otherwise we should just use the outer class name
if class.Name == nil {
if kind == classKindExportDefaultStmt {
class.Name = &defaultName
} else {
class.Name = &ast.LocRef{Loc: classLoc, Ref: p.generateTempRef(tempRefNoDeclare, "")}
}
}
p.recordUsage(class.Name.Ref)
return js_ast.Expr{Loc: class.Name.Loc, Data: &js_ast.EIdentifier{Ref: class.Name.Ref}}
}
}
// Handle lowering of instance and static fields. Move their initializers
// from the class body to either the constructor (instance fields) or after
// the class (static fields).
//
// If this returns true, the return property should be added to the class
// body. Otherwise the property should be omitted from the class body.
lowerField := func(prop js_ast.Property, private *js_ast.EPrivateIdentifier, shouldOmitFieldInitializer bool, staticFieldToBlockAssign bool) (js_ast.Property, bool) {
mustLowerPrivate := private != nil && p.privateSymbolNeedsToBeLowered(private)
// The TypeScript compiler doesn't follow the JavaScript spec for
// uninitialized fields. They are supposed to be set to undefined but the
// TypeScript compiler just omits them entirely.
if !shouldOmitFieldInitializer {
loc := prop.Loc
// Determine where to store the field
var target js_ast.Expr
if prop.Flags.Has(js_ast.PropertyIsStatic) && !staticFieldToBlockAssign {
target = nameFunc()
} else {
target = js_ast.Expr{Loc: loc, Data: js_ast.EThisShared}
}
// Generate the assignment initializer
var init js_ast.Expr
if prop.InitializerOrNil.Data != nil {
init = prop.InitializerOrNil
} else {
init = js_ast.Expr{Loc: loc, Data: js_ast.EUndefinedShared}
}
// Generate the assignment target
var memberExpr js_ast.Expr
if mustLowerPrivate {
// Generate a new symbol for this private field
ref := p.generateTempRef(tempRefNeedsDeclare, "_"+p.symbols[private.Ref.InnerIndex].OriginalName[1:])
p.symbols[private.Ref.InnerIndex].Link = ref
// Initialize the private field to a new WeakMap
if p.weakMapRef == ast.InvalidRef {
p.weakMapRef = p.newSymbol(ast.SymbolUnbound, "WeakMap")
p.moduleScope.Generated = append(p.moduleScope.Generated, p.weakMapRef)
}
privateMembers = append(privateMembers, js_ast.Assign(
js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: ref}},
js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.ENew{Target: js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: p.weakMapRef}}}},
))
p.recordUsage(ref)
// Add every newly-constructed instance into this map
memberExpr = p.callRuntime(loc, "__privateAdd", []js_ast.Expr{
target,
{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: ref}},
init,
})
p.recordUsage(ref)
} else if private == nil && class.UseDefineForClassFields {
var args []js_ast.Expr
if _, ok := init.Data.(*js_ast.EUndefined); ok {
args = []js_ast.Expr{target, prop.Key}
} else {
args = []js_ast.Expr{target, prop.Key, init}
}
memberExpr = js_ast.Expr{Loc: loc, Data: &js_ast.ECall{
Target: p.importFromRuntime(loc, "__publicField"),
Args: args,
}}
} else {
if key, ok := prop.Key.Data.(*js_ast.EString); ok && !prop.Flags.Has(js_ast.PropertyIsComputed) && !prop.Flags.Has(js_ast.PropertyPreferQuotedKey) {
target = js_ast.Expr{Loc: loc, Data: &js_ast.EDot{
Target: target,
Name: helpers.UTF16ToString(key.Value),
NameLoc: prop.Key.Loc,
}}
} else {
target = js_ast.Expr{Loc: loc, Data: &js_ast.EIndex{
Target: target,
Index: prop.Key,
}}
}
memberExpr = js_ast.Assign(target, init)
}
if prop.Flags.Has(js_ast.PropertyIsStatic) {
// Move this property to an assignment after the class ends
if staticFieldToBlockAssign {
// Use inline assignment in a static block instead of lowering
return js_ast.Property{
Loc: loc,
Kind: js_ast.PropertyClassStaticBlock,
ClassStaticBlock: &js_ast.ClassStaticBlock{
Loc: loc,
Block: js_ast.SBlock{Stmts: []js_ast.Stmt{
{Loc: loc, Data: &js_ast.SExpr{Value: memberExpr}}},
},
},
}, true
} else {
// Move this property to an assignment after the class ends
staticMembers = append(staticMembers, memberExpr)
}
} else {
// Move this property to an assignment inside the class constructor
instanceMembers = append(instanceMembers, js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: memberExpr}})
}
}
if private == nil || mustLowerPrivate {
// Remove the field from the class body
return js_ast.Property{}, false
}
// Keep the private field but remove the initializer
prop.InitializerOrNil = js_ast.Expr{}
return prop, true
}
// If this returns true, the method property should be dropped as it has
// already been accounted for elsewhere (e.g. a lowered private method).
lowerMethod := func(prop js_ast.Property, private *js_ast.EPrivateIdentifier) bool {
if private != nil && p.privateSymbolNeedsToBeLowered(private) {
loc := prop.Loc
// Don't generate a symbol for a getter/setter pair twice
if p.symbols[private.Ref.InnerIndex].Link == ast.InvalidRef {
// Generate a new symbol for this private method
ref := p.generateTempRef(tempRefNeedsDeclare, "_"+p.symbols[private.Ref.InnerIndex].OriginalName[1:])
p.symbols[private.Ref.InnerIndex].Link = ref
// Initialize the private method to a new WeakSet
if p.weakSetRef == ast.InvalidRef {
p.weakSetRef = p.newSymbol(ast.SymbolUnbound, "WeakSet")
p.moduleScope.Generated = append(p.moduleScope.Generated, p.weakSetRef)
}
privateMembers = append(privateMembers, js_ast.Assign(
js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: ref}},
js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.ENew{Target: js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: p.weakSetRef}}}},
))
p.recordUsage(ref)
// Determine where to store the private method
var target js_ast.Expr
if prop.Flags.Has(js_ast.PropertyIsStatic) {
target = nameFunc()
} else {
target = js_ast.Expr{Loc: loc, Data: js_ast.EThisShared}
}
// Add every newly-constructed instance into this map
methodExpr := p.callRuntime(loc, "__privateAdd", []js_ast.Expr{
target,
{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: ref}},
})
p.recordUsage(ref)
// Make sure that adding to the map happens before any field
// initializers to handle cases like this:
//
// class A {
// pub = this.#priv;
// #priv() {}
// }
//
if prop.Flags.Has(js_ast.PropertyIsStatic) {
// Move this property to an assignment after the class ends
staticPrivateMethods = append(staticPrivateMethods, methodExpr)
} else {
// Move this property to an assignment inside the class constructor
instancePrivateMethods = append(instancePrivateMethods, js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: methodExpr}})
}
}
// Move the method definition outside the class body
methodRef := p.generateTempRef(tempRefNeedsDeclare, "_")
if prop.Kind == js_ast.PropertySet {
p.symbols[methodRef.InnerIndex].Link = p.privateSetters[private.Ref]
} else {
p.symbols[methodRef.InnerIndex].Link = p.privateGetters[private.Ref]
}
p.recordUsage(methodRef)
privateMembers = append(privateMembers, js_ast.Assign(
js_ast.Expr{Loc: prop.Key.Loc, Data: &js_ast.EIdentifier{Ref: methodRef}},
prop.ValueOrNil,
))
return true
}
if key, ok := prop.Key.Data.(*js_ast.EString); ok && helpers.UTF16EqualsString(key.Value, "constructor") {
if fn, ok := prop.ValueOrNil.Data.(*js_ast.EFunction); ok {
// Remember where the constructor is for later
ctor = fn
// Initialize TypeScript constructor parameter fields
if p.options.ts.Parse {
for _, arg := range ctor.Fn.Args {
if arg.IsTypeScriptCtorField {
if id, ok := arg.Binding.Data.(*js_ast.BIdentifier); ok {
parameterFields = append(parameterFields, js_ast.AssignStmt(
js_ast.Expr{Loc: arg.Binding.Loc, Data: p.dotOrMangledPropVisit(
js_ast.Expr{Loc: arg.Binding.Loc, Data: js_ast.EThisShared},
p.symbols[id.Ref.InnerIndex].OriginalName,
arg.Binding.Loc,
)},
js_ast.Expr{Loc: arg.Binding.Loc, Data: &js_ast.EIdentifier{Ref: id.Ref}},
))
}
}
}
}
}
}
return false
}
classLoweringInfo := p.computeClassLoweringInfo(class)
properties := make([]js_ast.Property, 0, len(class.Properties))
autoAccessorCount := 0
for _, prop := range class.Properties {
if prop.Kind == js_ast.PropertyClassStaticBlock {
// Drop empty class blocks when minifying
if p.options.minifySyntax && len(prop.ClassStaticBlock.Block.Stmts) == 0 {
continue
}
if classLoweringInfo.lowerAllStaticFields {
block := *prop.ClassStaticBlock
isAllExprs := []js_ast.Expr{}
// Are all statements in the block expression statements?
loop:
for _, stmt := range block.Block.Stmts {
switch s := stmt.Data.(type) {
case *js_ast.SEmpty:
// Omit stray semicolons completely
case *js_ast.SExpr:
isAllExprs = append(isAllExprs, s.Value)
default:
isAllExprs = nil
break loop
}
}
if isAllExprs != nil {
// I think it should be safe to inline the static block IIFE here
// since all uses of "this" should have already been replaced by now.
staticMembers = append(staticMembers, isAllExprs...)
} else {
// But if there is a non-expression statement, fall back to using an
// IIFE since we may be in an expression context and can't use a block.
staticMembers = append(staticMembers, js_ast.Expr{Loc: prop.Loc, Data: &js_ast.ECall{
Target: js_ast.Expr{Loc: prop.Loc, Data: &js_ast.EArrow{Body: js_ast.FnBody{
Loc: block.Loc,
Block: block.Block,
}}},
CanBeUnwrappedIfUnused: p.astHelpers.StmtsCanBeRemovedIfUnused(block.Block.Stmts, 0),
}})
}
continue
}
// Keep this property