/
classFields.ts
1529 lines (1379 loc) · 72.3 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
/*@internal*/
namespace ts {
const enum ClassPropertySubstitutionFlags {
/**
* Enables substitutions for class expressions with static fields
* which have initializers that reference the class name.
*/
ClassAliases = 1 << 0,
}
export const enum PrivateIdentifierKind {
Field = "f",
Method = "m",
Accessor = "a"
}
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;
/**
* Defined for ease of access when in a union with PrivateIdentifierStaticFieldInfo.
*/
variableName: undefined;
}
interface PrivateIdentifierStaticFieldInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Field;
isStatic: true;
/**
* Contains the variable that will server as the storage for the field.
*/
variableName: Identifier;
}
type PrivateIdentifierInfo =
| PrivateIdentifierMethodInfo
| PrivateIdentifierInstanceFieldInfo
| PrivateIdentifierStaticFieldInfo
| PrivateIdentifierAccessorInfo;
interface PrivateIdentifierEnvironment {
/**
* Used for prefixing generated variable names.
*/
className: string;
/**
* Used for brand check on static members
*/
classConstructor?: Identifier;
/**
* Used for brand check on private methods.
*/
weakSetName?: Identifier;
/**
* A mapping of private names to information needed for transformation.
*/
identifiers: UnderscoreEscapedMap<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.
*/
export function transformClassFields(context: TransformationContext) {
const {
factory,
hoistVariableDeclaration,
endLexicalEnvironment,
resumeLexicalEnvironment,
addBlockScopedVariable
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
const shouldTransformPrivateElements = languageVersion < ScriptTarget.ESNext;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
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;
const privateIdentifierEnvironmentStack: (PrivateIdentifierEnvironment | undefined)[] = [];
let currentPrivateIdentifierEnvironment: PrivateIdentifierEnvironment | undefined;
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
const options = context.getCompilerOptions();
if (node.isDeclarationFile
|| useDefineForClassFields && options.target === ScriptTarget.ESNext) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function visitor(node: Node): VisitResult<Node> {
if (!(node.transformFlags & TransformFlags.ContainsClassFields)) return node;
switch (node.kind) {
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
return visitClassLike(node as ClassLikeDeclaration);
case SyntaxKind.PropertyDeclaration:
return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.PropertyAccessExpression:
return visitPropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.PrefixUnaryExpression:
return visitPrefixUnaryExpression(node as PrefixUnaryExpression);
case SyntaxKind.PostfixUnaryExpression:
return visitPostfixUnaryExpression(node as PostfixUnaryExpression, /*valueIsDiscarded*/ false);
case SyntaxKind.CallExpression:
return visitCallExpression(node as CallExpression);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression);
case SyntaxKind.PrivateIdentifier:
return visitPrivateIdentifier(node as PrivateIdentifier);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
}
return visitEachChild(node, visitor, context);
}
function visitorDestructuringTarget(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ArrayLiteralExpression:
return visitAssignmentPattern(node as AssignmentPattern);
default:
return visitor(node);
}
}
/**
* 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.
*/
function visitPrivateIdentifier(node: PrivateIdentifier) {
if (!shouldTransformPrivateElements) {
return node;
}
return setOriginalNode(factory.createIdentifier(""), node);
}
/**
* Visits the members of a class that has fields.
*
* @param node The node to visit.
*/
function classElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.Constructor:
// Constructors for classes using class fields are transformed in
// `visitClassDeclaration` or `visitClassExpression`.
return undefined;
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
return visitMethodOrAccessorDeclaration(node as MethodDeclaration | AccessorDeclaration);
case SyntaxKind.PropertyDeclaration:
return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(node as ComputedPropertyName);
case SyntaxKind.SemicolonClassElement:
return node;
default:
return visitor(node);
}
}
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 visitComputedPropertyName(name: ComputedPropertyName) {
let node = visitEachChild(name, visitor, context);
if (some(pendingExpressions)) {
const expressions = pendingExpressions;
expressions.push(node.expression);
pendingExpressions = [];
node = factory.updateComputedPropertyName(
node,
factory.inlineExpressions(expressions)
);
}
return node;
}
function visitMethodOrAccessorDeclaration(node: MethodDeclaration | AccessorDeclaration) {
Debug.assert(!some(node.decorators));
if (!shouldTransformPrivateElements || !isPrivateIdentifier(node.name)) {
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 => !isStaticModifier(m)),
node.asteriskToken,
functionName,
/* typeParameters */ undefined,
visitParameterList(node.parameters, classElementVisitor, context),
/* type */ undefined,
visitFunctionBody(node.body!, classElementVisitor, context)
)
)
);
}
// remove method declaration from class
return undefined;
}
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 visitPropertyDeclaration(node: PropertyDeclaration) {
Debug.assert(!some(node.decorators));
if (isPrivateIdentifier(node.name)) {
if (!shouldTransformPrivateElements) {
// Initializer is elided as the field is initialized in transformConstructor.
return factory.updatePropertyDeclaration(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.name,
/*questionOrExclamationToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined
);
}
// leave invalid code untransformed
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (!info.isValid) {
return node;
}
}
// Create a temporary variable to store a computed property name (if necessary).
// If it's not inlineable, then we emit an expression after the class which assigns
// the property name to the temporary variable.
const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields);
if (expr && !isSimpleInlineableExpression(expr)) {
getPendingExpressions().push(expr);
}
return undefined;
}
function createPrivateIdentifierAccess(info: PrivateIdentifierInfo, receiver: Expression): Expression {
return createPrivateIdentifierAccessHelper(info, visitNode(receiver, visitor, isExpression));
}
function createPrivateIdentifierAccessHelper(info: PrivateIdentifierInfo, receiver: Expression): Expression {
setCommentRange(receiver, moveRangePos(receiver, -1));
switch(info.kind) {
case PrivateIdentifierKind.Accessor:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.getterName
);
case PrivateIdentifierKind.Method:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.methodName
);
case PrivateIdentifierKind.Field:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.variableName
);
default:
Debug.assertNever(info, "Unknown private element type");
}
}
function visitPropertyAccessExpression(node: PropertyAccessExpression) {
if (shouldTransformPrivateElements && isPrivateIdentifier(node.name)) {
const privateIdentifierInfo = accessPrivateIdentifier(node.name);
if (privateIdentifierInfo) {
return setTextRange(
setOriginalNode(
createPrivateIdentifierAccess(privateIdentifierInfo, node.expression),
node
),
node
);
}
}
return visitEachChild(node, visitor, context);
}
function visitPrefixUnaryExpression(node: PrefixUnaryExpression) {
if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.operand)) {
const operator = node.operator === SyntaxKind.PlusPlusToken ?
SyntaxKind.PlusToken : node.operator === SyntaxKind.MinusMinusToken ?
SyntaxKind.MinusToken : undefined;
let info: PrivateIdentifierInfo | undefined;
if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
const receiver = visitNode(node.operand.expression, visitor, isExpression);
const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
const existingValue = factory.createPrefixUnaryExpression(SyntaxKind.PlusToken, createPrivateIdentifierAccess(info, readExpression));
return setOriginalNode(
createPrivateIdentifierAssignment(
info,
initializeExpression || readExpression,
factory.createBinaryExpression(existingValue, operator, factory.createNumericLiteral(1)),
SyntaxKind.EqualsToken
),
node
);
}
}
return visitEachChild(node, visitor, context);
}
function visitPostfixUnaryExpression(node: PostfixUnaryExpression, valueIsDiscarded: boolean) {
if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.operand)) {
const operator = node.operator === SyntaxKind.PlusPlusToken ?
SyntaxKind.PlusToken : node.operator === SyntaxKind.MinusMinusToken ?
SyntaxKind.MinusToken : undefined;
let info: PrivateIdentifierInfo | undefined;
if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
const receiver = visitNode(node.operand.expression, visitor, isExpression);
const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
const existingValue = factory.createPrefixUnaryExpression(SyntaxKind.PlusToken, createPrivateIdentifierAccess(info, readExpression));
// Create a temporary variable to store the value returned by the expression.
const returnValue = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
return setOriginalNode(
factory.inlineExpressions(compact<Expression>([
createPrivateIdentifierAssignment(
info,
initializeExpression || readExpression,
factory.createBinaryExpression(
returnValue ? factory.createAssignment(returnValue, existingValue) : existingValue,
operator,
factory.createNumericLiteral(1)
),
SyntaxKind.EqualsToken
),
returnValue
])),
node
);
}
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement) {
if (node.incrementor && isPostfixUnaryExpression(node.incrementor)) {
return factory.updateForStatement(
node,
visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true),
visitIterationBody(node.statement, visitor, context)
);
}
return visitEachChild(node, visitor, context);
}
function visitExpressionStatement(node: ExpressionStatement) {
if (isPostfixUnaryExpression(node.expression)) {
return factory.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
}
return visitEachChild(node, visitor, context);
}
function createCopiableReceiverExpr(receiver: Expression): { readExpression: Expression; initializeExpression: Expression | undefined } {
const clone = nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
if (isSimpleInlineableExpression(receiver)) {
return { readExpression: clone, initializeExpression: undefined };
}
const readExpression = factory.createTempVariable(hoistVariableDeclaration);
const initializeExpression = factory.createAssignment(readExpression, clone);
return { readExpression, initializeExpression };
}
function visitCallExpression(node: CallExpression) {
if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.expression)) {
// Transform call expressions of private names to properly bind the `this` parameter.
const { thisArg, target } = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion);
if (isCallChain(node)) {
return factory.updateCallChain(
node,
factory.createPropertyAccessChain(visitNode(target, visitor), node.questionDotToken, "call"),
/*questionDotToken*/ undefined,
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)]
);
}
return factory.updateCallExpression(
node,
factory.createPropertyAccessExpression(visitNode(target, visitor), "call"),
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)]
);
}
return visitEachChild(node, visitor, context);
}
function visitTaggedTemplateExpression(node: TaggedTemplateExpression) {
if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.tag)) {
// Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
const { thisArg, target } = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion);
return factory.updateTaggedTemplateExpression(
node,
factory.createCallExpression(
factory.createPropertyAccessExpression(visitNode(target, visitor), "bind"),
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression)]
),
/*typeArguments*/ undefined,
visitNode(node.template, visitor, isTemplateLiteral)
);
}
return visitEachChild(node, visitor, context);
}
function visitBinaryExpression(node: BinaryExpression) {
if (shouldTransformPrivateElements) {
if (isDestructuringAssignment(node)) {
const savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
node = factory.updateBinaryExpression(
node,
visitNode(node.left, visitorDestructuringTarget),
node.operatorToken,
visitNode(node.right, visitor)
);
const expr = some(pendingExpressions) ?
factory.inlineExpressions(compact([...pendingExpressions!, node])) :
node;
pendingExpressions = savedPendingExpressions;
return expr;
}
if (isAssignmentExpression(node) && isPrivateIdentifierPropertyAccessExpression(node.left)) {
const info = accessPrivateIdentifier(node.left.name);
if (info) {
return setTextRange(
setOriginalNode(
createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind),
node
),
node
);
}
}
}
return visitEachChild(node, visitor, context);
}
function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression {
receiver = visitNode(receiver, visitor, isExpression);
right = visitNode(right, visitor, isExpression);
if (isCompoundAssignment(operator)) {
const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
receiver = initializeExpression || readExpression;
right = factory.createBinaryExpression(
createPrivateIdentifierAccessHelper(info, readExpression),
getNonAssignmentOperatorForCompoundAssignment(operator),
right
);
}
setCommentRange(receiver, moveRangePos(receiver, -1));
switch(info.kind) {
case PrivateIdentifierKind.Accessor:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
info.setterName
);
case PrivateIdentifierKind.Method:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
/* f */ undefined
);
case PrivateIdentifierKind.Field:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
info.variableName
);
default:
Debug.assertNever(info, "Unknown private element type");
}
}
/**
* Set up the environment for a class.
*/
function visitClassLike(node: ClassLikeDeclaration) {
const savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
if (shouldTransformPrivateElements) {
startPrivateIdentifierEnvironment();
const name = getNameOfDeclaration(node);
if (name && isIdentifier(name)) {
getPrivateIdentifierEnvironment().className = idText(name);
}
const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
if (some(privateInstanceMethodsAndAccessors)) {
getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass(
"instances",
privateInstanceMethodsAndAccessors[0].name
);
}
}
const result = isClassDeclaration(node) ?
visitClassDeclaration(node) :
visitClassExpression(node);
if (shouldTransformPrivateElements) {
endPrivateIdentifierEnvironment();
}
pendingExpressions = savedPendingExpressions;
return result;
}
function doesClassElementNeedTransform(node: ClassElement) {
return isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && isPrivateIdentifier(node.name));
}
function getPrivateInstanceMethodsAndAccessors(node: ClassLikeDeclaration) {
return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName);
}
function visitClassDeclaration(node: ClassDeclaration) {
if (!forEach(node.members, doesClassElementNeedTransform)) {
return visitEachChild(node, visitor, context);
}
const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true);
let pendingPrivateStateAssignment: BinaryExpression | undefined;
if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) {
const temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true);
getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp);
pendingPrivateStateAssignment = factory.createAssignment(
temp,
factory.getInternalName(node)
);
}
const extendsClauseElement = getEffectiveBaseTypeNode(node);
const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword);
const statements: Statement[] = [
factory.updateClassDeclaration(
node,
/*decorators*/ undefined,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
transformClassMembers(node, isDerivedClass)
)
];
if (pendingPrivateStateAssignment) {
getPendingExpressions().unshift(pendingPrivateStateAssignment);
}
// Write any pending expressions from elided or moved computed property names
if (some(pendingExpressions)) {
statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
}
// Emit static property assignment. Because classDeclaration is lexically evaluated,
// it is safe to emit static property assignment after classDeclaration
// From ES6 specification:
// HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
// a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
if (some(staticProperties)) {
addPropertyStatements(statements, staticProperties, factory.getInternalName(node));
}
return statements;
}
function visitClassExpression(node: ClassExpression): Expression {
if (!forEach(node.members, doesClassElementNeedTransform)) {
return visitEachChild(node, visitor, context);
}
// If this class expression is a transformation of a decorated class declaration,
// then we want to output the pendingExpressions as statements, not as inlined
// expressions with the class statement.
//
// In this case, we use pendingStatements to produce the same output as the
// class declaration transformation. The VariableStatement visitor will insert
// these statements after the class expression variable statement.
const isDecoratedClassDeclaration = isClassDeclaration(getOriginalNode(node));
const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true);
const extendsClauseElement = getEffectiveBaseTypeNode(node);
const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword);
const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference;
let temp: Identifier | undefined;
function createClassTempVar() {
const classCheckFlags = resolver.getNodeCheckFlags(node);
const isClassWithConstructorReference = classCheckFlags & NodeCheckFlags.ClassWithConstructorReference;
const requiresBlockScopedVar = classCheckFlags & NodeCheckFlags.BlockScopedBindingInLoop;
return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference);
}
if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) {
temp = createClassTempVar();
getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp);
}
const classExpression = factory.updateClassExpression(
node,
visitNodes(node.decorators, visitor, isDecorator),
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
transformClassMembers(node, isDerivedClass)
);
const hasTransformableStatics = some(staticProperties, p => !!p.initializer || (shouldTransformPrivateElements && isPrivateIdentifier(p.name)));
if (hasTransformableStatics || some(pendingExpressions)) {
if (isDecoratedClassDeclaration) {
Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
// Write any pending expressions from elided or moved computed property names
if (pendingStatements && pendingExpressions && some(pendingExpressions)) {
pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
}
if (pendingStatements && some(staticProperties)) {
addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node));
}
if (temp) {
return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]);
}
return classExpression;
}
else {
const expressions: Expression[] = [];
temp ||= createClassTempVar();
if (isClassWithConstructorReference) {
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
const alias = factory.cloneNode(temp) as GeneratedIdentifier;
alias.autoGenerateFlags &= ~GeneratedIdentifierFlags.ReservedInNestedScopes;
classAliases[getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
// the body of a class with static initializers.
setEmitFlags(classExpression, EmitFlags.Indented | getEmitFlags(classExpression));
expressions.push(startOnNewLine(factory.createAssignment(temp, classExpression)));
// Add any pending expressions leftover from elided or relocated computed property names
addRange(expressions, map(pendingExpressions, startOnNewLine));
addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
expressions.push(startOnNewLine(temp));
return factory.inlineExpressions(expressions);
}
}
return classExpression;
}
function transformClassMembers(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
if (shouldTransformPrivateElements) {
// Declare private names.
for (const member of node.members) {
if (isPrivateIdentifierClassElementDeclaration(member)) {
addPrivateIdentifierToEnvironment(member);
}
}
if (some(getPrivateInstanceMethodsAndAccessors(node))) {
createBrandCheckWeakSetForPrivateMethods();
}
}
const members: ClassElement[] = [];
const constructor = transformConstructor(node, isDerivedClass);
if (constructor) {
members.push(constructor);
}
addRange(members, visitNodes(node.members, classElementVisitor, isClassElement));
return setTextRange(factory.createNodeArray(members), /*location*/ node.members);
}
function createBrandCheckWeakSetForPrivateMethods() {
const { weakSetName } = getPrivateIdentifierEnvironment();
Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
getPendingExpressions().push(
factory.createAssignment(
weakSetName,
factory.createNewExpression(
factory.createIdentifier("WeakSet"),
/*typeArguments*/ undefined,
[]
)
)
);
}
function isClassElementThatRequiresConstructorStatement(member: ClassElement) {
if (hasStaticModifier(member) || hasSyntacticModifier(getOriginalNode(member), ModifierFlags.Abstract)) {
return false;
}
if (useDefineForClassFields) {
// If we are using define semantics and targeting ESNext or higher,
// then we don't need to transform any class properties.
return languageVersion < ScriptTarget.ESNext;
}
return isInitializedProperty(member) || shouldTransformPrivateElements && isPrivateIdentifierClassElementDeclaration(member);
}
function transformConstructor(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
const constructor = visitNode(getFirstConstructorWithBody(node), visitor, isConstructorDeclaration);
const elements = node.members.filter(isClassElementThatRequiresConstructorStatement);
if (!some(elements)) {
return constructor;
}
const parameters = visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
const body = transformConstructorBody(node, constructor, isDerivedClass);
if (!body) {
return undefined;
}
return startOnNewLine(
setOriginalNode(
setTextRange(
factory.createConstructorDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
parameters ?? [],
body
),
constructor || node
),
constructor
)
);
}
function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) {
let properties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
if (!useDefineForClassFields) {
properties = filter(properties, property => !!property.initializer || isPrivateIdentifier(property.name));
}
const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors);
// Only generate synthetic constructor when there are property initializers to move.
if (!constructor && !needsConstructorBody) {
return visitFunctionBody(/*node*/ undefined, visitor, context);
}
resumeLexicalEnvironment();
let indexOfFirstStatement = 0;
let statements: Statement[] = [];
if (!constructor && isDerivedClass) {
// Add a synthetic `super` call:
//
// super(...arguments);
//
statements.push(
factory.createExpressionStatement(
factory.createCallExpression(
factory.createSuper(),
/*typeArguments*/ undefined,
[factory.createSpreadElement(factory.createIdentifier("arguments"))]
)
)
);
}
if (constructor) {
indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
}
// Add the property initializers. Transforms this:
//
// public x = 1;
//
// Into this:
//
// constructor() {
// this.x = 1;
// }
//
if (constructor?.body) {
let afterParameterProperties = findIndex(constructor.body.statements, s => !isParameterPropertyDeclaration(getOriginalNode(s), constructor), indexOfFirstStatement);
if (afterParameterProperties === -1) {
afterParameterProperties = constructor.body.statements.length;
}
if (afterParameterProperties > indexOfFirstStatement) {
if (!useDefineForClassFields) {
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
}
indexOfFirstStatement = afterParameterProperties;
}
}
const receiver = factory.createThis();
// private methods can be called in property initializers, they should execute first.
addMethodStatements(statements, privateMethodsAndAccessors, receiver);
addPropertyStatements(statements, properties, receiver);
// Add existing statements, skipping the initial super call.
if (constructor) {
addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatement));
}
statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
return setTextRange(
factory.createBlock(
setTextRange(
factory.createNodeArray(statements),
/*location*/ constructor ? constructor.body!.statements : node.members
),
/*multiLine*/ true
),
/*location*/ constructor ? constructor.body : undefined
);
}
/**
* Generates assignment statements for property initializers.
*
* @param properties An array of property declarations to transform.
* @param receiver The receiver on which each property should be assigned.
*/
function addPropertyStatements(statements: Statement[], properties: readonly PropertyDeclaration[], receiver: LeftHandSideExpression) {
for (const property of properties) {
const expression = transformProperty(property, receiver);
if (!expression) {
continue;
}
const statement = factory.createExpressionStatement(expression);
setSourceMapRange(statement, moveRangePastModifiers(property));
setCommentRange(statement, property);
setOriginalNode(statement, property);
statements.push(statement);
}
}
/**
* Generates assignment expressions for property initializers.
*
* @param properties An array of property declarations to transform.
* @param receiver The receiver on which each property should be assigned.
*/
function generateInitializedPropertyExpressions(properties: readonly PropertyDeclaration[], receiver: LeftHandSideExpression) {
const expressions: Expression[] = [];
for (const property of properties) {
const expression = transformProperty(property, receiver);
if (!expression) {
continue;
}
startOnNewLine(expression);
setSourceMapRange(expression, moveRangePastModifiers(property));
setCommentRange(expression, property);
setOriginalNode(expression, property);
expressions.push(expression);
}
return expressions;
}
/**