/
es2015.ts
4373 lines (3899 loc) · 206 KB
/
es2015.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*@internal*/
namespace ts {
const enum ES2015SubstitutionFlags {
/** Enables substitutions for captured `this` */
CapturedThis = 1 << 0,
/** Enables substitutions for block-scoped bindings. */
BlockScopedBindings = 1 << 1,
}
/**
* If loop contains block scoped binding captured in some function then loop body is converted to a function.
* Lexical bindings declared in loop initializer will be passed into the loop body function as parameters,
* however if this binding is modified inside the body - this new value should be propagated back to the original binding.
* This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body.
* On every iteration this variable is initialized with value of corresponding binding.
* At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body)
* we copy the value inside the loop to the out parameter holder.
*
* for (let x;;) {
* let a = 1;
* let b = () => a;
* x++
* if (...) break;
* ...
* }
*
* will be converted to
*
* var out_x;
* var loop = function(x) {
* var a = 1;
* var b = function() { return a; }
* x++;
* if (...) return out_x = x, "break";
* ...
* out_x = x;
* }
* for (var x;;) {
* out_x = x;
* var state = loop(x);
* x = out_x;
* if (state === "break") break;
* }
*
* NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function
* so nobody can observe this new value.
*/
interface LoopOutParameter {
flags: LoopOutParameterFlags;
originalName: Identifier;
outParamName: Identifier;
}
const enum LoopOutParameterFlags {
Body = 1 << 0, // Modified in the body of the iteration statement
Initializer = 1 << 1, // Set in the initializer of a ForStatement
}
const enum CopyDirection {
ToOriginal,
ToOutParameter
}
const enum Jump {
Break = 1 << 1,
Continue = 1 << 2,
Return = 1 << 3
}
interface ConvertedLoopState {
/*
* set of labels that occurred inside the converted loop
* used to determine if labeled jump can be emitted as is or it should be dispatched to calling code
*/
labels?: Map<boolean>;
/*
* collection of labeled jumps that transfer control outside the converted loop.
* maps store association 'label -> labelMarker' where
* - label - value of label as it appear in code
* - label marker - return value that should be interpreted by calling code as 'jump to <label>'
*/
labeledNonLocalBreaks?: Map<string>;
labeledNonLocalContinues?: Map<string>;
/*
* set of non-labeled jumps that transfer control outside the converted loop
* used to emit dispatching logic in the caller of converted loop
*/
nonLocalJumps?: Jump;
/*
* set of non-labeled jumps that should be interpreted as local
* i.e. if converted loop contains normal loop or switch statement then inside this loop break should be treated as local jump
*/
allowedNonLabeledJumps?: Jump;
/*
* alias for 'arguments' object from the calling code stack frame
* i.e.
* for (let x;;) <statement that captures x in closure and uses 'arguments'>
* should be converted to
* var loop = function(x) { <code where 'arguments' is replaced with 'arguments_1'> }
* var arguments_1 = arguments
* for (var x;;) loop(x);
* otherwise semantics of the code will be different since 'arguments' inside converted loop body
* will refer to function that holds converted loop.
* This value is set on demand.
*/
argumentsName?: Identifier;
/*
* alias for 'this' from the calling code stack frame in case if this was used inside the converted loop
*/
thisName?: Identifier;
/*
* set to true if node contains lexical 'this' so we can mark function that wraps convered loop body as 'CapturedThis' for subsequent substitution.
*/
containsLexicalThis?: boolean;
/*
* list of non-block scoped variable declarations that appear inside converted loop
* such variable declarations should be moved outside the loop body
* for (let x;;) {
* var y = 1;
* ...
* }
* should be converted to
* var loop = function(x) {
* y = 1;
* ...
* }
* var y;
* for (var x;;) loop(x);
*/
hoistedLocalVariables?: Identifier[];
conditionVariable?: Identifier;
loopParameters: ParameterDeclaration[];
/**
* List of loop out parameters - detailed descripion can be found in the comment to LoopOutParameter
*/
loopOutParameters: LoopOutParameter[];
}
type LoopConverter = (node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convertedLoopBodyStatements: Statement[] | undefined) => Statement;
// Facts we track as we traverse the tree
const enum HierarchyFacts {
None = 0,
//
// Ancestor facts
//
Function = 1 << 0, // Enclosed in a non-arrow function
ArrowFunction = 1 << 1, // Enclosed in an arrow function
AsyncFunctionBody = 1 << 2, // Enclosed in an async function body
NonStaticClassElement = 1 << 3, // Enclosed in a non-static, non-async class element
CapturesThis = 1 << 4, // Enclosed in a function that captures the lexical 'this' (used in substitution)
ExportedVariableStatement = 1 << 5, // Enclosed in an exported variable statement in the current scope
TopLevel = 1 << 6, // Enclosing block-scoped container is a top-level container
Block = 1 << 7, // Enclosing block-scoped container is a Block
IterationStatement = 1 << 8, // Enclosed in an IterationStatement
IterationStatementBlock = 1 << 9, // Enclosing Block is enclosed in an IterationStatement
ForStatement = 1 << 10, // Enclosing block-scoped container is a ForStatement
ForInOrForOfStatement = 1 << 11, // Enclosing block-scoped container is a ForInStatement or ForOfStatement
ConstructorWithCapturedSuper = 1 << 12, // Enclosed in a constructor that captures 'this' for use with 'super'
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
// NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
AncestorFactsMask = (ConstructorWithCapturedSuper << 1) - 1,
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
BlockScopeIncludes = None,
BlockScopeExcludes = TopLevel | Block | IterationStatement | IterationStatementBlock | ForStatement | ForInOrForOfStatement,
// A source file is a top-level block scope.
SourceFileIncludes = TopLevel,
SourceFileExcludes = BlockScopeExcludes & ~TopLevel,
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
FunctionIncludes = Function | TopLevel,
FunctionExcludes = BlockScopeExcludes & ~TopLevel | ArrowFunction | AsyncFunctionBody | CapturesThis | NonStaticClassElement | ConstructorWithCapturedSuper,
AsyncFunctionBodyIncludes = FunctionIncludes | AsyncFunctionBody,
AsyncFunctionBodyExcludes = FunctionExcludes & ~NonStaticClassElement,
// Arrow functions are lexically scoped to their container, but are new block scopes.
ArrowFunctionIncludes = ArrowFunction | TopLevel,
ArrowFunctionExcludes = BlockScopeExcludes & ~TopLevel | ConstructorWithCapturedSuper,
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
ConstructorIncludes = FunctionIncludes | NonStaticClassElement,
ConstructorExcludes = FunctionExcludes & ~NonStaticClassElement,
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
DoOrWhileStatementIncludes = IterationStatement,
DoOrWhileStatementExcludes = None,
// 'for' statements are new block scopes and have special handling for 'let' declarations.
ForStatementIncludes = IterationStatement | ForStatement,
ForStatementExcludes = BlockScopeExcludes & ~ForStatement,
// 'for-in' and 'for-of' statements are new block scopes and have special handling for
// 'let' declarations.
ForInOrForOfStatementIncludes = IterationStatement | ForInOrForOfStatement,
ForInOrForOfStatementExcludes = BlockScopeExcludes & ~ForInOrForOfStatement,
// Blocks (other than function bodies) are new block scopes.
BlockIncludes = Block,
BlockExcludes = BlockScopeExcludes & ~Block,
IterationStatementBlockIncludes = IterationStatementBlock,
IterationStatementBlockExcludes = BlockScopeExcludes,
//
// Subtree facts
//
NewTarget = 1 << 13, // Contains a 'new.target' meta-property
CapturedLexicalThis = 1 << 14, // Contains a lexical `this` reference captured by an arrow function.
//
// Subtree masks
//
SubtreeFactsMask = ~AncestorFactsMask,
ArrowFunctionSubtreeExcludes = None,
FunctionSubtreeExcludes = NewTarget | CapturedLexicalThis,
}
export function transformES2015(context: TransformationContext) {
const {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
let currentSourceFile: SourceFile;
let currentText: string;
let hierarchyFacts: HierarchyFacts;
let taggedTemplateStringDeclarations: VariableDeclaration[];
function recordTaggedTemplateString(temp: Identifier) {
taggedTemplateStringDeclarations = append(
taggedTemplateStringDeclarations,
createVariableDeclaration(temp));
}
/**
* Used to track if we are emitting body of the converted loop
*/
let convertedLoopState: ConvertedLoopState | undefined;
/**
* Keeps track of whether substitutions have been enabled for specific cases.
* They are persisted between each SourceFile transformation and should not
* be reset.
*/
let enabledSubstitutions: ES2015SubstitutionFlags;
return chainBundle(transformSourceFile);
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
currentSourceFile = node;
currentText = node.text;
const visited = visitSourceFile(node);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined!;
currentText = undefined!;
taggedTemplateStringDeclarations = undefined!;
hierarchyFacts = HierarchyFacts.None;
return visited;
}
/**
* 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, propagating specific facts from the subtree.
* @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
* @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts: HierarchyFacts, excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & HierarchyFacts.SubtreeFactsMask | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean {
return (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper) !== 0
&& node.kind === SyntaxKind.ReturnStatement
&& !(<ReturnStatement>node).expression;
}
function shouldVisitNode(node: Node): boolean {
return (node.transformFlags & TransformFlags.ContainsES2015) !== 0
|| convertedLoopState !== undefined
|| (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper && (isStatement(node) || (node.kind === SyntaxKind.Block)))
|| (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
|| (getEmitFlags(node) & EmitFlags.TypeScriptClassWrapper) !== 0;
}
function visitor(node: Node): VisitResult<Node> {
if (shouldVisitNode(node)) {
return visitJavaScript(node);
}
else {
return node;
}
}
function callExpressionVisitor(node: Node): VisitResult<Node> {
if (node.kind === SyntaxKind.SuperKeyword) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
}
return visitor(node);
}
function visitJavaScript(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.StaticKeyword:
return undefined; // elide static keyword
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ClassExpression:
return visitClassExpression(<ClassExpression>node);
case SyntaxKind.Parameter:
return visitParameter(<ParameterDeclaration>node);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.ArrowFunction:
return visitArrowFunction(<ArrowFunction>node);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
case SyntaxKind.Identifier:
return visitIdentifier(<Identifier>node);
case SyntaxKind.VariableDeclarationList:
return visitVariableDeclarationList(<VariableDeclarationList>node);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
case SyntaxKind.CaseBlock:
return visitCaseBlock(<CaseBlock>node);
case SyntaxKind.Block:
return visitBlock(<Block>node, /*isFunctionBody*/ false);
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
return visitBreakOrContinueStatement(<BreakOrContinueStatement>node);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
return visitDoOrWhileStatement(<DoStatement | WhileStatement>node, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(<ExpressionStatement>node);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
case SyntaxKind.ShorthandPropertyAssignment:
return visitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(<ComputedPropertyName>node);
case SyntaxKind.ArrayLiteralExpression:
return visitArrayLiteralExpression(<ArrayLiteralExpression>node);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(<ParenthesizedExpression>node, /*needsDestructuringValue*/ true);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node, /*needsDestructuringValue*/ true);
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
case SyntaxKind.TemplateTail:
return visitTemplateLiteral(<LiteralExpression>node);
case SyntaxKind.StringLiteral:
return visitStringLiteral(<StringLiteral>node);
case SyntaxKind.NumericLiteral:
return visitNumericLiteral(<NumericLiteral>node);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.TemplateExpression:
return visitTemplateExpression(<TemplateExpression>node);
case SyntaxKind.YieldExpression:
return visitYieldExpression(<YieldExpression>node);
case SyntaxKind.SpreadElement:
return visitSpreadElement(<SpreadElement>node);
case SyntaxKind.SuperKeyword:
return visitSuperKeyword(/*isExpressionOfCall*/ false);
case SyntaxKind.ThisKeyword:
return visitThisKeyword(node);
case SyntaxKind.MetaProperty:
return visitMetaProperty(<MetaProperty>node);
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return visitAccessorDeclaration(<AccessorDeclaration>node);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.ReturnStatement:
return visitReturnStatement(<ReturnStatement>node);
default:
return visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node: SourceFile): SourceFile {
const ancestorFacts = enterSubtree(HierarchyFacts.SourceFileExcludes, HierarchyFacts.SourceFileIncludes);
const prologue: Statement[] = [];
const statements: Statement[] = [];
startLexicalEnvironment();
let statementOffset = addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
statementOffset = addCustomPrologue(prologue, node.statements, statementOffset, visitor);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(
createVariableStatement(/*modifiers*/ undefined,
createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
mergeLexicalEnvironment(prologue, endLexicalEnvironment());
insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None);
return updateSourceFileNode(
node,
setTextRange(createNodeArray(concatenate(prologue, statements)), node.statements)
);
}
function visitSwitchStatement(node: SwitchStatement): SwitchStatement {
if (convertedLoopState !== undefined) {
const savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
// for switch statement allow only non-labeled break
convertedLoopState.allowedNonLabeledJumps! |= Jump.Break;
const result = visitEachChild(node, visitor, context);
convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
return result;
}
return visitEachChild(node, visitor, context);
}
function visitCaseBlock(node: CaseBlock): CaseBlock {
const ancestorFacts = enterSubtree(HierarchyFacts.BlockScopeExcludes, HierarchyFacts.BlockScopeIncludes);
const updated = visitEachChild(node, visitor, context);
exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None);
return updated;
}
function returnCapturedThis(node: Node): ReturnStatement {
return setOriginalNode(createReturn(createFileLevelUniqueName("_this")), node);
}
function visitReturnStatement(node: ReturnStatement): Statement {
if (convertedLoopState) {
convertedLoopState.nonLocalJumps! |= Jump.Return;
if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
node = returnCapturedThis(node);
}
return createReturn(
createObjectLiteral(
[
createPropertyAssignment(
createIdentifier("value"),
node.expression
? visitNode(node.expression, visitor, isExpression)
: createVoidZero()
)
]
)
);
}
else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
return returnCapturedThis(node);
}
return visitEachChild(node, visitor, context);
}
function visitThisKeyword(node: Node): Node {
if (hierarchyFacts & HierarchyFacts.ArrowFunction) {
hierarchyFacts |= HierarchyFacts.CapturedLexicalThis;
}
if (convertedLoopState) {
if (hierarchyFacts & HierarchyFacts.ArrowFunction) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
convertedLoopState.containsLexicalThis = true;
return node;
}
return convertedLoopState.thisName || (convertedLoopState.thisName = createUniqueName("this"));
}
return node;
}
function visitIdentifier(node: Identifier): Identifier {
if (!convertedLoopState) {
return node;
}
if (isGeneratedIdentifier(node)) {
return node;
}
if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
return node;
}
return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = createUniqueName("arguments"));
}
function visitBreakOrContinueStatement(node: BreakOrContinueStatement): Statement {
if (convertedLoopState) {
// check if we can emit break/continue as is
// it is possible if either
// - break/continue is labeled and label is located inside the converted loop
// - break/continue is non-labeled and located in non-converted loop/switch statement
const jump = node.kind === SyntaxKind.BreakStatement ? Jump.Break : Jump.Continue;
const canUseBreakOrContinue =
(node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label))) ||
(!node.label && (convertedLoopState.allowedNonLabeledJumps! & jump));
if (!canUseBreakOrContinue) {
let labelMarker: string;
const label = node.label;
if (!label) {
if (node.kind === SyntaxKind.BreakStatement) {
convertedLoopState.nonLocalJumps! |= Jump.Break;
labelMarker = "break";
}
else {
convertedLoopState.nonLocalJumps! |= Jump.Continue;
// note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
labelMarker = "continue";
}
}
else {
if (node.kind === SyntaxKind.BreakStatement) {
labelMarker = `break-${label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ true, idText(label), labelMarker);
}
else {
labelMarker = `continue-${label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ false, idText(label), labelMarker);
}
}
let returnExpression: Expression = createLiteral(labelMarker);
if (convertedLoopState.loopOutParameters.length) {
const outParams = convertedLoopState.loopOutParameters;
let expr: Expression | undefined;
for (let i = 0; i < outParams.length; i++) {
const copyExpr = copyOutParameter(outParams[i], CopyDirection.ToOutParameter);
if (i === 0) {
expr = copyExpr;
}
else {
expr = createBinary(expr!, SyntaxKind.CommaToken, copyExpr);
}
}
returnExpression = createBinary(expr!, SyntaxKind.CommaToken, returnExpression);
}
return createReturn(returnExpression);
}
}
return visitEachChild(node, visitor, context);
}
/**
* Visits a ClassDeclaration and transforms it into a variable statement.
*
* @param node A ClassDeclaration node.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
// [source]
// class C { }
//
// [output]
// var C = (function () {
// function C() {
// }
// return C;
// }());
const variable = createVariableDeclaration(
getLocalName(node, /*allowComments*/ true),
/*type*/ undefined,
transformClassLikeDeclarationToExpression(node)
);
setOriginalNode(variable, node);
const statements: Statement[] = [];
const statement = createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList([variable]));
setOriginalNode(statement, node);
setTextRange(statement, node);
startOnNewLine(statement);
statements.push(statement);
// Add an `export default` statement for default exports (for `--target es5 --module es6`)
if (hasModifier(node, ModifierFlags.Export)) {
const exportStatement = hasModifier(node, ModifierFlags.Default)
? createExportDefault(getLocalName(node))
: createExternalModuleExport(getLocalName(node));
setOriginalNode(exportStatement, statement);
statements.push(exportStatement);
}
const emitFlags = getEmitFlags(node);
if ((emitFlags & EmitFlags.HasEndOfDeclarationMarker) === 0) {
// Add a DeclarationMarker as a marker for the end of the declaration
statements.push(createEndOfDeclarationMarker(node));
setEmitFlags(statement, emitFlags | EmitFlags.HasEndOfDeclarationMarker);
}
return singleOrMany(statements);
}
/**
* Visits a ClassExpression and transforms it into an expression.
*
* @param node A ClassExpression node.
*/
function visitClassExpression(node: ClassExpression): Expression {
// [source]
// C = class { }
//
// [output]
// C = (function () {
// function class_1() {
// }
// return class_1;
// }())
return transformClassLikeDeclarationToExpression(node);
}
/**
* Transforms a ClassExpression or ClassDeclaration into an expression.
*
* @param node A ClassExpression or ClassDeclaration node.
*/
function transformClassLikeDeclarationToExpression(node: ClassExpression | ClassDeclaration): Expression {
// [source]
// class C extends D {
// constructor() {}
// method() {}
// get prop() {}
// set prop(v) {}
// }
//
// [output]
// (function (_super) {
// __extends(C, _super);
// function C() {
// }
// C.prototype.method = function () {}
// Object.defineProperty(C.prototype, "prop", {
// get: function() {},
// set: function() {},
// enumerable: true,
// configurable: true
// });
// return C;
// }(D))
if (node.name) {
enableSubstitutionsForBlockScopedBindings();
}
const extendsClauseElement = getClassExtendsHeritageElement(node);
const classFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
extendsClauseElement ? [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createFileLevelUniqueName("_super"))] : [],
/*type*/ undefined,
transformClassBody(node, extendsClauseElement)
);
// To preserve the behavior of the old emitter, we explicitly indent
// the body of the function here if it was requested in an earlier
// transformation.
setEmitFlags(classFunction, (getEmitFlags(node) & EmitFlags.Indented) | EmitFlags.ReuseTempVariableScope);
// "inner" and "outer" below are added purely to preserve source map locations from
// the old emitter
const inner = createPartiallyEmittedExpression(classFunction);
inner.end = node.end;
setEmitFlags(inner, EmitFlags.NoComments);
const outer = createPartiallyEmittedExpression(inner);
outer.end = skipTrivia(currentText, node.pos);
setEmitFlags(outer, EmitFlags.NoComments);
const result = createParen(
createCall(
outer,
/*typeArguments*/ undefined,
extendsClauseElement
? [visitNode(extendsClauseElement.expression, visitor, isExpression)]
: []
)
);
addSyntheticLeadingComment(result, SyntaxKind.MultiLineCommentTrivia, "* @class ");
return result;
}
/**
* Transforms a ClassExpression or ClassDeclaration into a function body.
*
* @param node A ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function transformClassBody(node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): Block {
const statements: Statement[] = [];
startLexicalEnvironment();
addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
addConstructor(statements, node, extendsClauseElement);
addClassMembers(statements, node);
// Create a synthetic text range for the return statement.
const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), SyntaxKind.CloseBraceToken);
const localName = getInternalName(node);
// The following partially-emitted expression exists purely to align our sourcemap
// emit with the original emitter.
const outer = createPartiallyEmittedExpression(localName);
outer.end = closingBraceLocation.end;
setEmitFlags(outer, EmitFlags.NoComments);
const statement = createReturn(outer);
statement.pos = closingBraceLocation.pos;
setEmitFlags(statement, EmitFlags.NoComments | EmitFlags.NoTokenSourceMaps);
statements.push(statement);
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
const block = createBlock(setTextRange(createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
setEmitFlags(block, EmitFlags.NoComments);
return block;
}
/**
* Adds a call to the `__extends` helper if needed for a class.
*
* @param statements The statements of the class body function.
* @param node The ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function addExtendsHelperIfNeeded(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): void {
if (extendsClauseElement) {
statements.push(
setTextRange(
createExpressionStatement(
createExtendsHelper(context, getInternalName(node))
),
/*location*/ extendsClauseElement
)
);
}
}
/**
* Adds the constructor of the class to a class body function.
*
* @param statements The statements of the class body function.
* @param node The ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function addConstructor(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): void {
const savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
const ancestorFacts = enterSubtree(HierarchyFacts.ConstructorExcludes, HierarchyFacts.ConstructorIncludes);
const constructor = getFirstConstructorWithBody(node);
const hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
const constructorFunction = createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
getInternalName(node),
/*typeParameters*/ undefined,
transformConstructorParameters(constructor, hasSynthesizedSuper),
/*type*/ undefined,
transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)
);
setTextRange(constructorFunction, constructor || node);
if (extendsClauseElement) {
setEmitFlags(constructorFunction, EmitFlags.CapturesThis);
}
statements.push(constructorFunction);
exitSubtree(ancestorFacts, HierarchyFacts.FunctionSubtreeExcludes, HierarchyFacts.None);
convertedLoopState = savedConvertedLoopState;
}
/**
* Transforms the parameters of the constructor declaration of a class.
*
* @param constructor The constructor for the class.
* @param hasSynthesizedSuper A value indicating whether the constructor starts with a
* synthesized `super` call.
*/
function transformConstructorParameters(constructor: ConstructorDeclaration | undefined, hasSynthesizedSuper: boolean) {
// If the TypeScript transformer needed to synthesize a constructor for property
// initializers, it would have also added a synthetic `...args` parameter and
// `super` call.
// If this is the case, we do not include the synthetic `...args` parameter and
// will instead use the `arguments` object in ES5/3.
return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| <ParameterDeclaration[]>[];
}
function createDefaultConstructorBody(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
// We must be here because the user didn't write a constructor
// but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
// If that's the case we can just immediately return the result of a 'super()' call.
const statements: Statement[] = [];
resumeLexicalEnvironment();
mergeLexicalEnvironment(statements, endLexicalEnvironment());
if (isDerivedClass) {
// return _super !== null && _super.apply(this, arguments) || this;
statements.push(createReturn(createDefaultSuperCallOrThis()));
}
const statementsArray = createNodeArray(statements);
setTextRange(statementsArray, node.members);
const block = createBlock(statementsArray, /*multiLine*/ true);
setTextRange(block, node);
setEmitFlags(block, EmitFlags.NoComments);
return block;
}
/**
* Transforms the body of a constructor declaration of a class.
*
* @param constructor The constructor for the class.
* @param node The node which contains the constructor.
* @param extendsClauseElement The expression for the class `extends` clause.
* @param hasSynthesizedSuper A value indicating whether the constructor starts with a
* synthesized `super` call.
*/
function transformConstructorBody(constructor: ConstructorDeclaration & { body: FunctionBody } | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments | undefined, hasSynthesizedSuper: boolean) {
// determine whether the class is known syntactically to be a derived class (e.g. a
// class that extends a value that is not syntactically known to be `null`).
const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword;
// When the subclass does not have a constructor, we synthesize a *default* constructor using the following
// representation:
//
// ```
// // es2015 (source)
// class C extends Base { }
//
// // es5 (transformed)
// var C = (function (_super) {
// function C() {
// return _super.apply(this, arguments) || this;
// }
// return C;
// })(Base);
// ```
if (!constructor) return createDefaultConstructorBody(node, isDerivedClass);
// The prologue will contain all leading standard and custom prologue statements added by this transform
const prologue: Statement[] = [];
const statements: Statement[] = [];
resumeLexicalEnvironment();
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
let statementOffset = 0;
if (!hasSynthesizedSuper) statementOffset = addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
if (!hasSynthesizedSuper) statementOffset = addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
// If the first statement is a call to `super()`, visit the statement directly
let superCallExpression: Expression | undefined;
if (hasSynthesizedSuper) {
superCallExpression = createDefaultSuperCallOrThis();
}
else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
const firstStatement = constructor.body.statements[statementOffset];
if (isExpressionStatement(firstStatement) && isSuperCall(firstStatement.expression)) {
superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
}
if (superCallExpression) {
hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper;
statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
// visit the remaining statements
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset));
mergeLexicalEnvironment(prologue, endLexicalEnvironment());
insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
if (isDerivedClass) {
if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) {
// If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
// following representation:
//
// ```
// // es2015 (source)
// class C extends Base {
// constructor() {
// super("foo");
// }
// }