-
Notifications
You must be signed in to change notification settings - Fork 12.3k
/
classFields.ts
3316 lines (2985 loc) · 152 KB
/
classFields.ts
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
import {
__String,
AccessorDeclaration,
accessPrivateIdentifier as accessPrivateIdentifierCommon,
addEmitFlags,
addEmitHelpers,
addRange,
AnonymousFunctionDefinition,
append,
ArrayAssignmentElement,
AssignmentExpression,
AssignmentOperator,
AssignmentPattern,
AutoAccessorPropertyDeclaration,
BinaryExpression,
BindingElement,
Bundle,
CallExpression,
chainBundle,
ClassDeclaration,
ClassElement,
ClassExpression,
classHasClassThisAssignment,
classHasExplicitlyAssignedName,
ClassLikeDeclaration,
classOrConstructorParameterIsDecorated,
ClassStaticBlockDeclaration,
CommaListExpression,
compact,
ComputedPropertyName,
ConstructorDeclaration,
createAccessorPropertyBackingField,
createAccessorPropertyGetRedirector,
createAccessorPropertySetRedirector,
createMemberAccessForPropertyName,
Debug,
ElementAccessExpression,
EmitFlags,
EmitHint,
EqualsToken,
expandPreOrPostfixIncrementOrDecrementExpression,
ExportAssignment,
Expression,
ExpressionStatement,
ExpressionWithTypeArguments,
filter,
find,
findComputedPropertyNameCacheAssignment,
findSuperStatementIndexPath,
flattenCommaList,
ForStatement,
GeneratedIdentifier,
GeneratedIdentifierFlags,
GeneratedNamePart,
GetAccessorDeclaration,
getCommentRange,
getEffectiveBaseTypeNode,
getEmitFlags,
getEmitScriptTarget,
getInternalEmitFlags,
getNameOfDeclaration,
getNonAssignmentOperatorForCompoundAssignment,
getOriginalNode,
getOriginalNodeId,
getPrivateIdentifier,
getProperties,
getSourceMapRange,
getStaticPropertiesAndClassStaticBlock,
getUseDefineForClassFields,
hasAbstractModifier,
hasAccessorModifier,
hasDecorators,
hasStaticModifier,
hasSyntacticModifier,
Identifier,
InKeyword,
InternalEmitFlags,
isAccessor,
isAccessorModifier,
isArrayBindingOrAssignmentElement,
isArrayLiteralExpression,
isArrowFunction,
isAssignmentExpression,
isAutoAccessorPropertyDeclaration,
isBlock,
isCallChain,
isCallToHelper,
isCatchClause,
isClassDeclaration,
isClassElement,
isClassExpression,
isClassNamedEvaluationHelperBlock,
isClassStaticBlockDeclaration,
isClassThisAssignmentBlock,
isCommaExpression,
isCompoundAssignment,
isComputedPropertyName,
isConstructorDeclaration,
isDestructuringAssignment,
isElementAccessExpression,
isExportOrDefaultModifier,
isExpression,
isForInitializer,
isGeneratedIdentifier,
isGeneratedPrivateIdentifier,
isGetAccessor,
isGetAccessorDeclaration,
isHeritageClause,
isIdentifier,
isIdentifierText,
isInitializedProperty,
isLeftHandSideExpression,
isMethodDeclaration,
isModifier,
isModifierLike,
isNamedEvaluation,
isNonStaticMethodOrAccessorWithPrivateName,
isNumericLiteral,
isObjectBindingOrAssignmentElement,
isObjectLiteralElementLike,
isObjectLiteralExpression,
isOmittedExpression,
isParameter,
isParameterPropertyDeclaration,
isParenthesizedExpression,
isPrefixUnaryExpression,
isPrivateIdentifier,
isPrivateIdentifierClassElementDeclaration,
isPrivateIdentifierPropertyAccessExpression,
isPropertyAccessExpression,
isPropertyAssignment,
isPropertyDeclaration,
isPropertyName,
isSetAccessor,
isSetAccessorDeclaration,
isShorthandPropertyAssignment,
isSimpleCopiableExpression,
isSimpleInlineableExpression,
isSpreadAssignment,
isSpreadElement,
isStatement,
isStatic,
isStaticModifier,
isStringLiteral,
isSuperProperty,
isTemplateLiteral,
isThisProperty,
isTryStatement,
isVoidExpression,
LeftHandSideExpression,
LexicalEnvironment,
map,
MethodDeclaration,
Modifier,
ModifierFlags,
ModifierLike,
modifiersToFlags,
moveRangePastModifiers,
moveRangePos,
newPrivateEnvironment,
Node,
NodeArray,
NodeCheckFlags,
NodeFactory,
nodeIsSynthesized,
ObjectLiteralElement,
OmittedExpression,
OuterExpressionKinds,
ParameterDeclaration,
ParenthesizedExpression,
PostfixUnaryExpression,
PrefixUnaryExpression,
PrivateEnvironment,
PrivateIdentifier,
PrivateIdentifierAccessorDeclaration,
PrivateIdentifierKind,
PrivateIdentifierMethodDeclaration,
PrivateIdentifierPropertyAccessExpression,
PrivateIdentifierPropertyDeclaration,
PropertyAccessExpression,
PropertyAssignment,
PropertyDeclaration,
PropertyName,
removeAllComments,
ScriptTarget,
SetAccessorDeclaration,
setCommentRange,
setEmitFlags,
setOriginalNode,
setPrivateIdentifier,
setSourceMapRange,
setSyntheticLeadingComments,
setSyntheticTrailingComments,
setTextRange,
ShorthandPropertyAssignment,
skipOuterExpressions,
skipParentheses,
skipPartiallyEmittedExpressions,
some,
SourceFile,
SpreadAssignment,
SpreadElement,
startOnNewLine,
Statement,
SuperProperty,
SyntaxKind,
TaggedTemplateExpression,
Ternary,
ThisExpression,
TransformationContext,
TransformFlags,
transformNamedEvaluation,
tryCast,
tryGetTextOfPropertyName,
unescapeLeadingUnderscores,
VariableDeclaration,
VariableStatement,
visitArray,
visitCommaListElements,
visitEachChild,
visitFunctionBody,
visitIterationBody,
visitNode,
visitNodes,
Visitor,
visitParameterList,
VisitResult
} from "../_namespaces/ts";
const enum ClassPropertySubstitutionFlags {
/**
* Enables substitutions for class expressions with static fields
* which have initializers that reference the class name.
*/
ClassAliases = 1 << 0,
/**
* Enables substitutions for class expressions with static fields
* which have initializers that reference the 'this' or 'super'.
*/
ClassStaticThisOrSuperReference = 1 << 1,
}
interface PrivateIdentifierInfoBase {
/**
* brandCheckIdentifier can contain:
* - For instance field: The WeakMap that will be the storage for the field.
* - For instance methods or accessors: The WeakSet that will be used for brand checking.
* - For static members: The constructor that will be used for brand checking.
*/
brandCheckIdentifier: Identifier;
/**
* Stores if the identifier is static or not
*/
isStatic: boolean;
/**
* Stores if the identifier declaration is valid or not. Reserved names (e.g. #constructor)
* or duplicate identifiers are considered invalid.
*/
isValid: boolean;
}
interface PrivateIdentifierAccessorInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Accessor;
/**
* Identifier for a variable that will contain the private get accessor implementation, if any.
*/
getterName?: Identifier;
/**
* Identifier for a variable that will contain the private set accessor implementation, if any.
*/
setterName?: Identifier;
}
interface PrivateIdentifierMethodInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Method;
/**
* Identifier for a variable that will contain the private method implementation.
*/
methodName: Identifier;
}
interface PrivateIdentifierInstanceFieldInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Field;
isStatic: false;
}
interface PrivateIdentifierStaticFieldInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Field;
isStatic: true;
/**
* Contains the variable that will serve as the storage for the field.
*/
variableName: Identifier;
}
interface PrivateEnvironmentData {
/**
* Used for prefixing generated variable names.
*/
className?: Identifier;
/**
* Used for brand check on private methods.
*/
weakSetName?: Identifier;
}
interface UntransformedPrivateIdentifierInfo {
kind: "untransformed";
}
type PrivateIdentifierInfo =
| PrivateIdentifierMethodInfo
| PrivateIdentifierInstanceFieldInfo
| PrivateIdentifierStaticFieldInfo
| PrivateIdentifierAccessorInfo
| UntransformedPrivateIdentifierInfo;
interface ClassLexicalEnvironment {
facts: ClassFacts;
/**
* Used for brand checks on static members, and `this` references in static initializers
*/
classConstructor: Identifier | undefined;
classThis: Identifier | undefined;
/**
* Used for `super` references in static initializers.
*/
superClassReference: Identifier | undefined;
}
const enum ClassFacts {
None = 0,
ClassWasDecorated = 1 << 0,
NeedsClassConstructorReference = 1 << 1,
NeedsClassSuperReference = 1 << 2,
NeedsSubstitutionForThisInClassStaticField = 1 << 3,
WillHoistInitializersToConstructor = 1 << 4,
}
type LexicalEnv = LexicalEnvironment<ClassLexicalEnvironment | undefined, PrivateEnvironmentData, PrivateIdentifierInfo>;
type PrivateEnv = PrivateEnvironment<PrivateEnvironmentData, PrivateIdentifierInfo>;
/**
* Transforms ECMAScript Class Syntax.
* TypeScript parameter property syntax is transformed in the TypeScript transformer.
* For now, this transforms public field declarations using TypeScript class semantics,
* where declarations are elided and initializers are transformed as assignments in the constructor.
* When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
*
* @internal
*/
export function transformClassFields(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle {
const {
factory,
getEmitHelperFactory: emitHelpers,
hoistVariableDeclaration,
endLexicalEnvironment,
startLexicalEnvironment,
resumeLexicalEnvironment,
addBlockScopedVariable
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
const legacyDecorators = !!compilerOptions.experimentalDecorators;
// Always transform field initializers using Set semantics when `useDefineForClassFields: false`.
const shouldTransformInitializersUsingSet = !useDefineForClassFields;
// Transform field initializers using Define semantics when `useDefineForClassFields: true` and target < ES2022.
const shouldTransformInitializersUsingDefine = useDefineForClassFields && languageVersion < ScriptTarget.ES2022;
const shouldTransformInitializers = shouldTransformInitializersUsingSet || shouldTransformInitializersUsingDefine;
// We need to transform private members and class static blocks when target < ES2022.
const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < ScriptTarget.ES2022;
// We need to transform `accessor` fields when target < ESNext.
// We may need to transform `accessor` fields when `useDefineForClassFields: false`
const shouldTransformAutoAccessors =
languageVersion < ScriptTarget.ESNext ? Ternary.True :
!useDefineForClassFields ? Ternary.Maybe :
Ternary.False;
// We need to transform `this` in a static initializer into a reference to the class
// when target < ES2022 since the assignment will be moved outside of the class body.
const shouldTransformThisInStaticInitializers = languageVersion < ScriptTarget.ES2022;
// We don't need to transform `super` property access when target <= ES5 because
// the es2015 transformation handles those.
const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= ScriptTarget.ES2015;
const shouldTransformAnything =
shouldTransformInitializers ||
shouldTransformPrivateElementsOrClassStaticBlocks ||
shouldTransformAutoAccessors === Ternary.True;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
let shouldTransformPrivateStaticElementsInFile = false;
let enabledSubstitutions: ClassPropertySubstitutionFlags;
let classAliases: Identifier[];
/**
* Tracks what computed name expressions originating from elided names must be inlined
* at the next execution site, in document order
*/
let pendingExpressions: Expression[] | undefined;
/**
* Tracks what computed name expression statements and static property initializers must be
* emitted at the next execution site, in document order (for decorated classes).
*/
let pendingStatements: Statement[] | undefined;
let lexicalEnvironment: LexicalEnv | undefined;
const lexicalEnvironmentMap = new Map<Node, LexicalEnv>();
// Nodes that should not be replaced during emit substitution.
const noSubstitution = new Set<Node>();
let currentClassContainer: ClassLikeDeclaration | undefined;
let currentClassElement: ClassElement | undefined;
let shouldSubstituteThisWithClassThis = false;
let previousShouldSubstituteThisWithClassThis = false;
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
lexicalEnvironment = undefined;
shouldTransformPrivateStaticElementsInFile = !!(getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements);
if (!shouldTransformAnything && !shouldTransformPrivateStaticElementsInFile) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function modifierVisitor(node: ModifierLike): VisitResult<Modifier | undefined> {
switch (node.kind) {
case SyntaxKind.AccessorKeyword:
return shouldTransformAutoAccessorsInCurrentClass() ? undefined : node;
default:
return tryCast(node, isModifier);
}
}
function visitor(node: Node): VisitResult<Node> {
if (!(node.transformFlags & TransformFlags.ContainsClassFields) &&
!(node.transformFlags & TransformFlags.ContainsLexicalThisOrSuper)) {
return node;
}
switch (node.kind) {
case SyntaxKind.AccessorKeyword:
return Debug.fail("Use `modifierVisitor` instead.");
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ClassExpression:
return visitClassExpression(node as ClassExpression);
case SyntaxKind.ClassStaticBlockDeclaration:
case SyntaxKind.PropertyDeclaration:
return Debug.fail("Use `classElementVisitor` instead.");
case SyntaxKind.PropertyAssignment:
return visitPropertyAssignment(node as PropertyAssignment);
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.Parameter:
return visitParameterDeclaration(node as ParameterDeclaration);
case SyntaxKind.BindingElement:
return visitBindingElement(node as BindingElement);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(node as ExportAssignment);
case SyntaxKind.PrivateIdentifier:
return visitPrivateIdentifier(node as PrivateIdentifier);
case SyntaxKind.PropertyAccessExpression:
return visitPropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return visitElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ false);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, /*discarded*/ false);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false);
case SyntaxKind.CallExpression:
return visitCallExpression(node as CallExpression);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.ThisKeyword:
return visitThisExpression(node as ThisExpression);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
// If we are descending into a new scope, clear the current class element
return setCurrentClassElementAnd(
/*classElement*/ undefined,
fallbackVisitor,
node
);
case SyntaxKind.Constructor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor: {
// If we are descending into a class element, set the class element
return setCurrentClassElementAnd(
node as ConstructorDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration,
fallbackVisitor,
node
);
}
default:
return fallbackVisitor(node);
}
}
function fallbackVisitor(node: Node) {
return visitEachChild(node, visitor, context);
}
/**
* Visits a node in an expression whose result is discarded.
*/
function discardedValueVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ true);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, /*discarded*/ true);
case SyntaxKind.CommaListExpression:
return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true);
default:
return visitor(node);
}
}
/**
* Visits a node in a {@link HeritageClause}.
*/
function heritageClauseVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.HeritageClause:
return visitEachChild(node, heritageClauseVisitor, context);
case SyntaxKind.ExpressionWithTypeArguments:
return visitExpressionWithTypeArgumentsInHeritageClause(node as ExpressionWithTypeArguments);
default:
return visitor(node);
}
}
/**
* Visits the assignment target of a destructuring assignment.
*/
function assignmentTargetVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ArrayLiteralExpression:
return visitAssignmentPattern(node as AssignmentPattern);
default:
return visitor(node);
}
}
/**
* Visits a member of a class.
*/
function classElementVisitor(node: Node): VisitResult<Node | undefined> {
switch (node.kind) {
case SyntaxKind.Constructor:
return setCurrentClassElementAnd(
node as ConstructorDeclaration,
visitConstructorDeclaration,
node as ConstructorDeclaration);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
return setCurrentClassElementAnd(
node as MethodDeclaration | AccessorDeclaration,
visitMethodOrAccessorDeclaration,
node as MethodDeclaration | AccessorDeclaration);
case SyntaxKind.PropertyDeclaration:
return setCurrentClassElementAnd(
node as PropertyDeclaration,
visitPropertyDeclaration,
node as PropertyDeclaration);
case SyntaxKind.ClassStaticBlockDeclaration:
return setCurrentClassElementAnd(
node as ClassStaticBlockDeclaration,
visitClassStaticBlockDeclaration,
node as ClassStaticBlockDeclaration);
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(node as ComputedPropertyName);
case SyntaxKind.SemicolonClassElement:
return node;
default:
return isModifierLike(node) ? modifierVisitor(node) : visitor(node);
}
}
/**
* Visits a property name of a class member.
*/
function propertyNameVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(node as ComputedPropertyName);
default:
return visitor(node);
}
}
/**
* Visits the results of an auto-accessor field transformation in a second pass.
*/
function accessorFieldResultVisitor(node: Node) {
switch (node.kind) {
case SyntaxKind.PropertyDeclaration:
return transformFieldInitializer(node as PropertyDeclaration);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return classElementVisitor(node);
default:
Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration");
break;
}
}
/**
* If we visit a private name, this means it is an undeclared private name.
* Replace it with an empty identifier to indicate a problem with the code,
* unless we are in a statement position - otherwise this will not trigger
* a SyntaxError.
*/
function visitPrivateIdentifier(node: PrivateIdentifier) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return node;
}
if (isStatement(node.parent)) {
return node;
}
return setOriginalNode(factory.createIdentifier(""), node);
}
/**
* Visits `#id in expr`
*/
function transformPrivateIdentifierInInExpression(node: PrivateIdentifierInExpression) {
const info = accessPrivateIdentifier(node.left);
if (info) {
const receiver = visitNode(node.right, visitor, isExpression);
return setOriginalNode(
emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver),
node
);
}
// Private name has not been declared. Subsequent transformers will handle this error
return visitEachChild(node, visitor, context);
}
function visitPropertyAssignment(node: PropertyAssignment) {
// 13.2.5.5 RS: PropertyDefinitionEvaluation
// PropertyAssignment : PropertyName `:` AssignmentExpression
// ...
// 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and _isProtoSetter_ is *false*, then
// a. Let _popValue_ be ? NamedEvaluation of |AssignmentExpression| with argument _propKey_.
// ...
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
node = transformNamedEvaluation(context, node);
}
return visitEachChild(node, visitor, context);
}
function visitVariableStatement(node: VariableStatement) {
const savedPendingStatements = pendingStatements;
pendingStatements = [];
const visitedNode = visitEachChild(node, visitor, context);
const statement = some(pendingStatements) ?
[visitedNode, ...pendingStatements] :
visitedNode;
pendingStatements = savedPendingStatements;
return statement;
}
function visitVariableDeclaration(node: VariableDeclaration) {
// 14.3.1.2 RS: Evaluation
// LexicalBinding : BindingIdentifier Initializer
// ...
// 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
//
// 14.3.2.1 RS: Evaluation
// VariableDeclaration : BindingIdentifier Initializer
// ...
// 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
node = transformNamedEvaluation(context, node);
}
return visitEachChild(node, visitor, context);
}
function visitParameterDeclaration(node: ParameterDeclaration) {
// 8.6.3 RS: IteratorBindingInitialization
// SingleNameBinding : BindingIdentifier Initializer?
// ...
// 5. If |Initializer| is present and _v_ is *undefined*, then
// a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
//
// 14.3.3.3 RS: KeyedBindingInitialization
// SingleNameBinding : BindingIdentifier Initializer?
// ...
// 4. If |Initializer| is present and _v_ is *undefined*, then
// a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
node = transformNamedEvaluation(context, node);
}
return visitEachChild(node, visitor, context);
}
function visitBindingElement(node: BindingElement) {
// 8.6.3 RS: IteratorBindingInitialization
// SingleNameBinding : BindingIdentifier Initializer?
// ...
// 5. If |Initializer| is present and _v_ is *undefined*, then
// a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
//
// 14.3.3.3 RS: KeyedBindingInitialization
// SingleNameBinding : BindingIdentifier Initializer?
// ...
// 4. If |Initializer| is present and _v_ is *undefined*, then
// a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then
// i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_.
// ...
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
node = transformNamedEvaluation(context, node);
}
return visitEachChild(node, visitor, context);
}
function visitExportAssignment(node: ExportAssignment) {
// 16.2.3.7 RS: Evaluation
// ExportDeclaration : `export` `default` AssignmentExpression `;`
// 1. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true*, then
// a. Let _value_ be ? NamedEvaluation of |AssignmentExpression| with argument `"default"`.
// ...
// NOTE: Since emit for `export =` translates to `module.exports = ...`, the assigned nameof the class
// is `""`.
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ true, node.isExportEquals ? "" : "default");
}
return visitEachChild(node, visitor, context);
}
function injectPendingExpressions(expression: Expression) {
if (some(pendingExpressions)) {
if (isParenthesizedExpression(expression)) {
pendingExpressions.push(expression.expression);
expression = factory.updateParenthesizedExpression(expression, factory.inlineExpressions(pendingExpressions));
}
else {
pendingExpressions.push(expression);
expression = factory.inlineExpressions(pendingExpressions);
}
pendingExpressions = undefined;
}
return expression;
}
function visitComputedPropertyName(node: ComputedPropertyName) {
const expression = visitNode(node.expression, visitor, isExpression);
return factory.updateComputedPropertyName(node, injectPendingExpressions(expression));
}
function visitConstructorDeclaration(node: ConstructorDeclaration) {
if (currentClassContainer) {
return transformConstructor(node, currentClassContainer);
}
return fallbackVisitor(node);
}
function shouldTransformClassElementToWeakMap(node: PrivateIdentifierMethodDeclaration | PrivateIdentifierAccessorDeclaration | PrivateIdentifierPropertyDeclaration) {
if (shouldTransformPrivateElementsOrClassStaticBlocks) return true;
if (hasStaticModifier(node) && getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) return true;
return false;
}
function visitMethodOrAccessorDeclaration(node: MethodDeclaration | AccessorDeclaration) {
Debug.assert(!hasDecorators(node));
if (!isPrivateIdentifierClassElementDeclaration(node) || !shouldTransformClassElementToWeakMap(node)) {
return visitEachChild(node, classElementVisitor, context);
}
// leave invalid code untransformed
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (!info.isValid) {
return node;
}
const functionName = getHoistedFunctionName(node);
if (functionName) {
getPendingExpressions().push(
factory.createAssignment(
functionName,
factory.createFunctionExpression(
filter(node.modifiers, (m): m is Modifier => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)),
node.asteriskToken,
functionName,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
visitFunctionBody(node.body!, visitor, context)
)
)
);
}
// remove method declaration from class
return undefined;
}
function setCurrentClassElementAnd<T, U>(
classElement: ClassElement | undefined,
visitor: (arg: T) => U,
arg: T,
) {
if (classElement !== currentClassElement) {
const savedCurrentClassElement = currentClassElement;
currentClassElement = classElement;
const result = visitor(arg);
currentClassElement = savedCurrentClassElement;
return result;
}
return visitor(arg);
}
function getHoistedFunctionName(node: MethodDeclaration | AccessorDeclaration) {
Debug.assert(isPrivateIdentifier(node.name));
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (info.kind === PrivateIdentifierKind.Method) {
return info.methodName;
}
if (info.kind === PrivateIdentifierKind.Accessor) {
if (isGetAccessor(node)) {
return info.getterName;
}
if (isSetAccessor(node)) {
return info.setterName;
}
}
}
function getClassThis() {
const lex = getClassLexicalEnvironment();
const classThis = lex.classThis ?? lex.classConstructor ?? currentClassContainer?.name;
return Debug.checkDefined(classThis);
}
function transformAutoAccessor(node: AutoAccessorPropertyDeclaration): VisitResult<Node> {
// transforms:
// accessor x = 1;
// into:
// #x = 1;
// get x() { return this.#x; }
// set x(value) { this.#x = value; }
const commentRange = getCommentRange(node);
const sourceMapRange = getSourceMapRange(node);
// Since we're creating two declarations where there was previously one, cache
// the expression for any computed property names.
const name = node.name;
let getterName = name;
let setterName = name;
if (isComputedPropertyName(name) && !isSimpleInlineableExpression(name.expression)) {
const cacheAssignment = findComputedPropertyNameCacheAssignment(name);
if (cacheAssignment) {
getterName = factory.updateComputedPropertyName(name, visitNode(name.expression, visitor, isExpression));
setterName = factory.updateComputedPropertyName(name, cacheAssignment.left);
}
else {
const temp = factory.createTempVariable(hoistVariableDeclaration);
setSourceMapRange(temp, name.expression);
const expression = visitNode(name.expression, visitor, isExpression);
const assignment = factory.createAssignment(temp, expression);
setSourceMapRange(assignment, name.expression);
getterName = factory.updateComputedPropertyName(name, assignment);
setterName = factory.updateComputedPropertyName(name, temp);
}
}
const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier);
const backingField = createAccessorPropertyBackingField(factory, node, modifiers, node.initializer);
setOriginalNode(backingField, node);
setEmitFlags(backingField, EmitFlags.NoComments);
setSourceMapRange(backingField, sourceMapRange);
const receiver = isStatic(node) ? getClassThis() : factory.createThis();
const getter = createAccessorPropertyGetRedirector(factory, node, modifiers, getterName, receiver);
setOriginalNode(getter, node);
setCommentRange(getter, commentRange);
setSourceMapRange(getter, sourceMapRange);
// create a fresh copy of the modifiers so that we don't duplicate comments
const setterModifiers = factory.createModifiersFromModifierFlags(modifiersToFlags(modifiers));
const setter = createAccessorPropertySetRedirector(factory, node, setterModifiers, setterName, receiver);
setOriginalNode(setter, node);
setEmitFlags(setter, EmitFlags.NoComments);
setSourceMapRange(setter, sourceMapRange);
return visitArray([backingField, getter, setter], accessorFieldResultVisitor, isClassElement);
}
function transformPrivateFieldInitializer(node: PrivateIdentifierPropertyDeclaration) {
if (shouldTransformClassElementToWeakMap(node)) {
// If we are transforming private elements into WeakMap/WeakSet, we should elide the node.
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
// Leave invalid code untransformed
if (!info.isValid) {
return node;
}
// If we encounter a valid private static field and we're not transforming
// class static blocks, initialize it
if (info.isStatic && !shouldTransformPrivateElementsOrClassStaticBlocks) {
// TODO: fix
const statement = transformPropertyOrClassStaticBlock(node, factory.createThis());
if (statement) {
return factory.createClassStaticBlockDeclaration(factory.createBlock([statement], /*multiLine*/ true));
}
}
return undefined;
}
if (shouldTransformInitializersUsingSet && !isStatic(node) && lexicalEnvironment?.data && lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor) {
// If we are transforming initializers using Set semantics we will elide the initializer as it will
// be moved to the constructor to preserve evaluation order next to public instance fields. We don't
// need to do this transformation for private static fields since public static fields can be
// transformed into `static {}` blocks.
return factory.updatePropertyDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.name,
/*questionOrExclamationToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined
);
}
if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {