/
es2018.ts
1070 lines (985 loc) · 50.8 KB
/
es2018.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 ESNextSubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
export function transformES2018(context: TransformationContext) {
const {
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
let enabledSubstitutions: ESNextSubstitutionFlags;
let enclosingFunctionFlags: FunctionFlags;
let enclosingSuperContainerFlags: NodeCheckFlags = 0;
/** Keeps track of property names accessed on super (`super.x`) within async functions. */
let capturedSuperProperties: UnderscoreEscapedMap<true>;
/** Whether the async function contains an element access on super (`super[x]`). */
let hasSuperElementAccess: boolean;
/** A set of node IDs for generated super accessors. */
const substitutedSuperAccessors: boolean[] = [];
return chainBundle(transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function visitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*noDestructuringValue*/ false);
}
function visitorNoDestructuringValue(node: Node): VisitResult<Node> {
return visitorWorker(node, /*noDestructuringValue*/ true);
}
function visitorNoAsyncModifier(node: Node): VisitResult<Node> {
if (node.kind === SyntaxKind.AsyncKeyword) {
return undefined;
}
return node;
}
function visitorWorker(node: Node, noDestructuringValue: boolean): VisitResult<Node> {
if ((node.transformFlags & TransformFlags.ContainsES2018) === 0) {
return node;
}
switch (node.kind) {
case SyntaxKind.AwaitExpression:
return visitAwaitExpression(node as AwaitExpression);
case SyntaxKind.YieldExpression:
return visitYieldExpression(node as YieldExpression);
case SyntaxKind.ReturnStatement:
return visitReturnStatement(node as ReturnStatement);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(node as LabeledStatement);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, noDestructuringValue);
case SyntaxKind.CatchClause:
return visitCatchClause(node as CatchClause);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.VoidExpression:
return visitVoidExpression(node as VoidExpression);
case SyntaxKind.Constructor:
return visitConstructorDeclaration(node as ConstructorDeclaration);
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.GetAccessor:
return visitGetAccessorDeclaration(node as GetAccessorDeclaration);
case SyntaxKind.SetAccessor:
return visitSetAccessorDeclaration(node as SetAccessorDeclaration);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.ArrowFunction:
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.Parameter:
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue);
case SyntaxKind.PropertyAccessExpression:
if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) {
capturedSuperProperties.set(node.name.escapedText, true);
}
return visitEachChild(node, visitor, context);
case SyntaxKind.ElementAccessExpression:
if (capturedSuperProperties && (<ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword) {
hasSuperElementAccess = true;
}
return visitEachChild(node, visitor, context);
default:
return visitEachChild(node, visitor, context);
}
}
function visitAwaitExpression(node: AwaitExpression): Expression {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
return setOriginalNode(
setTextRange(
createYield(createAwaitHelper(context, visitNode(node.expression, visitor, isExpression))),
/*location*/ node
),
node
);
}
return visitEachChild(node, visitor, context);
}
function visitYieldExpression(node: YieldExpression) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
if (node.asteriskToken) {
const expression = visitNode(node.expression, visitor, isExpression);
return setOriginalNode(
setTextRange(
createYield(
createAwaitHelper(context,
updateYield(
node,
node.asteriskToken,
createAsyncDelegatorHelper(
context,
createAsyncValuesHelper(context, expression, expression),
expression
)
)
)
),
node
),
node
);
}
return setOriginalNode(
setTextRange(
createYield(
createDownlevelAwait(
node.expression
? visitNode(node.expression, visitor, isExpression)
: createVoidZero()
)
),
node
),
node
);
}
return visitEachChild(node, visitor, context);
}
function visitReturnStatement(node: ReturnStatement) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
return updateReturn(node, createDownlevelAwait(
node.expression ? visitNode(node.expression, visitor, isExpression) : createVoidZero()
));
}
return visitEachChild(node, visitor, context);
}
function visitLabeledStatement(node: LabeledStatement) {
if (enclosingFunctionFlags & FunctionFlags.Async) {
const statement = unwrapInnermostStatementOfLabel(node);
if (statement.kind === SyntaxKind.ForOfStatement && (<ForOfStatement>statement).awaitModifier) {
return visitForOfStatement(<ForOfStatement>statement, node);
}
return restoreEnclosingLabel(visitEachChild(statement, visitor, context), node);
}
return visitEachChild(node, visitor, context);
}
function chunkObjectLiteralElements(elements: ReadonlyArray<ObjectLiteralElementLike>): Expression[] {
let chunkObject: ObjectLiteralElementLike[] | undefined;
const objects: Expression[] = [];
for (const e of elements) {
if (e.kind === SyntaxKind.SpreadAssignment) {
if (chunkObject) {
objects.push(createObjectLiteral(chunkObject));
chunkObject = undefined;
}
const target = e.expression;
objects.push(visitNode(target, visitor, isExpression));
}
else {
chunkObject = append(chunkObject, e.kind === SyntaxKind.PropertyAssignment
? createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression))
: visitNode(e, visitor, isObjectLiteralElementLike));
}
}
if (chunkObject) {
objects.push(createObjectLiteral(chunkObject));
}
return objects;
}
function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression {
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
// If the first element is a spread element, then the first argument to __assign is {}:
// { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
const objects = chunkObjectLiteralElements(node.properties);
if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) {
objects.unshift(createObjectLiteral());
}
return createAssignHelper(context, objects);
}
return visitEachChild(node, visitor, context);
}
function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement {
return visitEachChild(node, visitorNoDestructuringValue, context);
}
function visitParenthesizedExpression(node: ParenthesizedExpression, noDestructuringValue: boolean): ParenthesizedExpression {
return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression {
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
return flattenDestructuringAssignment(
node,
visitor,
context,
FlattenLevel.ObjectRest,
!noDestructuringValue
);
}
else if (node.operatorToken.kind === SyntaxKind.CommaToken) {
return updateBinary(
node,
visitNode(node.left, visitorNoDestructuringValue, isExpression),
visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
function visitCatchClause(node: CatchClause) {
if (node.variableDeclaration &&
isBindingPattern(node.variableDeclaration.name) &&
node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
const name = getGeneratedNameForNode(node.variableDeclaration.name);
const updatedDecl = updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, FlattenLevel.ObjectRest);
let block = visitNode(node.block, visitor, isBlock);
if (some(visitedBindings)) {
block = updateBlock(block, [
createVariableStatement(/*modifiers*/ undefined, visitedBindings),
...block.statements,
]);
}
return updateCatchClause(
node,
updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined),
block);
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a VariableDeclaration node with a binding pattern.
*
* @param node A VariableDeclaration node.
*/
function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
return flattenDestructuringBinding(
node,
visitor,
context,
FlattenLevel.ObjectRest
);
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement): VisitResult<Statement> {
return updateFor(
node,
visitNode(node.initializer, visitorNoDestructuringValue, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
visitNode(node.statement, visitor, isStatement)
);
}
function visitVoidExpression(node: VoidExpression) {
return visitEachChild(node, visitorNoDestructuringValue, context);
}
/**
* Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
*
* @param node A ForOfStatement.
*/
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult<Statement> {
if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
return transformForAwaitOfStatement(node, outermostLabeledStatement);
}
else {
return restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement);
}
}
function transformForOfStatementWithObjectRest(node: ForOfStatement) {
const initializerWithoutParens = skipParentheses(node.initializer) as ForInitializer;
if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) {
let bodyLocation: TextRange | undefined;
let statementsLocation: TextRange | undefined;
const temp = createTempVariable(/*recordTempVariable*/ undefined);
const statements: Statement[] = [createForOfBindingStatement(initializerWithoutParens, temp)];
if (isBlock(node.statement)) {
addRange(statements, node.statement.statements);
bodyLocation = node.statement;
statementsLocation = node.statement.statements;
}
else if (node.statement) {
append(statements, node.statement);
bodyLocation = node.statement;
statementsLocation = node.statement;
}
return updateForOf(
node,
node.awaitModifier,
setTextRange(
createVariableDeclarationList(
[
setTextRange(createVariableDeclaration(temp), node.initializer)
],
NodeFlags.Let
),
node.initializer
),
node.expression,
setTextRange(
createBlock(
setTextRange(createNodeArray(statements), statementsLocation),
/*multiLine*/ true
),
bodyLocation
)
);
}
return node;
}
function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression) {
const binding = createForOfBindingStatement(node.initializer, boundValue);
let bodyLocation: TextRange | undefined;
let statementsLocation: TextRange | undefined;
const statements: Statement[] = [visitNode(binding, visitor, isStatement)];
const statement = visitNode(node.statement, visitor, isStatement);
if (isBlock(statement)) {
addRange(statements, statement.statements);
bodyLocation = statement;
statementsLocation = statement.statements;
}
else {
statements.push(statement);
}
return setEmitFlags(
setTextRange(
createBlock(
setTextRange(createNodeArray(statements), statementsLocation),
/*multiLine*/ true
),
bodyLocation
),
EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps
);
}
function createDownlevelAwait(expression: Expression) {
return enclosingFunctionFlags & FunctionFlags.Generator
? createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
: createAwait(expression);
}
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined) {
const expression = visitNode(node.expression, visitor, isExpression);
const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined);
const result = isIdentifier(expression) ? getGeneratedNameForNode(iterator) : createTempVariable(/*recordTempVariable*/ undefined);
const errorRecord = createUniqueName("e");
const catchVariable = getGeneratedNameForNode(errorRecord);
const returnMethod = createTempVariable(/*recordTempVariable*/ undefined);
const callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
const callNext = createCall(createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
const getDone = createPropertyAccess(result, "done");
const getValue = createPropertyAccess(result, "value");
const callReturn = createFunctionCall(returnMethod, iterator, []);
hoistVariableDeclaration(errorRecord);
hoistVariableDeclaration(returnMethod);
const forStatement = setEmitFlags(
setTextRange(
createFor(
/*initializer*/ setEmitFlags(
setTextRange(
createVariableDeclarationList([
setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression),
createVariableDeclaration(result)
]),
node.expression
),
EmitFlags.NoHoisting
),
/*condition*/ createComma(
createAssignment(result, createDownlevelAwait(callNext)),
createLogicalNot(getDone)
),
/*incrementor*/ undefined,
/*statement*/ convertForOfStatementHead(node, getValue)
),
/*location*/ node
),
EmitFlags.NoTokenTrailingSourceMaps
);
return createTry(
createBlock([
restoreEnclosingLabel(
forStatement,
outermostLabeledStatement
)
]),
createCatchClause(
createVariableDeclaration(catchVariable),
setEmitFlags(
createBlock([
createExpressionStatement(
createAssignment(
errorRecord,
createObjectLiteral([
createPropertyAssignment("error", catchVariable)
])
)
)
]),
EmitFlags.SingleLine
)
),
createBlock([
createTry(
/*tryBlock*/ createBlock([
setEmitFlags(
createIf(
createLogicalAnd(
createLogicalAnd(
result,
createLogicalNot(getDone)
),
createAssignment(
returnMethod,
createPropertyAccess(iterator, "return")
)
),
createExpressionStatement(createDownlevelAwait(callReturn))
),
EmitFlags.SingleLine
)
]),
/*catchClause*/ undefined,
/*finallyBlock*/ setEmitFlags(
createBlock([
setEmitFlags(
createIf(
errorRecord,
createThrow(
createPropertyAccess(errorRecord, "error")
)
),
EmitFlags.SingleLine
)
]),
EmitFlags.SingleLine
)
)
])
);
}
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return updateParameter(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
node.dotDotDotToken,
getGeneratedNameForNode(node),
/*questionToken*/ undefined,
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
function visitConstructorDeclaration(node: ConstructorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = FunctionFlags.Normal;
const updated = updateConstructor(
node,
/*decorators*/ undefined,
node.modifiers,
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = FunctionFlags.Normal;
const updated = updateGetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = FunctionFlags.Normal;
const updated = updateSetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitMethodDeclaration(node: MethodDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = getFunctionFlags(node);
const updated = updateMethod(
node,
/*decorators*/ undefined,
enclosingFunctionFlags & FunctionFlags.Generator
? visitNodes(node.modifiers, visitorNoAsyncModifier, isModifier)
: node.modifiers,
enclosingFunctionFlags & FunctionFlags.Async
? undefined
: node.asteriskToken,
visitNode(node.name, visitor, isPropertyName),
visitNode<Token<SyntaxKind.QuestionToken>>(/*questionToken*/ undefined, visitor, isToken),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
? transformAsyncGeneratorFunctionBody(node)
: transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitFunctionDeclaration(node: FunctionDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = getFunctionFlags(node);
const updated = updateFunctionDeclaration(
node,
/*decorators*/ undefined,
enclosingFunctionFlags & FunctionFlags.Generator
? visitNodes(node.modifiers, visitorNoAsyncModifier, isModifier)
: node.modifiers,
enclosingFunctionFlags & FunctionFlags.Async
? undefined
: node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
? transformAsyncGeneratorFunctionBody(node)
: transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitArrowFunction(node: ArrowFunction) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = getFunctionFlags(node);
const updated = updateArrowFunction(
node,
node.modifiers,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.equalsGreaterThanToken,
transformFunctionBody(node),
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function visitFunctionExpression(node: FunctionExpression) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
enclosingFunctionFlags = getFunctionFlags(node);
const updated = updateFunctionExpression(
node,
enclosingFunctionFlags & FunctionFlags.Generator
? visitNodes(node.modifiers, visitorNoAsyncModifier, isModifier)
: node.modifiers,
enclosingFunctionFlags & FunctionFlags.Async
? undefined
: node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
? transformAsyncGeneratorFunctionBody(node)
: transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
return updated;
}
function transformAsyncGeneratorFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
resumeLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologue(statements, node.body!.statements, /*ensureUseStrict*/ false, visitor);
appendObjectRestAssignmentsIfNeeded(statements, node);
const savedCapturedSuperProperties = capturedSuperProperties;
const savedHasSuperElementAccess = hasSuperElementAccess;
capturedSuperProperties = createUnderscoreEscapedMap<true>();
hasSuperElementAccess = false;
const returnStatement = createReturn(
createAsyncGeneratorHelper(
context,
createFunctionExpression(
/*modifiers*/ undefined,
createToken(SyntaxKind.AsteriskToken),
node.name && getGeneratedNameForNode(node.name),
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
updateBlock(
node.body!,
visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset)
)
)
)
);
// 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.AsyncMethodWithSuperBinding | NodeCheckFlags.AsyncMethodWithSuper);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[getNodeId(variableStatement)] = true;
insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
const block = updateBlock(node.body!, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
addEmitHelper(block, advancedAsyncSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
addEmitHelper(block, asyncSuperHelper);
}
}
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
return block;
}
function transformFunctionBody(node: FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | AccessorDeclaration): FunctionBody;
function transformFunctionBody(node: ArrowFunction): ConciseBody;
function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
resumeLexicalEnvironment();
let statementOffset = 0;
const statements: Statement[] = [];
const body = visitNode(node.body, visitor, isConciseBody);
if (isBlock(body)) {
statementOffset = addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
const leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || some(statements) || some(leadingStatements)) {
const block = convertToFunctionBody(body, /*multiLine*/ true);
insertStatementsAfterStandardPrologue(statements, leadingStatements);
addRange(statements, block.statements.slice(statementOffset));
return updateBlock(block, setTextRange(createNodeArray(statements), block.statements));
}
return body;
}
function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined {
for (const parameter of node.parameters) {
if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
const temp = getGeneratedNameForNode(parameter);
const declarations = flattenDestructuringBinding(
parameter,
visitor,
context,
FlattenLevel.ObjectRest,
temp,
/*doNotRecordTempVariablesInLine*/ false,
/*skipInitializer*/ true,
);
if (some(declarations)) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
declarations
)
);
setEmitFlags(statement, EmitFlags.CustomPrologue);
statements = append(statements, statement);
}
}
}
return statements;
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & ESNextSubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= ESNextSubstitutionFlags.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);
}
}
/**
* Called by the printer just before a node is printed.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to be printed.
* @param emitCallback The callback used to emit the node.
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) {
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ESNextSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
const superContainerFlags = resolver.getNodeCheckFlags(node) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
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 as NodeCheckFlags;
previousOnEmitNode(hint, node, emitCallback);
enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
return;
}
previousOnEmitNode(hint, node, emitCallback);
}
/**
* Hooks node substitutions.
*
* @param hint The context for the emitter.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression && enclosingSuperContainerFlags) {
return substituteExpression(<Expression>node);
}
return node;
}
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
return substituteCallExpression(<CallExpression>node);
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (node.expression.kind === SyntaxKind.SuperKeyword) {
return setTextRange(
createPropertyAccess(
createFileLevelUniqueName("_super"),
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 createCall(
createPropertyAccess(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
createThis(),
...node.arguments
]
);
}
return node;
}
function isSuperContainer(node: Node) {
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.AsyncMethodWithSuperBinding) {
return setTextRange(
createPropertyAccess(
createCall(
createIdentifier("_superIndex"),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value"
),
location
);
}
else {
return setTextRange(
createCall(
createIdentifier("_superIndex"),
/*typeArguments*/ undefined,
[argumentExpression]
),
location
);
}
}
}
export const assignHelper: UnscopedEmitHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
text: `
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};`
};
export function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]) {
if (context.getCompilerOptions().target! >= ScriptTarget.ES2015) {
return createCall(createPropertyAccess(createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined,
attributesSegments);
}
context.requestEmitHelper(assignHelper);
return createCall(
getHelperName("__assign"),
/*typeArguments*/ undefined,
attributesSegments
);
}
export const awaitHelper: UnscopedEmitHelper = {
name: "typescript:await",
scoped: false,
text: `
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }`
};
function createAwaitHelper(context: TransformationContext, expression: Expression) {
context.requestEmitHelper(awaitHelper);
return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
export const asyncGeneratorHelper: UnscopedEmitHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: `
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }