-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Es6RewriteGenerators.java
1575 lines (1437 loc) · 55.9 KB
/
Es6RewriteGenerators.java
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
/*
* Copyright 2014 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.Es6ToEs3Util.createType;
import static com.google.javascript.jscomp.Es6ToEs3Util.makeIterator;
import static com.google.javascript.jscomp.Es6ToEs3Util.withType;
import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.rhino.FunctionTypeI;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.ObjectTypeI;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TypeI;
import com.google.javascript.rhino.TypeIRegistry;
import com.google.javascript.rhino.jstype.JSTypeNative;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Converts ES6 generator functions to valid ES3 code. This pass runs after all ES6 features
* except for yield and generators have been transpiled.
*
* @author mattloring@google.com (Matthew Loring)
*/
public final class Es6RewriteGenerators
extends NodeTraversal.AbstractPostOrderCallback implements HotSwapCompilerPass {
static final String GENERATOR_PRELOAD_FUNCTION_NAME = "$jscomp$generator$function$name";
// Name of the variable that holds the state at which the generator
// should resume execution after a call to yield or return.
// The beginning state is 0 and the end state is -1.
private static final String GENERATOR_STATE = "$jscomp$generator$state";
private static final String GENERATOR_DO_WHILE_INITIAL = "$jscomp$generator$first$do";
private static final String GENERATOR_YIELD_ALL_NAME = "$jscomp$generator$yield$all";
private static final String GENERATOR_YIELD_ALL_ENTRY = "$jscomp$generator$yield$entry";
private static final String GENERATOR_ARGUMENTS = "$jscomp$generator$arguments";
private static final String GENERATOR_THIS = "$jscomp$generator$this";
private static final String GENERATOR_ACTION_ARG = "$jscomp$generator$action$arg";
private static final double GENERATOR_ACTION_NEXT = 0;
private static final double GENERATOR_ACTION_THROW = 1;
private static final String GENERATOR_NEXT_ARG = "$jscomp$generator$next$arg";
private static final String GENERATOR_THROW_ARG = "$jscomp$generator$throw$arg";
private static final String GENERATOR_SWITCH_ENTERED = "$jscomp$generator$switch$entered";
private static final String GENERATOR_SWITCH_VAL = "$jscomp$generator$switch$val";
private static final String GENERATOR_FINALLY_JUMP = "$jscomp$generator$finally";
private static final String GENERATOR_ERROR = "$jscomp$generator$global$error";
private static final String GENERATOR_FOR_IN_ARRAY = "$jscomp$generator$forin$array";
private static final String GENERATOR_FOR_IN_VAR = "$jscomp$generator$forin$var";
private static final String GENERATOR_FOR_IN_ITER = "$jscomp$generator$forin$iter";
private static final String GENERATOR_LOOP_GUARD = "$jscomp$generator$loop$guard";
private final AbstractCompiler compiler;
// Maintains a stack of numbers which identify the cases which mark the end of loops. These
// are used to manage jump destinations for break and continue statements.
private final List<LoopContext> currentLoopContext;
private final List<ExceptionContext> currentExceptionContext;
private static int generatorCaseCount;
private Supplier<String> generatorCounter;
// Current case statement onto which translated statements from the
// body of a generator will be appended.
private Node enclosingBlock;
// Destination for vars defined in the body of a generator.
private Node hoistRoot;
// Body of the generator function currently being translated.
private Node originalGeneratorBody;
// Current statement being translated.
private Node currentStatement;
private boolean hasTranslatedTry;
// Whether we should preserve type information during transpilation.
private final boolean addTypes;
private final TypeIRegistry registry;
private final TypeI unknownType;
private final TypeI undefinedType;
private final TypeI stringType;
private final TypeI booleanType;
private final TypeI falseType;
private final TypeI trueType;
private final TypeI numberType;
public Es6RewriteGenerators(AbstractCompiler compiler) {
checkNotNull(compiler);
this.compiler = compiler;
this.currentLoopContext = new ArrayList<>();
this.currentExceptionContext = new ArrayList<>();
generatorCounter = compiler.getUniqueNameIdSupplier();
this.addTypes = MostRecentTypechecker.NTI.equals(compiler.getMostRecentTypechecker());
this.registry = compiler.getTypeIRegistry();
this.unknownType = createType(addTypes, registry, JSTypeNative.UNKNOWN_TYPE);
this.undefinedType = createType(addTypes, registry, JSTypeNative.VOID_TYPE);
this.stringType = createType(addTypes, registry, JSTypeNative.STRING_TYPE);
this.booleanType = createType(addTypes, registry, JSTypeNative.BOOLEAN_TYPE);
this.falseType = createType(addTypes, registry, JSTypeNative.FALSE_TYPE);
this.trueType = createType(addTypes, registry, JSTypeNative.TRUE_TYPE);
this.numberType = createType(addTypes, registry, JSTypeNative.NUMBER_TYPE);
}
@Override
public void process(Node externs, Node root) {
// Report change only if the generator function is preloaded. See #cleanUpGeneratorSkeleton.
boolean reportChange = getPreloadedGeneratorFunc(compiler.getJsRoot()) != null;
TranspilationPasses.processTranspile(compiler, root, new DecomposeYields(compiler), this);
cleanUpGeneratorSkeleton(reportChange);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, new DecomposeYields(compiler), this);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case FUNCTION:
if (n.isGeneratorFunction()) {
generatorCaseCount = 0;
visitGenerator(n, parent);
}
break;
case NAME:
Node enclosing = NodeUtil.getEnclosingFunction(n);
if (enclosing != null
&& enclosing.isGeneratorFunction()
&& n.matchesQualifiedName("arguments")) {
n.setString(GENERATOR_ARGUMENTS);
}
break;
case THIS:
enclosing = NodeUtil.getEnclosingFunction(n);
if (enclosing != null && enclosing.isGeneratorFunction()) {
n.replaceWith(withType(IR.name(GENERATOR_THIS), n.getTypeI()));
}
break;
case YIELD:
if (n.isYieldAll()) {
visitYieldAll(t, n, parent);
} else if (!parent.isExprResult()) {
visitYieldExpr(t, n, parent);
} else {
visitYieldThrows(t, parent, parent.getParent());
}
break;
default:
break;
}
}
private void visitYieldThrows(NodeTraversal t, Node n, Node parent) {
Node ifThrows =
IR.ifNode(
withBooleanType(
IR.eq(
withNumberType(IR.name(GENERATOR_ACTION_ARG)),
withNumberType(IR.number(GENERATOR_ACTION_THROW)))),
IR.block(IR.throwNode(withUnknownType(IR.name(GENERATOR_THROW_ARG)))));
parent.addChildAfter(ifThrows, n);
t.reportCodeChange();
}
/**
* Translates expressions using the new yield-for syntax.
*
* <p>Sample translation:
*
* <pre>
* var i = yield * gen();
* </pre>
*
* <p>Is rewritten to:
*
* <pre>
* var $jscomp$generator$yield$all = gen();
* var $jscomp$generator$yield$entry;
* while (!($jscomp$generator$yield$entry =
* $jscomp$generator$yield$all.next($jscomp$generator$next$arg)).done) {
* yield $jscomp$generator$yield$entry.value;
* }
* var i = $jscomp$generator$yield$entry.value;
* </pre>
*/
private void visitYieldAll(NodeTraversal t, Node n, Node parent) {
ObjectTypeI yieldAllType = null;
TypeI typeParam = unknownType;
if (addTypes) {
yieldAllType = n.getFirstChild().getTypeI().autobox().toMaybeObjectType();
typeParam = yieldAllType.getTemplateTypes().get(0);
}
TypeI iteratorType = createGenericType(JSTypeNative.ITERATOR_TYPE, typeParam);
TypeI iteratorNextType =
addTypes ? iteratorType.toMaybeObjectType().getPropertyType("next") : null;
TypeI iIterableResultType = createGenericType(JSTypeNative.I_ITERABLE_RESULT_TYPE, typeParam);
TypeI iIterableResultDoneType =
addTypes ? iIterableResultType.toMaybeObjectType().getPropertyType("done") : null;
TypeI iIterableResultValueType =
addTypes ? iIterableResultType.toMaybeObjectType().getPropertyType("value") : null;
Node enclosingStatement = NodeUtil.getEnclosingStatement(n);
Node iterator = makeIterator(compiler, n.removeFirstChild());
if (addTypes) {
TypeI jscompType = t.getScope().getVar("$jscomp").getNode().getTypeI();
TypeI makeIteratorType = jscompType.toMaybeObjectType().getPropertyType("makeIterator");
iterator.getFirstChild().setTypeI(makeIteratorType);
iterator.getFirstFirstChild().setTypeI(jscompType);
}
Node generator =
IR.var(
withType(IR.name(GENERATOR_YIELD_ALL_NAME), iteratorType),
withType(iterator, iteratorType));
Node entryDecl = IR.var(withType(IR.name(GENERATOR_YIELD_ALL_ENTRY), iIterableResultType));
Node assignIterResult =
withType(
IR.assign(
withType(IR.name(GENERATOR_YIELD_ALL_ENTRY), iIterableResultType),
withType(
IR.call(
withType(
IR.getprop(
withType(IR.name(GENERATOR_YIELD_ALL_NAME), iteratorType),
withStringType(IR.string("next"))),
iteratorNextType),
withUnknownType(IR.name(GENERATOR_NEXT_ARG))),
iIterableResultType)),
iIterableResultType);
Node loopCondition =
withBooleanType(
IR.not(
withType(
IR.getprop(assignIterResult, withStringType(IR.string("done"))),
iIterableResultDoneType)));
Node elemValue =
withType(
IR.getprop(
withType(IR.name(GENERATOR_YIELD_ALL_ENTRY), iIterableResultType),
withStringType(IR.string("value"))),
iIterableResultValueType);
Node yieldStatement = IR.exprResult(withUnknownType(IR.yield(elemValue.cloneTree())));
Node loop = IR.whileNode(loopCondition, IR.block(yieldStatement));
enclosingStatement.getParent().addChildBefore(generator, enclosingStatement);
enclosingStatement.getParent().addChildBefore(entryDecl, enclosingStatement);
enclosingStatement.getParent().addChildBefore(loop, enclosingStatement);
if (parent.isExprResult()) {
parent.detach();
} else {
parent.replaceChild(n, elemValue);
}
visitYieldThrows(t, yieldStatement, yieldStatement.getParent());
t.reportCodeChange();
}
private void visitYieldExpr(NodeTraversal t, Node n, Node parent) {
Node enclosingStatement = NodeUtil.getEnclosingStatement(n);
Node yieldStatement =
IR.exprResult(
n.hasChildren()
? withType(IR.yield(n.removeFirstChild()), n.getTypeI())
: withType(IR.yield(), n.getTypeI()));
Node yieldResult = withUnknownType(IR.name(GENERATOR_NEXT_ARG + generatorCounter.get()));
Node yieldResultDecl =
IR.var(yieldResult.cloneTree(), withUnknownType(IR.name(GENERATOR_NEXT_ARG)));
parent.replaceChild(n, yieldResult);
enclosingStatement.getParent().addChildBefore(yieldStatement, enclosingStatement);
enclosingStatement.getParent().addChildBefore(yieldResultDecl, enclosingStatement);
visitYieldThrows(t, yieldStatement, yieldStatement.getParent());
t.reportCodeChange();
}
private void visitGenerator(Node n, Node parent) {
Es6ToEs3Util.preloadEs6Symbol(compiler);
hasTranslatedTry = false;
Node genBlock = preloadGeneratorSkeleton(compiler, false).getLastChild().cloneTree();
generatorCaseCount++;
originalGeneratorBody = n.getLastChild();
n.replaceChild(originalGeneratorBody, genBlock);
NodeUtil.markNewScopesChanged(genBlock, compiler);
n.setIsGeneratorFunction(false);
TypeI generatorFuncType = n.getTypeI();
TypeI generatorReturnType =
addTypes ? generatorFuncType.toMaybeFunctionType().getReturnType() : null;
TypeI yieldType = unknownType;
if (addTypes) {
if (generatorReturnType.isGenericObjectType()) {
yieldType = generatorReturnType.autobox().toMaybeObjectType().getTemplateTypes().get(0);
}
addTypesToGeneratorSkeleton(genBlock, yieldType);
}
// TODO(mattloring): remove this suppression once we can optimize the switch statement to
// remove unused cases.
JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(n.getJSDocInfo());
// TODO(mattloring): copy existing suppressions.
builder.recordSuppressions(ImmutableSet.of("uselessCode"));
JSDocInfo info = builder.build();
n.setJSDocInfo(info);
// Set state to the default after the body of the function has completed.
originalGeneratorBody.addChildToBack(
IR.exprResult(
withNumberType(
IR.assign(
withNumberType(IR.name(GENERATOR_STATE)), withNumberType(IR.number(-1))))));
enclosingBlock = getUnique(genBlock, Token.CASE).getLastChild();
hoistRoot = genBlock.getFirstChild();
if (NodeUtil.isNameReferenced(originalGeneratorBody, GENERATOR_ARGUMENTS)) {
hoistRoot
.getParent()
.addChildAfter(
IR.var(
withUnknownType(IR.name(GENERATOR_ARGUMENTS)),
withUnknownType(IR.name("arguments"))),
hoistRoot);
}
if (NodeUtil.isNameReferenced(originalGeneratorBody, GENERATOR_THIS)) {
hoistRoot
.getParent()
.addChildAfter(
IR.var(withUnknownType(IR.name(GENERATOR_THIS)), withUnknownType(IR.thisNode())),
hoistRoot);
}
while (originalGeneratorBody.hasChildren()) {
currentStatement = originalGeneratorBody.removeFirstChild();
boolean advanceCase = translateStatementInOriginalBody();
if (advanceCase) {
int caseNumber;
if (currentStatement.isGeneratorMarker()) {
caseNumber = (int) currentStatement.getFirstChild().getDouble();
} else {
caseNumber = generatorCaseCount;
generatorCaseCount++;
}
Node oldCase = enclosingBlock.getParent();
Node newCase =
withBooleanType(IR.caseNode(withNumberType(IR.number(caseNumber)), IR.block()));
enclosingBlock = newCase.getLastChild();
if (oldCase.isTry()) {
oldCase = oldCase.getGrandparent();
if (!currentExceptionContext.isEmpty()) {
Node newTry =
IR.tryCatch(IR.block(), currentExceptionContext.get(0).catchBlock.cloneTree());
newCase.getLastChild().addChildToBack(newTry);
enclosingBlock = newCase.getLastChild().getLastChild().getFirstChild();
}
}
oldCase.getParent().addChildAfter(newCase, oldCase);
}
}
parent.useSourceInfoIfMissingFromForTree(parent);
compiler.reportChangeToEnclosingScope(genBlock);
}
/** Returns {@code true} if a new case node should be added */
private boolean translateStatementInOriginalBody() {
if (currentStatement.isVar()) {
visitVar();
return false;
} else if (currentStatement.isGeneratorMarker()) {
visitGeneratorMarker();
return true;
} else if (currentStatement.isFunction()) {
visitFunctionStatement();
return false;
} else if (currentStatement.isNormalBlock()) {
visitBlock();
return false;
} else if (controlCanExit(currentStatement)) {
switch (currentStatement.getToken()) {
case WHILE:
case DO:
case FOR:
visitLoop(null);
return false;
case FOR_IN:
visitForIn();
return false;
case LABEL:
visitLabel();
return false;
case SWITCH:
visitSwitch();
return false;
case IF:
if (!currentStatement.isGeneratorSafe()) {
visitIf();
return false;
}
break;
case TRY:
visitTry();
return false;
case EXPR_RESULT:
if (currentStatement.getFirstChild().isYield()) {
visitYieldExprResult();
return true;
}
break;
case RETURN:
visitReturn();
return false;
case CONTINUE:
visitContinue();
return false;
case BREAK:
if (!currentStatement.isGeneratorSafe()) {
visitBreak();
return false;
}
break;
case THROW:
visitThrow();
return false;
default:
// We never want to copy over an untranslated statement for which control exits.
throw new RuntimeException(
"Untranslatable control-exiting statement in generator function: "
+ currentStatement.getToken());
}
}
// In the default case, add the statement to the current case block unchanged.
enclosingBlock.addChildToBack(currentStatement);
return false;
}
private void visitFunctionStatement() {
hoistRoot.getParent().addChildAfter(currentStatement, hoistRoot);
}
private void visitTry() {
Node tryBody = currentStatement.getFirstChild();
Node caughtError;
Node catchBody;
Node catchBlock = tryBody.getNext();
if (catchBlock.hasChildren()) {
// There is a catch block
caughtError = catchBlock.getFirstChild().removeFirstChild();
catchBody = catchBlock.getFirstChild().removeFirstChild();
} else {
caughtError = withUnknownType(IR.name(GENERATOR_ERROR + "temp"));
catchBody = IR.block(IR.throwNode(caughtError.cloneTree()));
catchBody.getFirstChild().setGeneratorSafe(true);
}
Node finallyBody = catchBlock.getNext();
int catchStartState = generatorCaseCount++;
Node catchStart = makeGeneratorMarker(catchStartState);
Node errorNameGenerated =
withUnknownType(IR.name("$jscomp$generator$" + caughtError.getString()));
originalGeneratorBody.addChildToFront(catchStart);
originalGeneratorBody.addChildAfter(catchBody, catchStart);
Node assignError =
withUnknownType(
IR.assign(withUnknownType(IR.name(GENERATOR_ERROR)), errorNameGenerated.cloneTree()));
Node newCatchBody =
IR.block(IR.exprResult(assignError), createStateUpdate(catchStartState), createSafeBreak());
Node newCatch = IR.catchNode(errorNameGenerated, newCatchBody);
currentExceptionContext.add(0, new ExceptionContext(catchStartState, newCatch));
if (finallyBody != null) {
Node finallyName = withNumberType(IR.name(GENERATOR_FINALLY_JUMP + generatorCounter.get()));
int finallyStartState = generatorCaseCount++;
Node finallyStart = makeGeneratorMarker(finallyStartState);
int finallyEndState = generatorCaseCount++;
Node finallyEnd = makeGeneratorMarker(finallyEndState);
NodeTraversal.traverseEs6(
compiler, tryBody, new ControlExitsCheck(finallyName, finallyStartState));
NodeTraversal.traverseEs6(
compiler, catchBody, new ControlExitsCheck(finallyName, finallyStartState));
originalGeneratorBody.addChildToFront(tryBody.detach());
originalGeneratorBody.addChildAfter(finallyStart, catchBody);
originalGeneratorBody.addChildAfter(finallyBody.detach(), finallyStart);
originalGeneratorBody.addChildAfter(finallyEnd, finallyBody);
originalGeneratorBody.addChildToFront(IR.var(finallyName.cloneTree()));
finallyBody.addChildToBack(
IR.exprResult(
withNumberType(
IR.assign(withNumberType(IR.name(GENERATOR_STATE)), finallyName.cloneTree()))));
finallyBody.addChildToBack(createSafeBreak());
tryBody.addChildToBack(
IR.exprResult(
withNumberType(
IR.assign(finallyName.cloneTree(), withNumberType(IR.number(finallyEndState))))));
tryBody.addChildToBack(createStateUpdate(finallyStartState));
tryBody.addChildToBack(createSafeBreak());
catchBody.addChildToBack(
IR.exprResult(
withNumberType(
IR.assign(finallyName.cloneTree(), withNumberType(IR.number(finallyEndState))))));
} else {
int catchEndState = generatorCaseCount++;
Node catchEnd = makeGeneratorMarker(catchEndState);
originalGeneratorBody.addChildAfter(catchEnd, catchBody);
tryBody.addChildToBack(createStateUpdate(catchEndState));
tryBody.addChildToBack(createSafeBreak());
originalGeneratorBody.addChildToFront(tryBody.detach());
}
catchBody.addChildToFront(IR.var(caughtError, withUnknownType(IR.name(GENERATOR_ERROR))));
if (enclosingBlock.getParent().isTry()) {
enclosingBlock = enclosingBlock.getGrandparent();
}
enclosingBlock.addChildToBack(IR.tryCatch(IR.block(), newCatch));
enclosingBlock = enclosingBlock.getLastChild().getFirstChild();
if (!hasTranslatedTry) {
hasTranslatedTry = true;
hoistRoot
.getParent()
.addChildAfter(IR.var(withUnknownType(IR.name(GENERATOR_ERROR))), hoistRoot);
}
}
private void visitContinue() {
checkState(currentLoopContext.get(0).continueCase != -1);
int continueCase;
if (currentStatement.hasChildren()) {
continueCase = getLoopContext(currentStatement.removeFirstChild().getString()).continueCase;
} else {
continueCase = currentLoopContext.get(0).continueCase;
}
enclosingBlock.addChildToBack(createStateUpdate(continueCase));
enclosingBlock.addChildToBack(createSafeBreak());
}
private void visitThrow() {
enclosingBlock.addChildToBack(createStateUpdate(-1));
enclosingBlock.addChildToBack(currentStatement);
}
private void visitBreak() {
int breakCase;
if (currentStatement.hasChildren()) {
LoopContext loop = getLoopContext(currentStatement.removeFirstChild().getString());
if (loop == null) {
compiler.report(
JSError.make(
currentStatement,
Es6ToEs3Util.CANNOT_CONVERT_YET,
"Breaking to a label that is not a loop"));
return;
}
breakCase = loop.breakCase;
} else {
breakCase = currentLoopContext.get(0).breakCase;
}
enclosingBlock.addChildToBack(createStateUpdate(breakCase));
enclosingBlock.addChildToBack(createSafeBreak());
}
private void visitLabel() {
Node labelName = currentStatement.removeFirstChild();
Node child = currentStatement.removeFirstChild();
if (NodeUtil.isLoopStructure(child)) {
currentStatement = child;
visitLoop(labelName.getString());
} else {
originalGeneratorBody.addChildToFront(child);
}
}
/**
* Pops the loop information off of our stack if we reach the marker cooresponding
* to the end of the current loop.
*/
private void visitGeneratorMarker() {
if (!currentLoopContext.isEmpty()
&& currentLoopContext.get(0).breakCase == currentStatement.getFirstChild().getDouble()) {
currentLoopContext.remove(0);
}
if (!currentExceptionContext.isEmpty()
&& currentExceptionContext.get(0).catchStartCase
== currentStatement.getFirstChild().getDouble()) {
currentExceptionContext.remove(0);
}
}
/**
* Uses a case statement to jump over the body if the condition of the
* if statement is false. Additionally, lift the body of the {@code if}
* statement to the top level.
*/
private void visitIf() {
Node condition = currentStatement.removeFirstChild();
Node ifBody = currentStatement.removeFirstChild();
boolean hasElse = currentStatement.hasChildren();
int ifEndState = generatorCaseCount++;
Node invertedConditional =
IR.ifNode(
withBooleanType(IR.not(condition)),
IR.block(createStateUpdate(ifEndState), createSafeBreak()));
invertedConditional.setGeneratorSafe(true);
Node endIf = makeGeneratorMarker(ifEndState);
originalGeneratorBody.addChildToFront(invertedConditional);
originalGeneratorBody.addChildAfter(ifBody, invertedConditional);
originalGeneratorBody.addChildAfter(endIf, ifBody);
if (hasElse) {
Node elseBlock = currentStatement.removeFirstChild();
int elseEndState = generatorCaseCount++;
Node endElse = makeGeneratorMarker(elseEndState);
ifBody.addChildToBack(createStateUpdate(elseEndState));
ifBody.addChildToBack(createSafeBreak());
originalGeneratorBody.addChildAfter(elseBlock, endIf);
originalGeneratorBody.addChildAfter(endElse, elseBlock);
}
}
/**
* Translates switch statements into a series of if statements.
*
* <p>Sample translation:
* <pre>
* switch (i) {
* case 1:
* s;
* case 2:
* t;
* ...
* }
* </pre>
*
* <p>Is eventually rewritten to:
*
* <pre>
* $jscomp$generator$switch$entered0 = false;
* if ($jscomp$generator$switch$entered0 || i == 1) {
* $jscomp$generator$switch$entered0 = true;
* s;
* }
* if ($jscomp$generator$switch$entered0 || i == 2) {
* $jscomp$generator$switch$entered0 = true;
* t;
* }
* ...
*
* </pre>
*/
private void visitSwitch() {
Node didEnter = withBooleanType(IR.name(GENERATOR_SWITCH_ENTERED + generatorCounter.get()));
Node didEnterDecl = IR.var(didEnter.cloneTree(), withFalseType(IR.falseNode()));
Node switchVal =
withType(
IR.name(GENERATOR_SWITCH_VAL + generatorCounter.get()),
currentStatement.getFirstChild().getTypeI());
Node switchValDecl = IR.var(switchVal.cloneTree(), currentStatement.removeFirstChild());
originalGeneratorBody.addChildToFront(didEnterDecl);
originalGeneratorBody.addChildAfter(switchValDecl, didEnterDecl);
Node insertionPoint = switchValDecl;
while (currentStatement.hasChildren()) {
Node currCase = currentStatement.removeFirstChild();
Node equivBlock;
currCase
.getLastChild()
.addChildToFront(
IR.exprResult(
withBooleanType(IR.assign(didEnter.cloneTree(), withTrueType(IR.trueNode())))));
if (currCase.isDefaultCase()) {
if (currentStatement.hasChildren()) {
compiler.report(
JSError.make(
currentStatement,
Es6ToEs3Util.CANNOT_CONVERT_YET,
"Default case as intermediate case"));
}
equivBlock = IR.block(currCase.removeFirstChild());
} else {
equivBlock =
IR.ifNode(
withBooleanType(
IR.or(
didEnter.cloneTree(),
withBooleanType(
IR.sheq(switchVal.cloneTree(), currCase.removeFirstChild())))),
currCase.removeFirstChild());
}
originalGeneratorBody.addChildAfter(equivBlock, insertionPoint);
insertionPoint = equivBlock;
}
int breakTarget = generatorCaseCount++;
int cont = currentLoopContext.isEmpty() ? -1 : currentLoopContext.get(0).continueCase;
currentLoopContext.add(0, new LoopContext(breakTarget, cont, null));
Node breakCase = makeGeneratorMarker(breakTarget);
originalGeneratorBody.addChildAfter(breakCase, insertionPoint);
}
/**
* Lifts all children to the body of the original generator to flatten the block.
*/
private void visitBlock() {
if (!currentStatement.hasChildren()) {
return;
}
Node insertionPoint = currentStatement.removeFirstChild();
originalGeneratorBody.addChildToFront(insertionPoint);
for (Node child = currentStatement.removeFirstChild();
child != null;
child = currentStatement.removeFirstChild()) {
originalGeneratorBody.addChildAfter(child, insertionPoint);
insertionPoint = child;
}
}
/**
* Translates for in loops to a for in loop which produces an array of
* values iterated over followed by a plain for loop which performs the logic
* contained in the body of the original for in.
*
* <p>Sample translation:
* <pre>
* for (i in j) {
* s;
* }
* </pre>
*
* <p>Is eventually rewritten to:
*
* <pre>
* $jscomp$arr = [];
* $jscomp$iter = j;
* for (i in $jscomp$iter) {
* $jscomp$arr.push(i);
* }
* for ($jscomp$var = 0; $jscomp$var < $jscomp$arr.length; $jscomp$var++) {
* i = $jscomp$arr[$jscomp$var];
* if (!(i in $jscomp$iter)) {
* continue;
* }
* s;
* }
* </pre>
*/
private void visitForIn() {
Node variable = currentStatement.removeFirstChild();
Node iterable = currentStatement.removeFirstChild();
Node body = currentStatement.removeFirstChild();
TypeI iterableType = iterable.getTypeI();
TypeI typeParam = unknownType;
if (addTypes) {
typeParam = iterableType.autobox().toMaybeObjectType().getTemplateTypes().get(0);
}
TypeI arrayType = createGenericType(JSTypeNative.ARRAY_TYPE, typeParam);
String loopId = generatorCounter.get();
Node arrayName = withType(IR.name(GENERATOR_FOR_IN_ARRAY + loopId), arrayType);
Node varName = withNumberType(IR.name(GENERATOR_FOR_IN_VAR + loopId));
Node iterableName = withType(IR.name(GENERATOR_FOR_IN_ITER + loopId), iterableType);
if (variable.isVar()) {
variable = variable.removeFirstChild();
}
body.addChildToFront(
IR.ifNode(
withBooleanType(IR.not(IR.in(variable.cloneTree(), iterableName.cloneTree()))),
IR.block(IR.continueNode())));
body.addChildToFront(
IR.var(variable.cloneTree(), IR.getelem(arrayName.cloneTree(), varName.cloneTree())));
hoistRoot.getParent().addChildAfter(IR.var(arrayName.cloneTree()), hoistRoot);
hoistRoot.getParent().addChildAfter(IR.var(varName.cloneTree()), hoistRoot);
hoistRoot.getParent().addChildAfter(IR.var(iterableName.cloneTree()), hoistRoot);
Node arrayDef =
IR.exprResult(
withType(
IR.assign(arrayName.cloneTree(), withType(IR.arraylit(), arrayType)), arrayType));
Node iterDef =
IR.exprResult(withType(IR.assign(iterableName.cloneTree(), iterable), iterableType));
Node newForIn =
IR.forIn(
variable.cloneTree(),
iterableName,
IR.block(
IR.exprResult(
withNumberType(
IR.call(IR.getprop(arrayName.cloneTree(), IR.string("push")), variable)))));
Node newFor =
IR.forNode(
withNumberType(IR.assign(varName.cloneTree(), withNumberType(IR.number(0)))),
withBooleanType(
IR.lt(
varName.cloneTree(),
withNumberType(IR.getprop(arrayName, IR.string("length"))))),
withNumberType(IR.inc(varName, true)),
body);
enclosingBlock.addChildToBack(arrayDef);
enclosingBlock.addChildToBack(iterDef);
enclosingBlock.addChildToBack(newForIn);
originalGeneratorBody.addChildToFront(newFor);
}
/**
* Translates loops to a case statement followed by an if statement
* containing the loop body. The if statement finishes by
* jumping back to the initial case statement to enter the loop again.
* In the case of for and do loops, initialization and post loop statements are inserted
* before and after the if statement. Below is a sample translation for a while loop:
*
* <p>Sample translation:
* <pre>
* while (b) {
* s;
* }
* </pre>
*
* <p>Is eventually rewritten to:
* <pre>
* case n:
* if (b) {
* s;
* state = n;
* break;
* }
* </pre>
*/
private void visitLoop(String label) {
Node initializer;
Node guard;
Node incr;
Node body;
if (currentStatement.isWhile()) {
guard = currentStatement.removeFirstChild();
body = currentStatement.removeFirstChild();
initializer = IR.empty();
incr = IR.empty();
} else if (currentStatement.isVanillaFor()) {
initializer = currentStatement.removeFirstChild();
if (initializer.isAssign()) {
initializer = IR.exprResult(initializer);
}
guard = currentStatement.removeFirstChild();
incr = currentStatement.removeFirstChild();
body = currentStatement.removeFirstChild();
} else {
checkState(currentStatement.isDo());
initializer = IR.empty();
incr =
withBooleanType(
IR.assign(
withBooleanType(IR.name(GENERATOR_DO_WHILE_INITIAL)),
withFalseType(IR.falseNode())));
body = currentStatement.removeFirstChild();
guard = currentStatement.removeFirstChild();
}
Node condition;
Node prestatement;
if (guard.isNormalBlock()) {
prestatement = guard.removeFirstChild();
condition = guard.removeFirstChild();
} else {
prestatement = IR.block();
condition = guard;
}
int loopBeginState = generatorCaseCount++;
int continueState = loopBeginState;
if (!incr.isEmpty()) {
continueState = generatorCaseCount++;
Node continueCase = makeGeneratorMarker(continueState);
body.addChildToBack(continueCase);
body.addChildToBack(incr.isNormalBlock() ? incr : IR.exprResult(incr));
}
currentLoopContext.add(0, new LoopContext(generatorCaseCount, continueState, label));
Node beginCase = makeGeneratorMarker(loopBeginState);
Node conditionalBranch =
IR.ifNode(condition.isEmpty() ? withTrueType(IR.trueNode()) : condition, body);
Node setStateLoopStart = createStateUpdate(loopBeginState);
Node breakToStart = createSafeBreak();
originalGeneratorBody.addChildToFront(conditionalBranch);
if (!prestatement.isEmpty()) {
originalGeneratorBody.addChildToFront(prestatement);
}
originalGeneratorBody.addChildToFront(beginCase);
if (!initializer.isEmpty()) {
originalGeneratorBody.addChildToFront(initializer);
}
body.addChildToBack(setStateLoopStart);
body.addChildToBack(breakToStart);
}
/**
* Hoists {@code var} statements into the closure containing the iterator
* to preserve their state across
* multiple calls to next().
*/
private void visitVar() {
Node name = currentStatement.removeFirstChild();
while (name != null) {
if (name.hasChildren()) {
enclosingBlock.addChildToBack(
IR.exprResult(withType(IR.assign(name, name.removeFirstChild()), name.getTypeI())));
}
hoistRoot.getParent().addChildAfter(IR.var(name.cloneTree()), hoistRoot);
// name now refers to "generated" assignment which is not visible to end user. Don't index it.
name.makeNonIndexable();
name = currentStatement.removeFirstChild();
}
}
/**
* Translates {@code yield} to set the state so that execution resume at the next statement
* when the function is next called and then returns an iterator result with
* the desired value.
*/
private void visitYieldExprResult() {
enclosingBlock.addChildToBack(createStateUpdate());
Node yield = currentStatement.getFirstChild();
Node value =
yield.hasChildren() ? yield.removeFirstChild() : withUndefinedType(IR.name("undefined"));
enclosingBlock.addChildToBack(IR.returnNode(createIteratorResult(value, false)));
}
/**
* Translates {@code return} statements to set the state to done before returning the
* desired value.
*/
private void visitReturn() {
enclosingBlock.addChildToBack(createStateUpdate(-1));
enclosingBlock.addChildToBack(
IR.returnNode(
createIteratorResult(
currentStatement.hasChildren()
? currentStatement.removeFirstChild()
: withUndefinedType(IR.name("undefined")),
true)));
}
private Node createStateUpdate() {
return IR.exprResult(
withNumberType(
IR.assign(
withNumberType(IR.name(GENERATOR_STATE)),