/
generators.ts
3183 lines (2883 loc) · 128 KB
/
generators.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
// Transforms generator functions into a compatible ES5 representation with similar runtime
// semantics. This is accomplished by first transforming the body of each generator
// function into an intermediate representation that is the compiled into a JavaScript
// switch statement.
//
// Many functions in this transformer will contain comments indicating the expected
// intermediate representation. For illustrative purposes, the following intermediate
// language is used to define this intermediate representation:
//
// .nop - Performs no operation.
// .local NAME, ... - Define local variable declarations.
// .mark LABEL - Mark the location of a label.
// .br LABEL - Jump to a label. If jumping out of a protected
// region, all .finally blocks are executed.
// .brtrue LABEL, (x) - Jump to a label IIF the expression `x` is truthy.
// If jumping out of a protected region, all .finally
// blocks are executed.
// .brfalse LABEL, (x) - Jump to a label IIF the expression `x` is falsey.
// If jumping out of a protected region, all .finally
// blocks are executed.
// .yield (x) - Yield the value of the optional expression `x`.
// Resume at the next label.
// .yieldstar (x) - Delegate yield to the value of the optional
// expression `x`. Resume at the next label.
// NOTE: `x` must be an Iterator, not an Iterable.
// .loop CONTINUE, BREAK - Marks the beginning of a loop. Any "continue" or
// "break" abrupt completions jump to the CONTINUE or
// BREAK labels, respectively.
// .endloop - Marks the end of a loop.
// .with (x) - Marks the beginning of a WithStatement block, using
// the supplied expression.
// .endwith - Marks the end of a WithStatement.
// .switch - Marks the beginning of a SwitchStatement.
// .endswitch - Marks the end of a SwitchStatement.
// .labeled NAME - Marks the beginning of a LabeledStatement with the
// supplied name.
// .endlabeled - Marks the end of a LabeledStatement.
// .try TRY, CATCH, FINALLY, END - Marks the beginning of a protected region, and the
// labels for each block.
// .catch (x) - Marks the beginning of a catch block.
// .finally - Marks the beginning of a finally block.
// .endfinally - Marks the end of a finally block.
// .endtry - Marks the end of a protected region.
// .throw (x) - Throws the value of the expression `x`.
// .return (x) - Returns the value of the expression `x`.
//
// In addition, the illustrative intermediate representation introduces some special
// variables:
//
// %sent% - Either returns the next value sent to the generator,
// returns the result of a delegated yield, or throws
// the exception sent to the generator.
// %error% - Returns the value of the current exception in a
// catch block.
//
// This intermediate representation is then compiled into JavaScript syntax. The resulting
// compilation output looks something like the following:
//
// function f() {
// var /*locals*/;
// /*functions*/
// return __generator(function (state) {
// switch (state.label) {
// /*cases per label*/
// }
// });
// }
//
// Each of the above instructions corresponds to JavaScript emit similar to the following:
//
// .local NAME | var NAME;
// -------------------------------|----------------------------------------------
// .mark LABEL | case LABEL:
// -------------------------------|----------------------------------------------
// .br LABEL | return [3 /*break*/, LABEL];
// -------------------------------|----------------------------------------------
// .brtrue LABEL, (x) | if (x) return [3 /*break*/, LABEL];
// -------------------------------|----------------------------------------------
// .brfalse LABEL, (x) | if (!(x)) return [3, /*break*/, LABEL];
// -------------------------------|----------------------------------------------
// .yield (x) | return [4 /*yield*/, x];
// .mark RESUME | case RESUME:
// a = %sent%; | a = state.sent();
// -------------------------------|----------------------------------------------
// .yieldstar (x) | return [5 /*yield**/, x];
// .mark RESUME | case RESUME:
// a = %sent%; | a = state.sent();
// -------------------------------|----------------------------------------------
// .with (_a) | with (_a) {
// a(); | a();
// | }
// | state.label = LABEL;
// .mark LABEL | case LABEL:
// | with (_a) {
// b(); | b();
// | }
// .endwith |
// -------------------------------|----------------------------------------------
// | case 0:
// | state.trys = [];
// | ...
// .try TRY, CATCH, FINALLY, END |
// .mark TRY | case TRY:
// | state.trys.push([TRY, CATCH, FINALLY, END]);
// .nop |
// a(); | a();
// .br END | return [3 /*break*/, END];
// .catch (e) |
// .mark CATCH | case CATCH:
// | e = state.sent();
// b(); | b();
// .br END | return [3 /*break*/, END];
// .finally |
// .mark FINALLY | case FINALLY:
// c(); | c();
// .endfinally | return [7 /*endfinally*/];
// .endtry |
// .mark END | case END:
/*@internal*/
namespace ts {
type Label = number;
const enum OpCode {
Nop, // No operation, used to force a new case in the state machine
Statement, // A regular javascript statement
Assign, // An assignment
Break, // A break instruction used to jump to a label
BreakWhenTrue, // A break instruction used to jump to a label if a condition evaluates to true
BreakWhenFalse, // A break instruction used to jump to a label if a condition evaluates to false
Yield, // A completion instruction for the `yield` keyword
YieldStar, // A completion instruction for the `yield*` keyword (not implemented, but reserved for future use)
Return, // A completion instruction for the `return` keyword
Throw, // A completion instruction for the `throw` keyword
Endfinally // Marks the end of a `finally` block
}
type OperationArguments = [Label] | [Label, Expression] | [Statement] | [Expression | undefined] | [Expression, Expression];
// whether a generated code block is opening or closing at the current operation for a FunctionBuilder
const enum BlockAction {
Open,
Close,
}
// the kind for a generated code block in a FunctionBuilder
const enum CodeBlockKind {
Exception,
With,
Switch,
Loop,
Labeled
}
// the state for a generated code exception block
const enum ExceptionBlockState {
Try,
Catch,
Finally,
Done
}
// A generated code block
type CodeBlock = | ExceptionBlock | LabeledBlock | SwitchBlock | LoopBlock | WithBlock;
// a generated exception block, used for 'try' statements
interface ExceptionBlock {
kind: CodeBlockKind.Exception;
state: ExceptionBlockState;
startLabel: Label;
catchVariable?: Identifier;
catchLabel?: Label;
finallyLabel?: Label;
endLabel: Label;
}
// A generated code that tracks the target for 'break' statements in a LabeledStatement.
interface LabeledBlock {
kind: CodeBlockKind.Labeled;
labelText: string;
isScript: boolean;
breakLabel: Label;
}
// a generated block that tracks the target for 'break' statements in a 'switch' statement
interface SwitchBlock {
kind: CodeBlockKind.Switch;
isScript: boolean;
breakLabel: Label;
}
// a generated block that tracks the targets for 'break' and 'continue' statements, used for iteration statements
interface LoopBlock {
kind: CodeBlockKind.Loop;
continueLabel: Label;
isScript: boolean;
breakLabel: Label;
}
// a generated block associated with a 'with' statement
interface WithBlock {
kind: CodeBlockKind.With;
expression: Identifier;
startLabel: Label;
endLabel: Label;
}
// NOTE: changes to this enum should be reflected in the __generator helper.
const enum Instruction {
Next = 0,
Throw = 1,
Return = 2,
Break = 3,
Yield = 4,
YieldStar = 5,
Catch = 6,
Endfinally = 7,
}
function getInstructionName(instruction: Instruction): string {
switch (instruction) {
case Instruction.Return: return "return";
case Instruction.Break: return "break";
case Instruction.Yield: return "yield";
case Instruction.YieldStar: return "yield*";
case Instruction.Endfinally: return "endfinally";
default: return undefined!; // TODO: GH#18217
}
}
export function transformGenerators(context: TransformationContext) {
const {
factory,
getEmitHelperFactory: emitHelpers,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistFunctionDeclaration,
hoistVariableDeclaration
} = context;
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const resolver = context.getEmitResolver();
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
let renamedCatchVariables: ESMap<string, boolean>;
let renamedCatchVariableDeclarations: Identifier[];
let inGeneratorFunctionBody: boolean;
let inStatementContainingYield: boolean;
// The following three arrays store information about generated code blocks.
// All three arrays are correlated by their index. This approach is used over allocating
// objects to store the same information to avoid GC overhead.
//
let blocks: CodeBlock[] | undefined; // Information about the code block
let blockOffsets: number[] | undefined; // The operation offset at which a code block begins or ends
let blockActions: BlockAction[] | undefined; // Whether the code block is opened or closed
let blockStack: CodeBlock[] | undefined; // A stack of currently open code blocks
// Labels are used to mark locations in the code that can be the target of a Break (jump)
// operation. These are translated into case clauses in a switch statement.
// The following two arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
let labelOffsets: number[] | undefined; // The operation offset at which the label is defined.
let labelExpressions: Mutable<LiteralExpression>[][] | undefined; // The NumericLiteral nodes bound to each label.
let nextLabelId = 1; // The next label id to use.
// Operations store information about generated code for the function body. This
// Includes things like statements, assignments, breaks (jumps), and yields.
// The following three arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
let operations: OpCode[] | undefined; // The operation to perform.
let operationArguments: (OperationArguments | undefined)[] | undefined; // The arguments to the operation.
let operationLocations: (TextRange | undefined)[] | undefined; // The source map location for the operation.
let state: Identifier; // The name of the state object used by the generator at runtime.
// The following variables store information used by the `build` function:
//
let blockIndex = 0; // The index of the current block.
let labelNumber = 0; // The current label number.
let labelNumbers: number[][] | undefined;
let lastOperationWasAbrupt: boolean; // Indicates whether the last operation was abrupt (break/continue).
let lastOperationWasCompletion: boolean; // Indicates whether the last operation was a completion (return/throw).
let clauses: CaseClause[] | undefined; // The case clauses generated for labels.
let statements: Statement[] | undefined; // The statements for the current label.
let exceptionBlockStack: ExceptionBlock[] | undefined; // A stack of containing exception blocks.
let currentExceptionBlock: ExceptionBlock | undefined; // The current exception block.
let withBlockStack: WithBlock[] | undefined; // A stack containing `with` blocks.
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
/**
* Visits a node.
*
* @param node The node to visit.
*/
function visitor(node: Node): VisitResult<Node> {
const transformFlags = node.transformFlags;
if (inStatementContainingYield) {
return visitJavaScriptInStatementContainingYield(node);
}
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
else if (isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
else if (transformFlags & TransformFlags.ContainsGenerator) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
}
/**
* Visits a node that is contained within a statement that contains yield.
*
* @param node The node to visit.
*/
function visitJavaScriptInStatementContainingYield(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.DoStatement:
return visitDoStatement(<DoStatement>node);
case SyntaxKind.WhileStatement:
return visitWhileStatement(<WhileStatement>node);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
default:
return visitJavaScriptInGeneratorFunctionBody(node);
}
}
/**
* Visits a node that is contained within a generator function.
*
* @param node The node to visit.
*/
function visitJavaScriptInGeneratorFunctionBody(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return visitAccessorDeclaration(<AccessorDeclaration>node);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node);
case SyntaxKind.BreakStatement:
return visitBreakStatement(<BreakStatement>node);
case SyntaxKind.ContinueStatement:
return visitContinueStatement(<ContinueStatement>node);
case SyntaxKind.ReturnStatement:
return visitReturnStatement(<ReturnStatement>node);
default:
if (node.transformFlags & TransformFlags.ContainsYield) {
return visitJavaScriptContainingYield(node);
}
else if (node.transformFlags & (TransformFlags.ContainsGenerator | TransformFlags.ContainsHoistedDeclarationOrCompletion)) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
}
}
/**
* Visits a node that contains a YieldExpression.
*
* @param node The node to visit.
*/
function visitJavaScriptContainingYield(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
case SyntaxKind.CommaListExpression:
return visitCommaListExpression(<CommaListExpression>node);
case SyntaxKind.ConditionalExpression:
return visitConditionalExpression(<ConditionalExpression>node);
case SyntaxKind.YieldExpression:
return visitYieldExpression(<YieldExpression>node);
case SyntaxKind.ArrayLiteralExpression:
return visitArrayLiteralExpression(<ArrayLiteralExpression>node);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.ElementAccessExpression:
return visitElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
default:
return visitEachChild(node, visitor, context);
}
}
/**
* Visits a generator function.
*
* @param node The node to visit.
*/
function visitGenerator(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
default:
return Debug.failBadSyntaxKind(node);
}
}
/**
* Visits a function declaration.
*
* This will be called when one of the following conditions are met:
* - The function declaration is a generator function.
* - The function declaration is contained within the body of a generator function.
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): Statement | undefined {
// Currently, we only support generators that were originally async functions.
if (node.asteriskToken) {
node = setOriginalNode(
setTextRange(
factory.createFunctionDeclaration(
/*decorators*/ undefined,
node.modifiers,
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformGeneratorFunctionBody(node.body!)
),
/*location*/ node
),
node
);
}
else {
const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
const savedInStatementContainingYield = inStatementContainingYield;
inGeneratorFunctionBody = false;
inStatementContainingYield = false;
node = visitEachChild(node, visitor, context);
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
inStatementContainingYield = savedInStatementContainingYield;
}
if (inGeneratorFunctionBody) {
// Function declarations in a generator function body are hoisted
// to the top of the lexical scope and elided from the current statement.
hoistFunctionDeclaration(node);
return undefined;
}
else {
return node;
}
}
/**
* Visits a function expression.
*
* This will be called when one of the following conditions are met:
* - The function expression is a generator function.
* - The function expression is contained within the body of a generator function.
*
* @param node The node to visit.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
// Currently, we only support generators that were originally async functions.
if (node.asteriskToken) {
node = setOriginalNode(
setTextRange(
factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformGeneratorFunctionBody(node.body)
),
/*location*/ node
),
node
);
}
else {
const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
const savedInStatementContainingYield = inStatementContainingYield;
inGeneratorFunctionBody = false;
inStatementContainingYield = false;
node = visitEachChild(node, visitor, context);
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
inStatementContainingYield = savedInStatementContainingYield;
}
return node;
}
/**
* Visits a get or set accessor declaration.
*
* This will be called when one of the following conditions are met:
* - The accessor is contained within the body of a generator function.
*
* @param node The node to visit.
*/
function visitAccessorDeclaration(node: AccessorDeclaration) {
const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
const savedInStatementContainingYield = inStatementContainingYield;
inGeneratorFunctionBody = false;
inStatementContainingYield = false;
node = visitEachChild(node, visitor, context);
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
inStatementContainingYield = savedInStatementContainingYield;
return node;
}
/**
* Transforms the body of a generator function declaration.
*
* @param node The function body to transform.
*/
function transformGeneratorFunctionBody(body: Block) {
// Save existing generator state
const statements: Statement[] = [];
const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
const savedInStatementContainingYield = inStatementContainingYield;
const savedBlocks = blocks;
const savedBlockOffsets = blockOffsets;
const savedBlockActions = blockActions;
const savedBlockStack = blockStack;
const savedLabelOffsets = labelOffsets;
const savedLabelExpressions = labelExpressions;
const savedNextLabelId = nextLabelId;
const savedOperations = operations;
const savedOperationArguments = operationArguments;
const savedOperationLocations = operationLocations;
const savedState = state;
// Initialize generator state
inGeneratorFunctionBody = true;
inStatementContainingYield = false;
blocks = undefined;
blockOffsets = undefined;
blockActions = undefined;
blockStack = undefined;
labelOffsets = undefined;
labelExpressions = undefined;
nextLabelId = 1;
operations = undefined;
operationArguments = undefined;
operationLocations = undefined;
state = factory.createTempVariable(/*recordTempVariable*/ undefined);
// Build the generator
resumeLexicalEnvironment();
const statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
const buildResult = build();
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(factory.createReturnStatement(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
inStatementContainingYield = savedInStatementContainingYield;
blocks = savedBlocks;
blockOffsets = savedBlockOffsets;
blockActions = savedBlockActions;
blockStack = savedBlockStack;
labelOffsets = savedLabelOffsets;
labelExpressions = savedLabelExpressions;
nextLabelId = savedNextLabelId;
operations = savedOperations;
operationArguments = savedOperationArguments;
operationLocations = savedOperationLocations;
state = savedState;
return setTextRange(factory.createBlock(statements, body.multiLine), body);
}
/**
* Visits a variable statement.
*
* This will be called when one of the following conditions are met:
* - The variable statement is contained within the body of a generator function.
*
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): Statement | undefined {
if (node.transformFlags & TransformFlags.ContainsYield) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
else {
// Do not hoist custom prologues.
if (getEmitFlags(node) & EmitFlags.CustomPrologue) {
return node;
}
for (const variable of node.declarationList.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
}
const variables = getInitializedVariables(node.declarationList);
if (variables.length === 0) {
return undefined;
}
return setSourceMapRange(
factory.createExpressionStatement(
factory.inlineExpressions(
map(variables, transformInitializedVariable)
)
),
node
);
}
}
/**
* Visits a binary expression.
*
* This will be called when one of the following conditions are met:
* - The node contains a YieldExpression.
*
* @param node The node to visit.
*/
function visitBinaryExpression(node: BinaryExpression): Expression {
const assoc = getExpressionAssociativity(node);
switch (assoc) {
case Associativity.Left:
return visitLeftAssociativeBinaryExpression(node);
case Associativity.Right:
return visitRightAssociativeBinaryExpression(node);
default:
return Debug.assertNever(assoc);
}
}
/**
* Visits a right-associative binary expression containing `yield`.
*
* @param node The node to visit.
*/
function visitRightAssociativeBinaryExpression(node: BinaryExpression) {
const { left, right } = node;
if (containsYield(right)) {
let target: Expression;
switch (left.kind) {
case SyntaxKind.PropertyAccessExpression:
// [source]
// a.b = yield;
//
// [intermediate]
// .local _a
// _a = a;
// .yield resumeLabel
// .mark resumeLabel
// _a.b = %sent%;
target = factory.updatePropertyAccessExpression(
<PropertyAccessExpression>left,
cacheExpression(visitNode((<PropertyAccessExpression>left).expression, visitor, isLeftHandSideExpression)),
(<PropertyAccessExpression>left).name
);
break;
case SyntaxKind.ElementAccessExpression:
// [source]
// a[b] = yield;
//
// [intermediate]
// .local _a, _b
// _a = a;
// _b = b;
// .yield resumeLabel
// .mark resumeLabel
// _a[_b] = %sent%;
target = factory.updateElementAccessExpression(<ElementAccessExpression>left,
cacheExpression(visitNode((<ElementAccessExpression>left).expression, visitor, isLeftHandSideExpression)),
cacheExpression(visitNode((<ElementAccessExpression>left).argumentExpression, visitor, isExpression))
);
break;
default:
target = visitNode(left, visitor, isExpression);
break;
}
const operator = node.operatorToken.kind;
if (isCompoundAssignment(operator)) {
return setTextRange(
factory.createAssignment(
target,
setTextRange(
factory.createBinaryExpression(
cacheExpression(target),
getNonAssignmentOperatorForCompoundAssignment(operator),
visitNode(right, visitor, isExpression)
),
node
)
),
node
);
}
else {
return factory.updateBinaryExpression(node, target, node.operatorToken, visitNode(right, visitor, isExpression));
}
}
return visitEachChild(node, visitor, context);
}
function visitLeftAssociativeBinaryExpression(node: BinaryExpression) {
if (containsYield(node.right)) {
if (isLogicalOperator(node.operatorToken.kind)) {
return visitLogicalBinaryExpression(node);
}
else if (node.operatorToken.kind === SyntaxKind.CommaToken) {
return visitCommaExpression(node);
}
// [source]
// a() + (yield) + c()
//
// [intermediate]
// .local _a
// _a = a();
// .yield resumeLabel
// _a + %sent% + c()
return factory.updateBinaryExpression(node,
cacheExpression(visitNode(node.left, visitor, isExpression)),
node.operatorToken,
visitNode(node.right, visitor, isExpression));
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a comma expression containing `yield`.
*
* @param node The node to visit.
*/
function visitCommaExpression(node: BinaryExpression) {
// [source]
// x = a(), yield, b();
//
// [intermediate]
// a();
// .yield resumeLabel
// .mark resumeLabel
// x = %sent%, b();
let pendingExpressions: Expression[] = [];
visit(node.left);
visit(node.right);
return factory.inlineExpressions(pendingExpressions);
function visit(node: Expression) {
if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.CommaToken) {
visit(node.left);
visit(node.right);
}
else {
if (containsYield(node) && pendingExpressions.length > 0) {
emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
pendingExpressions = [];
}
pendingExpressions.push(visitNode(node, visitor, isExpression));
}
}
}
/**
* Visits a comma-list expression.
*
* @param node The node to visit.
*/
function visitCommaListExpression(node: CommaListExpression) {
// flattened version of `visitCommaExpression`
let pendingExpressions: Expression[] = [];
for (const elem of node.elements) {
if (isBinaryExpression(elem) && elem.operatorToken.kind === SyntaxKind.CommaToken) {
pendingExpressions.push(visitCommaExpression(elem));
}
else {
if (containsYield(elem) && pendingExpressions.length > 0) {
emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
pendingExpressions = [];
}
pendingExpressions.push(visitNode(elem, visitor, isExpression));
}
}
return factory.inlineExpressions(pendingExpressions);
}
/**
* Visits a logical binary expression containing `yield`.
*
* @param node A node to visit.
*/
function visitLogicalBinaryExpression(node: BinaryExpression) {
// Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
// to be transformed as such:
//
// [source]
// x = a() && yield;
//
// [intermediate]
// .local _a
// _a = a();
// .brfalse resultLabel, (_a)
// .yield resumeLabel
// .mark resumeLabel
// _a = %sent%;
// .mark resultLabel
// x = _a;
//
// [source]
// x = a() || yield;
//
// [intermediate]
// .local _a
// _a = a();
// .brtrue resultLabel, (_a)
// .yield resumeLabel
// .mark resumeLabel
// _a = %sent%;
// .mark resultLabel
// x = _a;
const resultLabel = defineLabel();
const resultLocal = declareLocal();
emitAssignment(resultLocal, visitNode(node.left, visitor, isExpression), /*location*/ node.left);
if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
// Logical `&&` shortcuts when the left-hand operand is falsey.
emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
}
else {
// Logical `||` shortcuts when the left-hand operand is truthy.
emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
}
emitAssignment(resultLocal, visitNode(node.right, visitor, isExpression), /*location*/ node.right);
markLabel(resultLabel);
return resultLocal;
}
/**
* Visits a conditional expression containing `yield`.
*
* @param node The node to visit.
*/
function visitConditionalExpression(node: ConditionalExpression): Expression {
// [source]
// x = a() ? yield : b();
//
// [intermediate]
// .local _a
// .brfalse whenFalseLabel, (a())
// .yield resumeLabel
// .mark resumeLabel
// _a = %sent%;
// .br resultLabel
// .mark whenFalseLabel
// _a = b();
// .mark resultLabel
// x = _a;
// We only need to perform a specific transformation if a `yield` expression exists
// in either the `whenTrue` or `whenFalse` branches.
// A `yield` in the condition will be handled by the normal visitor.
if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
const whenFalseLabel = defineLabel();
const resultLabel = defineLabel();
const resultLocal = declareLocal();
emitBreakWhenFalse(whenFalseLabel, visitNode(node.condition, visitor, isExpression), /*location*/ node.condition);
emitAssignment(resultLocal, visitNode(node.whenTrue, visitor, isExpression), /*location*/ node.whenTrue);
emitBreak(resultLabel);
markLabel(whenFalseLabel);
emitAssignment(resultLocal, visitNode(node.whenFalse, visitor, isExpression), /*location*/ node.whenFalse);
markLabel(resultLabel);
return resultLocal;
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a `yield` expression.
*
* @param node The node to visit.
*/
function visitYieldExpression(node: YieldExpression): LeftHandSideExpression {
// [source]
// x = yield a();
//
// [intermediate]
// .yield resumeLabel, (a())
// .mark resumeLabel
// x = %sent%;
const resumeLabel = defineLabel();
const expression = visitNode(node.expression, visitor, isExpression);
if (node.asteriskToken) {
// NOTE: `expression` must be defined for `yield*`.
const iterator = (getEmitFlags(node.expression!) & EmitFlags.Iterator) === 0
? setTextRange(emitHelpers().createValuesHelper(expression!), node)
: expression;
emitYieldStar(iterator, /*location*/ node);
}
else {
emitYield(expression, /*location*/ node);
}
markLabel(resumeLabel);
return createGeneratorResume(/*location*/ node);
}
/**
* Visits an ArrayLiteralExpression that contains a YieldExpression.
*
* @param node The node to visit.
*/
function visitArrayLiteralExpression(node: ArrayLiteralExpression) {
return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
}
/**
* Visits an array of expressions containing one or more YieldExpression nodes
* and returns an expression for the resulting value.
*
* @param elements The elements to visit.
* @param multiLine Whether array literals created should be emitted on multiple lines.
*/
function visitElements(elements: NodeArray<Expression>, leadingElement?: Expression, location?: TextRange, multiLine?: boolean) {
// [source]
// ar = [1, yield, 2];
//
// [intermediate]
// .local _a
// _a = [1];
// .yield resumeLabel
// .mark resumeLabel
// ar = _a.concat([%sent%, 2]);
const numInitialElements = countInitialNodesWithoutYield(elements);
let temp: Identifier | undefined;
if (numInitialElements > 0) {
temp = declareLocal();
const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements);
emitAssignment(temp,
factory.createArrayLiteralExpression(
leadingElement
? [leadingElement, ...initialElements]
: initialElements
)
);
leadingElement = undefined;