forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
es2018.ts
1432 lines (1325 loc) · 65.7 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
import {
__String,
AccessorDeclaration,
addEmitFlags,
addEmitHelper,
addEmitHelpers,
addRange,
advancedAsyncSuperHelper,
append,
ArrowFunction,
asyncSuperHelper,
AwaitExpression,
BinaryExpression,
Bundle,
CallExpression,
CatchClause,
chainBundle,
CommaListExpression,
concatenate,
ConciseBody,
ConstructorDeclaration,
createForOfBindingStatement,
createSuperAccessVariableStatement,
Debug,
ElementAccessExpression,
EmitFlags,
EmitHint,
Expression,
ExpressionStatement,
flattenDestructuringAssignment,
flattenDestructuringBinding,
FlattenLevel,
ForInitializer,
ForOfStatement,
ForStatement,
FunctionBody,
FunctionDeclaration,
FunctionExpression,
FunctionFlags,
FunctionLikeDeclaration,
GeneratedIdentifierFlags,
GetAccessorDeclaration,
getEmitScriptTarget,
getFunctionFlags,
getNodeId,
hasSyntacticModifier,
Identifier,
insertStatementsAfterStandardPrologue,
isAssignmentPattern,
isBindingPattern,
isBlock,
isConciseBody,
isDestructuringAssignment,
isEffectiveStrictModeSourceFile,
isExpression,
isForInitializer,
isIdentifier,
isModifier,
isModifierLike,
isObjectLiteralElementLike,
isParameter,
isPropertyAccessExpression,
isPropertyName,
isQuestionToken,
isStatement,
isSuperProperty,
isVariableDeclarationList,
LabeledStatement,
LeftHandSideExpression,
MethodDeclaration,
ModifierFlags,
Node,
NodeCheckFlags,
NodeFlags,
ObjectLiteralElementLike,
ObjectLiteralExpression,
ParameterDeclaration,
ParenthesizedExpression,
ProcessLevel,
processTaggedTemplateExpression,
PropertyAccessExpression,
ReturnStatement,
ScriptTarget,
SetAccessorDeclaration,
setEmitFlags,
setOriginalNode,
setSourceMapRange,
setTextRange,
SignatureDeclaration,
skipParentheses,
some,
SourceFile,
startOnNewLine,
Statement,
SyntaxKind,
TaggedTemplateExpression,
TextRange,
TransformationContext,
TransformFlags,
unwrapInnermostStatementOfLabel,
VariableDeclaration,
VariableStatement,
visitEachChild,
visitIterationBody,
visitLexicalEnvironment,
visitNode,
visitNodes,
visitParameterList,
VisitResult,
VoidExpression,
YieldExpression,
} from "../_namespaces/ts";
const enum ESNextSubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
// Facts we track as we traverse the tree
const enum HierarchyFacts {
None = 0,
//
// Ancestor facts
//
HasLexicalThis = 1 << 0,
IterationContainer = 1 << 1,
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
//
// Ancestor masks
//
AncestorFactsMask = (IterationContainer << 1) - 1,
SourceFileIncludes = HasLexicalThis,
SourceFileExcludes = IterationContainer,
StrictModeSourceFileIncludes = None,
ClassOrFunctionIncludes = HasLexicalThis,
ClassOrFunctionExcludes = IterationContainer,
ArrowFunctionIncludes = None,
ArrowFunctionExcludes = ClassOrFunctionExcludes,
IterationStatementIncludes = IterationContainer,
IterationStatementExcludes = None,
}
/** @internal */
export function transformES2018(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle {
const {
factory,
getEmitHelperFactory: emitHelpers,
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 exportedVariableStatement = false;
let enabledSubstitutions: ESNextSubstitutionFlags;
let enclosingFunctionFlags: FunctionFlags;
let parametersWithPrecedingObjectRestOrSpread: Set<ParameterDeclaration> | undefined;
let enclosingSuperContainerFlags: NodeCheckFlags = 0;
let hierarchyFacts: HierarchyFacts = 0;
let currentSourceFile: SourceFile;
let taggedTemplateStringDeclarations: VariableDeclaration[];
/** 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. */
const substitutedSuperAccessors: boolean[] = [];
return chainBundle(context, transformSourceFile);
function affectsSubtree(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
}
/**
* Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
* @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
* @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
*/
function enterSubtree(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
const ancestorFacts = hierarchyFacts;
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & HierarchyFacts.AncestorFactsMask;
return ancestorFacts;
}
/**
* Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
* subtree.
* @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
*/
function exitSubtree(ancestorFacts: HierarchyFacts) {
hierarchyFacts = ancestorFacts;
}
function recordTaggedTemplateString(temp: Identifier) {
taggedTemplateStringDeclarations = append(
taggedTemplateStringDeclarations,
factory.createVariableDeclaration(temp));
}
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
currentSourceFile = node;
const visited = visitSourceFile(node);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined!;
taggedTemplateStringDeclarations = undefined!;
return visited;
}
function visitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*expressionResultIsUnused*/ false);
}
function visitorWithUnusedExpressionResult(node: Node): VisitResult<Node> {
return visitorWorker(node, /*expressionResultIsUnused*/ true);
}
function visitorNoAsyncModifier(node: Node): VisitResult<Node | undefined> {
if (node.kind === SyntaxKind.AsyncKeyword) {
return undefined;
}
return node;
}
function doWithHierarchyFacts<T, U>(cb: (value: T) => U, value: T, excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
if (affectsSubtree(excludeFacts, includeFacts)) {
const ancestorFacts = enterSubtree(excludeFacts, includeFacts);
const result = cb(value);
exitSubtree(ancestorFacts);
return result;
}
return cb(value);
}
function visitDefault(node: Node): VisitResult<Node> {
return visitEachChild(node, visitor, context);
}
/**
* @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
* expression of an `ExpressionStatement`).
*/
function visitorWorker(node: Node, expressionResultIsUnused: 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, expressionResultIsUnused);
case SyntaxKind.CommaListExpression:
return visitCommaListExpression(node as CommaListExpression, expressionResultIsUnused);
case SyntaxKind.CatchClause:
return visitCatchClause(node as CatchClause);
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForInStatement:
return doWithHierarchyFacts(
visitDefault,
node,
HierarchyFacts.IterationStatementExcludes,
HierarchyFacts.IterationStatementIncludes);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForStatement:
return doWithHierarchyFacts(
visitForStatement,
node as ForStatement,
HierarchyFacts.IterationStatementExcludes,
HierarchyFacts.IterationStatementIncludes);
case SyntaxKind.VoidExpression:
return visitVoidExpression(node as VoidExpression);
case SyntaxKind.Constructor:
return doWithHierarchyFacts(
visitConstructorDeclaration,
node as ConstructorDeclaration,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.MethodDeclaration:
return doWithHierarchyFacts(
visitMethodDeclaration,
node as MethodDeclaration,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.GetAccessor:
return doWithHierarchyFacts(
visitGetAccessorDeclaration,
node as GetAccessorDeclaration,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.SetAccessor:
return doWithHierarchyFacts(
visitSetAccessorDeclaration,
node as SetAccessorDeclaration,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.FunctionDeclaration:
return doWithHierarchyFacts(
visitFunctionDeclaration,
node as FunctionDeclaration,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.FunctionExpression:
return doWithHierarchyFacts(
visitFunctionExpression,
node as FunctionExpression,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
case SyntaxKind.ArrowFunction:
return doWithHierarchyFacts(
visitArrowFunction,
node as ArrowFunction,
HierarchyFacts.ArrowFunctionExcludes,
HierarchyFacts.ArrowFunctionIncludes);
case SyntaxKind.Parameter:
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, expressionResultIsUnused);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
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.ClassDeclaration:
case SyntaxKind.ClassExpression:
return doWithHierarchyFacts(
visitDefault,
node,
HierarchyFacts.ClassOrFunctionExcludes,
HierarchyFacts.ClassOrFunctionIncludes);
default:
return visitEachChild(node, visitor, context);
}
}
function visitAwaitExpression(node: AwaitExpression): Expression {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
return setOriginalNode(
setTextRange(
factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(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(Debug.checkDefined(node.expression), visitor, isExpression);
return setOriginalNode(
setTextRange(
factory.createYieldExpression(
/*asteriskToken*/ undefined,
emitHelpers().createAwaitHelper(
factory.updateYieldExpression(
node,
node.asteriskToken,
setTextRange(
emitHelpers().createAsyncDelegatorHelper(
setTextRange(
emitHelpers().createAsyncValuesHelper(expression),
expression
)
),
expression
)
)
)
),
node
),
node
);
}
return setOriginalNode(
setTextRange(
factory.createYieldExpression(
/*asteriskToken*/ undefined,
createDownlevelAwait(
node.expression
? visitNode(node.expression, visitor, isExpression)
: factory.createVoidZero()
)
),
node
),
node
);
}
return visitEachChild(node, visitor, context);
}
function visitReturnStatement(node: ReturnStatement) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
return factory.updateReturnStatement(node, createDownlevelAwait(
node.expression ? visitNode(node.expression, visitor, isExpression) : factory.createVoidZero()
));
}
return visitEachChild(node, visitor, context);
}
function visitLabeledStatement(node: LabeledStatement) {
if (enclosingFunctionFlags & FunctionFlags.Async) {
const statement = unwrapInnermostStatementOfLabel(node);
if (statement.kind === SyntaxKind.ForOfStatement && (statement as ForOfStatement).awaitModifier) {
return visitForOfStatement(statement as ForOfStatement, node);
}
return factory.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory.liftToBlock), node);
}
return visitEachChild(node, visitor, context);
}
function chunkObjectLiteralElements(elements: readonly ObjectLiteralElementLike[]): Expression[] {
let chunkObject: ObjectLiteralElementLike[] | undefined;
const objects: Expression[] = [];
for (const e of elements) {
if (e.kind === SyntaxKind.SpreadAssignment) {
if (chunkObject) {
objects.push(factory.createObjectLiteralExpression(chunkObject));
chunkObject = undefined;
}
const target = e.expression;
objects.push(visitNode(target, visitor, isExpression));
}
else {
chunkObject = append(chunkObject, e.kind === SyntaxKind.PropertyAssignment
? factory.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression))
: visitNode(e, visitor, isObjectLiteralElementLike));
}
}
if (chunkObject) {
objects.push(factory.createObjectLiteralExpression(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(__assign({a}, o), {b});
// If the first element is a spread element, then the first argument to __assign is {}:
// { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
//
// We cannot call __assign with more than two elements, since any element could cause side effects. For
// example:
// var k = { a: 1, b: 2 };
// var o = { a: 3, ...k, b: k.a++ };
// // expected: { a: 1, b: 1 }
// If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
// `k` is spread and we end up with `{ a: 2, b: 1 }`.
//
// This also occurs for spread elements, not just property assignments:
// var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
// var l = { c: 3 };
// var o = { ...k, ...l };
// // expected: { a: 1, b: 2, z: 9 }
// If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
// end up with `{ a: 1, b: 2, c: 3 }`
const objects = chunkObjectLiteralElements(node.properties);
if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) {
objects.unshift(factory.createObjectLiteralExpression());
}
let expression: Expression = objects[0];
if (objects.length > 1) {
for (let i = 1; i < objects.length; i++) {
expression = emitHelpers().createAssignHelper([expression, objects[i]]);
}
return expression;
}
else {
return emitHelpers().createAssignHelper(objects);
}
}
return visitEachChild(node, visitor, context);
}
function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement {
return visitEachChild(node, visitorWithUnusedExpressionResult, context);
}
/**
* @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
* expression of an `ExpressionStatement`).
*/
function visitParenthesizedExpression(node: ParenthesizedExpression, expressionResultIsUnused: boolean): ParenthesizedExpression {
return visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
}
function visitSourceFile(node: SourceFile): SourceFile {
const ancestorFacts = enterSubtree(
HierarchyFacts.SourceFileExcludes,
isEffectiveStrictModeSourceFile(node, compilerOptions) ?
HierarchyFacts.StrictModeSourceFileIncludes :
HierarchyFacts.SourceFileIncludes);
exportedVariableStatement = false;
const visited = visitEachChild(node, visitor, context);
const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [
factory.createVariableStatement(/*modifiers*/ undefined,
factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
]);
const result = factory.updateSourceFile(visited, setTextRange(factory.createNodeArray(statement), node.statements));
exitSubtree(ancestorFacts);
return result;
}
function visitTaggedTemplateExpression(node: TaggedTemplateExpression) {
return processTaggedTemplateExpression(
context,
node,
visitor,
currentSourceFile,
recordTaggedTemplateString,
ProcessLevel.LiftRestriction
);
}
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
* @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
* expression of an `ExpressionStatement`).
*/
function visitBinaryExpression(node: BinaryExpression, expressionResultIsUnused: boolean): Expression {
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
return flattenDestructuringAssignment(
node,
visitor,
context,
FlattenLevel.ObjectRest,
!expressionResultIsUnused
);
}
if (node.operatorToken.kind === SyntaxKind.CommaToken) {
return factory.updateBinaryExpression(
node,
visitNode(node.left, visitorWithUnusedExpressionResult, isExpression),
node.operatorToken,
visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
/**
* @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
* expression of an `ExpressionStatement`).
*/
function visitCommaListExpression(node: CommaListExpression, expressionResultIsUnused: boolean): Expression {
if (expressionResultIsUnused) {
return visitEachChild(node, visitorWithUnusedExpressionResult, context);
}
let result: Expression[] | undefined;
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression);
if (result || visited !== element) {
result ||= node.elements.slice(0, i);
result.push(visited);
}
}
const elements = result ? setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
return factory.updateCommaListExpression(node, elements);
}
function visitCatchClause(node: CatchClause) {
if (node.variableDeclaration &&
isBindingPattern(node.variableDeclaration.name) &&
node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
const name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
const updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, FlattenLevel.ObjectRest);
let block = visitNode(node.block, visitor, isBlock);
if (some(visitedBindings)) {
block = factory.updateBlock(block, [
factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings),
...block.statements,
]);
}
return factory.updateCatchClause(
node,
factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined),
block);
}
return visitEachChild(node, visitor, context);
}
function visitVariableStatement(node: VariableStatement): VisitResult<VariableStatement> {
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
const savedExportedVariableStatement = exportedVariableStatement;
exportedVariableStatement = true;
const visited = visitEachChild(node, visitor, context);
exportedVariableStatement = savedExportedVariableStatement;
return visited;
}
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 (exportedVariableStatement) {
const savedExportedVariableStatement = exportedVariableStatement;
exportedVariableStatement = false;
const visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
exportedVariableStatement = savedExportedVariableStatement;
return visited;
}
return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
}
function visitVariableDeclarationWorker(node: VariableDeclaration, exportedVariableStatement: boolean): 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,
/*rval*/ undefined,
exportedVariableStatement
);
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement): VisitResult<Statement> {
return factory.updateForStatement(
node,
visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression),
visitIterationBody(node.statement, visitor, context)
);
}
function visitVoidExpression(node: VoidExpression) {
return visitEachChild(node, visitorWithUnusedExpressionResult, 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> {
const ancestorFacts = enterSubtree(HierarchyFacts.IterationStatementExcludes, HierarchyFacts.IterationStatementIncludes);
if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
node = transformForOfStatementWithObjectRest(node);
}
const result = node.awaitModifier ?
transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
factory.restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement);
exitSubtree(ancestorFacts);
return result;
}
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 = factory.createTempVariable(/*recordTempVariable*/ undefined);
const statements: Statement[] = [createForOfBindingStatement(factory, 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 factory.updateForOfStatement(
node,
node.awaitModifier,
setTextRange(
factory.createVariableDeclarationList(
[
setTextRange(factory.createVariableDeclaration(temp), node.initializer)
],
NodeFlags.Let
),
node.initializer
),
node.expression,
setTextRange(
factory.createBlock(
setTextRange(factory.createNodeArray(statements), statementsLocation),
/*multiLine*/ true
),
bodyLocation
)
);
}
return node;
}
function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression, nonUserCode: Identifier) {
const value = factory.createTempVariable(hoistVariableDeclaration);
const iteratorValueExpression = factory.createAssignment(value, boundValue);
const iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression);
setSourceMapRange(iteratorValueStatement, node.expression);
const exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse());
const exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression);
setSourceMapRange(exitNonUserCodeStatement, node.expression);
const statements: Statement[] = [iteratorValueStatement, exitNonUserCodeStatement];
const binding = createForOfBindingStatement(factory, node.initializer, value);
statements.push(visitNode(binding, visitor, isStatement));
let bodyLocation: TextRange | undefined;
let statementsLocation: TextRange | undefined;
const statement = visitIterationBody(node.statement, visitor, context);
if (isBlock(statement)) {
addRange(statements, statement.statements);
bodyLocation = statement;
statementsLocation = statement.statements;
}
else {
statements.push(statement);
}
return setTextRange(
factory.createBlock(
setTextRange(factory.createNodeArray(statements), statementsLocation),
/*multiLine*/ true
),
bodyLocation
);
}
function createDownlevelAwait(expression: Expression) {
return enclosingFunctionFlags & FunctionFlags.Generator
? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
: factory.createAwaitExpression(expression);
}
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined, ancestorFacts: HierarchyFacts) {
const expression = visitNode(node.expression, visitor, isExpression);
const iterator = isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
const result = isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
const nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined);
const done = factory.createTempVariable(hoistVariableDeclaration);
const errorRecord = factory.createUniqueName("e");
const catchVariable = factory.getGeneratedNameForNode(errorRecord);
const returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
const callValues = setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
const callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
const getDone = factory.createPropertyAccessExpression(result, "done");
const getValue = factory.createPropertyAccessExpression(result, "value");
const callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
hoistVariableDeclaration(errorRecord);
hoistVariableDeclaration(returnMethod);
// if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
const initializer = ancestorFacts & HierarchyFacts.IterationContainer ?
factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
callValues;
const forStatement = setEmitFlags(
setTextRange(
factory.createForStatement(
/*initializer*/ setEmitFlags(
setTextRange(
factory.createVariableDeclarationList([
factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()),
setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
factory.createVariableDeclaration(result)
]),
node.expression
),
EmitFlags.NoHoisting
),
/*condition*/ factory.inlineExpressions([
factory.createAssignment(result, createDownlevelAwait(callNext)),
factory.createAssignment(done, getDone),
factory.createLogicalNot(done)
]),
/*incrementor*/ factory.createAssignment(nonUserCode, factory.createTrue()),
/*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)
),
/*location*/ node
),
EmitFlags.NoTokenTrailingSourceMaps
);
setOriginalNode(forStatement, node);
return factory.createTryStatement(
factory.createBlock([
factory.restoreEnclosingLabel(
forStatement,
outermostLabeledStatement
)
]),
factory.createCatchClause(
factory.createVariableDeclaration(catchVariable),
setEmitFlags(
factory.createBlock([
factory.createExpressionStatement(
factory.createAssignment(
errorRecord,
factory.createObjectLiteralExpression([
factory.createPropertyAssignment("error", catchVariable)
])
)
)
]),
EmitFlags.SingleLine
)
),
factory.createBlock([
factory.createTryStatement(
/*tryBlock*/ factory.createBlock([
setEmitFlags(
factory.createIfStatement(
factory.createLogicalAnd(
factory.createLogicalAnd(
factory.createLogicalNot(nonUserCode),
factory.createLogicalNot(done),
),
factory.createAssignment(
returnMethod,
factory.createPropertyAccessExpression(iterator, "return")
)
),
factory.createExpressionStatement(createDownlevelAwait(callReturn))
),
EmitFlags.SingleLine
)
]),
/*catchClause*/ undefined,
/*finallyBlock*/ setEmitFlags(
factory.createBlock([
setEmitFlags(
factory.createIfStatement(
errorRecord,
factory.createThrowStatement(
factory.createPropertyAccessExpression(errorRecord, "error")
)
),
EmitFlags.SingleLine
)
]),
EmitFlags.SingleLine
)
)
])
);
}
function parameterVisitor(node: Node) {
Debug.assertNode(node, isParameter);
return visitParameter(node);
}
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
if (parametersWithPrecedingObjectRestOrSpread?.has(node)) {
return factory.updateParameterDeclaration(
node,
/*modifiers*/ undefined,
node.dotDotDotToken,
isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name,
/*questionToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined
);
}
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return factory.updateParameterDeclaration(
node,
/*modifiers*/ undefined,
node.dotDotDotToken,
factory.getGeneratedNameForNode(node),
/*questionToken*/ undefined,
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
function collectParametersWithPrecedingObjectRestOrSpread(node: SignatureDeclaration) {
let parameters: Set<ParameterDeclaration> | undefined;
for (const parameter of node.parameters) {
if (parameters) {
parameters.add(parameter);
}
else if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
parameters = new Set();
}
}
return parameters;
}
function visitConstructorDeclaration(node: ConstructorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
enclosingFunctionFlags = getFunctionFlags(node);
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
const updated = factory.updateConstructorDeclaration(
node,
node.modifiers,
visitParameterList(node.parameters, parameterVisitor, context),
transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
return updated;
}
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
enclosingFunctionFlags = getFunctionFlags(node);
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
const updated = factory.updateGetAccessorDeclaration(
node,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, parameterVisitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
enclosingFunctionFlags = savedEnclosingFunctionFlags;
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
return updated;
}
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
enclosingFunctionFlags = getFunctionFlags(node);
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
const updated = factory.updateSetAccessorDeclaration(
node,
node.modifiers,