/
es2017.ts
899 lines (806 loc) · 41.6 KB
/
es2017.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
/*@internal*/
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
const enum ES2017SubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
const enum ContextFlags {
NonTopLevel = 1 << 0,
HasLexicalThis = 1 << 1
}
export function transformES2017(context: TransformationContext) {
const {
factory,
getEmitHelperFactory: emitHelpers,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
let enabledSubstitutions: ES2017SubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
let enclosingSuperContainerFlags: NodeCheckFlags = 0;
let enclosingFunctionParameterNames: Set<__String>;
/**
* Keeps track of property names accessed on super (`super.x`) within async functions.
*/
let capturedSuperProperties: Set<__String>;
/** Whether the async function contains an element access on super (`super[x]`). */
let hasSuperElementAccess: boolean;
/** A set of node IDs for generated super accessors (variable statements). */
const substitutedSuperAccessors: boolean[] = [];
let contextFlags: ContextFlags = 0;
// Save the previous transformation hooks.
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
setContextFlag(ContextFlags.NonTopLevel, false);
setContextFlag(ContextFlags.HasLexicalThis, !isEffectiveStrictModeSourceFile(node, compilerOptions));
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function setContextFlag(flag: ContextFlags, val: boolean) {
contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
}
function inContext(flags: ContextFlags) {
return (contextFlags & flags) !== 0;
}
function inTopLevelContext() {
return !inContext(ContextFlags.NonTopLevel);
}
function inHasLexicalThisContext() {
return inContext(ContextFlags.HasLexicalThis);
}
function doWithContext<T, U>(flags: ContextFlags, cb: (value: T) => U, value: T) {
const contextFlagsToSet = flags & ~contextFlags;
if (contextFlagsToSet) {
setContextFlag(contextFlagsToSet, /*val*/ true);
const result = cb(value);
setContextFlag(contextFlagsToSet, /*val*/ false);
return result;
}
return cb(value);
}
function visitDefault(node: Node): VisitResult<Node> {
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): VisitResult<Node> {
if ((node.transformFlags & TransformFlags.ContainsES2017) === 0) {
return node;
}
switch (node.kind) {
case SyntaxKind.AsyncKeyword:
// ES2017 async modifier should be elided for targets < ES2017
return undefined;
case SyntaxKind.AwaitExpression:
return visitAwaitExpression(node as AwaitExpression);
case SyntaxKind.MethodDeclaration:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, node as MethodDeclaration);
case SyntaxKind.FunctionDeclaration:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, node as FunctionExpression);
case SyntaxKind.ArrowFunction:
return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, node as ArrowFunction);
case SyntaxKind.PropertyAccessExpression:
if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) {
capturedSuperProperties.add(node.name.escapedText);
}
return visitEachChild(node, visitor, context);
case SyntaxKind.ElementAccessExpression:
if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) {
hasSuperElementAccess = true;
}
return visitEachChild(node, visitor, context);
case SyntaxKind.GetAccessor:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitGetAccessorDeclaration, node as GetAccessorDeclaration);
case SyntaxKind.SetAccessor:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitSetAccessorDeclaration, node as SetAccessorDeclaration);
case SyntaxKind.Constructor:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitConstructorDeclaration, node as ConstructorDeclaration);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitDefault, node);
default:
return visitEachChild(node, visitor, context);
}
}
function asyncBodyVisitor(node: Node): VisitResult<Node> {
if (isNodeWithPossibleHoistedDeclaration(node)) {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatementInAsyncBody(node);
case SyntaxKind.ForStatement:
return visitForStatementInAsyncBody(node);
case SyntaxKind.ForInStatement:
return visitForInStatementInAsyncBody(node);
case SyntaxKind.ForOfStatement:
return visitForOfStatementInAsyncBody(node);
case SyntaxKind.CatchClause:
return visitCatchClauseInAsyncBody(node);
case SyntaxKind.Block:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseBlock:
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
case SyntaxKind.TryStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.LabeledStatement:
return visitEachChild(node, asyncBodyVisitor, context);
default:
return Debug.assertNever(node, "Unhandled node.");
}
}
return visitor(node);
}
function visitCatchClauseInAsyncBody(node: CatchClause) {
const catchClauseNames = new Set<__String>();
recordDeclarationName(node.variableDeclaration!, catchClauseNames); // TODO: GH#18217
// names declared in a catch variable are block scoped
let catchClauseUnshadowedNames: Set<__String> | undefined;
catchClauseNames.forEach((_, escapedName) => {
if (enclosingFunctionParameterNames.has(escapedName)) {
if (!catchClauseUnshadowedNames) {
catchClauseUnshadowedNames = new Set(enclosingFunctionParameterNames);
}
catchClauseUnshadowedNames.delete(escapedName);
}
});
if (catchClauseUnshadowedNames) {
const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
enclosingFunctionParameterNames = catchClauseUnshadowedNames;
const result = visitEachChild(node, asyncBodyVisitor, context);
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
return result;
}
else {
return visitEachChild(node, asyncBodyVisitor, context);
}
}
function visitVariableStatementInAsyncBody(node: VariableStatement) {
if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
const expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
return expression ? factory.createExpressionStatement(expression) : undefined;
}
return visitEachChild(node, visitor, context);
}
function visitForInStatementInAsyncBody(node: ForInStatement) {
return factory.updateForInStatement(
node,
isVariableDeclarationListWithCollidingName(node.initializer)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)!
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.expression, visitor, isExpression),
visitIterationBody(node.statement, asyncBodyVisitor, context)
);
}
function visitForOfStatementInAsyncBody(node: ForOfStatement) {
return factory.updateForOfStatement(
node,
visitNode(node.awaitModifier, visitor, isToken),
isVariableDeclarationListWithCollidingName(node.initializer)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)!
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.expression, visitor, isExpression),
visitIterationBody(node.statement, asyncBodyVisitor, context)
);
}
function visitForStatementInAsyncBody(node: ForStatement) {
const initializer = node.initializer!; // TODO: GH#18217
return factory.updateForStatement(
node,
isVariableDeclarationListWithCollidingName(initializer)
? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
visitIterationBody(node.statement, asyncBodyVisitor, context)
);
}
/**
* Visits an AwaitExpression node.
*
* This function will be called any time a ES2017 await expression is encountered.
*
* @param node The node to visit.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
// do not downlevel a top-level await as it is module syntax...
if (inTopLevelContext()) {
return visitEachChild(node, visitor, context);
}
return setOriginalNode(
setTextRange(
factory.createYieldExpression(
/*asteriskToken*/ undefined,
visitNode(node.expression, visitor, isExpression)
),
node
),
node
);
}
function visitConstructorDeclaration(node: ConstructorDeclaration) {
return factory.updateConstructorDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
visitParameterList(node.parameters, visitor, context),
transformMethodBody(node)
);
}
/**
* Visits a MethodDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked as async
*
* @param node The node to visit.
*/
function visitMethodDeclaration(node: MethodDeclaration) {
return factory.updateMethodDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.asteriskToken,
node.name,
/*questionToken*/ undefined,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
getFunctionFlags(node) & FunctionFlags.Async
? transformAsyncFunctionBody(node)
: transformMethodBody(node)
);
}
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
return factory.updateGetAccessorDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.name,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformMethodBody(node)
);
}
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
return factory.updateSetAccessorDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.name,
visitParameterList(node.parameters, visitor, context),
transformMethodBody(node)
);
}
/**
* Visits a FunctionDeclaration node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
return factory.updateFunctionDeclaration(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
getFunctionFlags(node) & FunctionFlags.Async
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
/**
* Visits a FunctionExpression node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The node to visit.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
return factory.updateFunctionExpression(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
getFunctionFlags(node) & FunctionFlags.Async
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
/**
* Visits an ArrowFunction.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The node to visit.
*/
function visitArrowFunction(node: ArrowFunction) {
return factory.updateArrowFunction(
node,
visitNodes(node.modifiers, visitor, isModifierLike),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.equalsGreaterThanToken,
getFunctionFlags(node) & FunctionFlags.Async
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context),
);
}
function recordDeclarationName({ name }: ParameterDeclaration | VariableDeclaration | BindingElement, names: Set<__String>) {
if (isIdentifier(name)) {
names.add(name.escapedText);
}
else {
for (const element of name.elements) {
if (!isOmittedExpression(element)) {
recordDeclarationName(element, names);
}
}
}
}
function isVariableDeclarationListWithCollidingName(node: ForInitializer): node is VariableDeclarationList {
return !!node
&& isVariableDeclarationList(node)
&& !(node.flags & NodeFlags.BlockScoped)
&& node.declarations.some(collidesWithParameterName);
}
function visitVariableDeclarationListWithCollidingNames(node: VariableDeclarationList, hasReceiver: boolean) {
hoistVariableDeclarationList(node);
const variables = getInitializedVariables(node);
if (variables.length === 0) {
if (hasReceiver) {
return visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, isExpression);
}
return undefined;
}
return factory.inlineExpressions(map(variables, transformInitializedVariable));
}
function hoistVariableDeclarationList(node: VariableDeclarationList) {
forEach(node.declarations, hoistVariable);
}
function hoistVariable({ name }: VariableDeclaration | BindingElement) {
if (isIdentifier(name)) {
hoistVariableDeclaration(name);
}
else {
for (const element of name.elements) {
if (!isOmittedExpression(element)) {
hoistVariable(element);
}
}
}
}
function transformInitializedVariable(node: VariableDeclaration) {
const converted = setSourceMapRange(
factory.createAssignment(
factory.converters.convertToAssignmentElementTarget(node.name),
node.initializer!
),
node
);
return visitNode(converted, visitor, isExpression);
}
function collidesWithParameterName({ name }: VariableDeclaration | BindingElement): boolean {
if (isIdentifier(name)) {
return enclosingFunctionParameterNames.has(name.escapedText);
}
else {
for (const element of name.elements) {
if (!isOmittedExpression(element) && collidesWithParameterName(element)) {
return true;
}
}
}
return false;
}
function transformMethodBody(node: MethodDeclaration | AccessorDeclaration | ConstructorDeclaration): FunctionBody | undefined {
Debug.assertIsDefined(node.body);
const savedCapturedSuperProperties = capturedSuperProperties;
const savedHasSuperElementAccess = hasSuperElementAccess;
capturedSuperProperties = new Set();
hasSuperElementAccess = false;
let updated = visitFunctionBody(node.body, visitor, context);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration);
const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 &&
resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) &&
(getFunctionFlags(originalMethod) & FunctionFlags.AsyncGenerator) !== FunctionFlags.AsyncGenerator;
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
if (capturedSuperProperties.size) {
const variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
substitutedSuperAccessors[getNodeId(variableStatement)] = true;
const statements = updated.statements.slice();
insertStatementsAfterStandardPrologue(statements, [variableStatement]);
updated = factory.updateBlock(updated, statements);
}
if (hasSuperElementAccess) {
// Emit helpers for super element access expressions (`super[x]`).
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) {
addEmitHelper(updated, advancedAsyncSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) {
addEmitHelper(updated, asyncSuperHelper);
}
}
}
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
return updated;
}
function transformAsyncFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody;
function transformAsyncFunctionBody(node: ArrowFunction): ConciseBody;
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
resumeLexicalEnvironment();
const original = getOriginalNode(node, isFunctionLike);
const nodeType = original.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
enclosingFunctionParameterNames = new Set();
for (const parameter of node.parameters) {
recordDeclarationName(parameter, enclosingFunctionParameterNames);
}
const savedCapturedSuperProperties = capturedSuperProperties;
const savedHasSuperElementAccess = hasSuperElementAccess;
if (!isArrowFunction) {
capturedSuperProperties = new Set();
hasSuperElementAccess = false;
}
let result: ConciseBody;
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = factory.copyPrologue((node.body as Block).statements, statements, /*ensureUseStrict*/ false, visitor);
statements.push(
factory.createReturnStatement(
emitHelpers().createAwaiterHelper(
inHasLexicalThisContext(),
hasLexicalArguments,
promiseConstructor,
transformAsyncFunctionBodyWorker(node.body as Block, statementOffset)
)
)
);
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.MethodWithSuperPropertyAccessInAsync);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
if (capturedSuperProperties.size) {
const variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
substitutedSuperAccessors[getNodeId(variableStatement)] = true;
insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
}
const block = factory.createBlock(statements, /*multiLine*/ true);
setTextRange(block, node.body);
if (emitSuperHelpers && hasSuperElementAccess) {
// Emit helpers for super element access expressions (`super[x]`).
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) {
addEmitHelper(block, advancedAsyncSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) {
addEmitHelper(block, asyncSuperHelper);
}
}
result = block;
}
else {
const expression = emitHelpers().createAwaiterHelper(
inHasLexicalThisContext(),
hasLexicalArguments,
promiseConstructor,
transformAsyncFunctionBodyWorker(node.body)
);
const declarations = endLexicalEnvironment();
if (some(declarations)) {
const block = factory.converters.convertToFunctionBlock(expression);
result = factory.updateBlock(block, setTextRange(factory.createNodeArray(concatenate(declarations, block.statements)), block.statements));
}
else {
result = expression;
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
}
return result;
}
function transformAsyncFunctionBodyWorker(body: ConciseBody, start?: number) {
if (isBlock(body)) {
return factory.updateBlock(body, visitNodes(body.statements, asyncBodyVisitor, isStatement, start));
}
else {
return factory.converters.convertToFunctionBlock(visitNode(body, asyncBodyVisitor, isConciseBody));
}
}
function getPromiseConstructor(type: TypeNode | undefined) {
const typeName = type && getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper;
// We need to enable substitutions for call, property access, and element access
// if we need to rewrite super calls.
context.enableSubstitution(SyntaxKind.CallExpression);
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// We need to be notified when entering and exiting declarations that bind super.
context.enableEmitNotification(SyntaxKind.ClassDeclaration);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.Constructor);
// We need to be notified when entering the generated accessor arrow functions.
context.enableEmitNotification(SyntaxKind.VariableStatement);
}
}
/**
* Hook for node emit.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
const superContainerFlags = resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync);
if (superContainerFlags !== enclosingSuperContainerFlags) {
const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
enclosingSuperContainerFlags = superContainerFlags;
previousOnEmitNode(hint, node, emitCallback);
enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
return;
}
}
// Disable substitution in the generated super accessor itself.
else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) {
const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
enclosingSuperContainerFlags = 0;
previousOnEmitNode(hint, node, emitCallback);
enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
return;
}
previousOnEmitNode(hint, node, emitCallback);
}
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression && enclosingSuperContainerFlags) {
return substituteExpression(node as Expression);
}
return node;
}
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.CallExpression:
return substituteCallExpression(node as CallExpression);
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (node.expression.kind === SyntaxKind.SuperKeyword) {
return setTextRange(
factory.createPropertyAccessExpression(
factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel),
node.name),
node
);
}
return node;
}
function substituteElementAccessExpression(node: ElementAccessExpression) {
if (node.expression.kind === SyntaxKind.SuperKeyword) {
return createSuperElementAccessInAsyncMethod(
node.argumentExpression,
node
);
}
return node;
}
function substituteCallExpression(node: CallExpression): Expression {
const expression = node.expression;
if (isSuperProperty(expression)) {
const argumentExpression = isPropertyAccessExpression(expression)
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return factory.createCallExpression(
factory.createPropertyAccessExpression(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
factory.createThis(),
...node.arguments
]
);
}
return node;
}
function isSuperContainer(node: Node): node is SuperContainer {
const kind = node.kind;
return kind === SyntaxKind.ClassDeclaration
|| kind === SyntaxKind.Constructor
|| kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor;
}
function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression {
if (enclosingSuperContainerFlags & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) {
return setTextRange(
factory.createPropertyAccessExpression(
factory.createCallExpression(
factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value"
),
location
);
}
else {
return setTextRange(
factory.createCallExpression(
factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel),
/*typeArguments*/ undefined,
[argumentExpression]
),
location
);
}
}
}
/** Creates a variable named `_super` with accessor properties for the given property names. */
export function createSuperAccessVariableStatement(factory: NodeFactory, resolver: EmitResolver, node: FunctionLikeDeclaration, names: Set<__String>) {
// Create a variable declaration with a getter/setter (if binding) definition for each name:
// const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
const hasBinding = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) !== 0;
const accessors: PropertyAssignment[] = [];
names.forEach((_, key) => {
const name = unescapeLeadingUnderscores(key);
const getterAndSetter: PropertyAssignment[] = [];
getterAndSetter.push(factory.createPropertyAssignment(
"get",
factory.createArrowFunction(
/* modifiers */ undefined,
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
/* equalsGreaterThanToken */ undefined,
setEmitFlags(
factory.createPropertyAccessExpression(
setEmitFlags(
factory.createSuper(),
EmitFlags.NoSubstitution
),
name
),
EmitFlags.NoSubstitution
)
)
));
if (hasBinding) {
getterAndSetter.push(
factory.createPropertyAssignment(
"set",
factory.createArrowFunction(
/* modifiers */ undefined,
/* typeParameters */ undefined,
/* parameters */ [
factory.createParameterDeclaration(
/* modifiers */ undefined,
/* dotDotDotToken */ undefined,
"v",
/* questionToken */ undefined,
/* type */ undefined,
/* initializer */ undefined
)
],
/* type */ undefined,
/* equalsGreaterThanToken */ undefined,
factory.createAssignment(
setEmitFlags(
factory.createPropertyAccessExpression(
setEmitFlags(
factory.createSuper(),
EmitFlags.NoSubstitution
),
name
),
EmitFlags.NoSubstitution
),
factory.createIdentifier("v")
)
)
)
);
}
accessors.push(
factory.createPropertyAssignment(
name,
factory.createObjectLiteralExpression(getterAndSetter),
)
);
});
return factory.createVariableStatement(
/* modifiers */ undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel),
/*exclamationToken*/ undefined,
/* type */ undefined,
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier("Object"),
"create"
),
/* typeArguments */ undefined,
[
factory.createNull(),
factory.createObjectLiteralExpression(accessors, /* multiline */ true)
]
)
)
],
NodeFlags.Const));
}
}