forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem.ts
More file actions
1934 lines (1730 loc) · 86.8 KB
/
system.ts
File metadata and controls
1934 lines (1730 loc) · 86.8 KB
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 {
export function transformSystemModule(context: TransformationContext) {
interface DependencyGroup {
name: StringLiteral;
externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
}
const {
factory,
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers for imported symbols.
context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment); // Substitutes expression identifiers for imported symbols
context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols.
context.enableSubstitution(SyntaxKind.MetaProperty); // Substitutes 'import.meta'
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: (Statement[] | undefined)[] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap: Identifier[] = []; // The export function associated with a source file.
const noSubstitutionMap: boolean[][] = []; // Set of nodes for which substitution rules should be ignored for each file.
const contextObjectMap: Identifier[] = []; // The context object associated with a source file.
let currentSourceFile: SourceFile; // The current file.
let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file.
let exportFunction: Identifier; // The export function for the current file.
let contextObject: Identifier; // The context object for the current file.
let hoistedStatements: Statement[] | undefined;
let enclosingBlockScopedContainer: Node;
let noSubstitution: boolean[] | undefined; // Set of nodes for which substitution rules should be ignored.
return chainBundle(context, transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return node;
}
const id = getOriginalNodeId(node);
currentSourceFile = node;
enclosingBlockScopedContainer = node;
// System modules have the following shape:
//
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
//
// The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
// is used to publish exported values. 'exports' returns its 'value' argument so in
// most cases expressions that mutate exported values can be rewritten as:
//
// expr -> exports('name', expr)
//
// The only exception in this rule is postfix unary operators,
// see comment to 'substitutePostfixUnaryExpression' for more details
// Collect information about the external module and dependency groups.
moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
exportFunction = factory.createUniqueName("exports");
exportFunctionsMap[id] = exportFunction;
contextObject = contextObjectMap[id] = factory.createUniqueName("context");
// Add the body of the module.
const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
const moduleBodyFunction = factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
],
/*type*/ undefined,
moduleBodyBlock
);
// Write the call to `System.register`
// Clear the emit-helpers flag for later passes since we'll have already used it in the module body
// So the helper will be emit at the correct position instead of at the top of the source-file
const moduleName = tryGetModuleNameFromFile(factory, node, host, compilerOptions);
const dependencies = factory.createArrayLiteralExpression(map(dependencyGroups, dependencyGroup => dependencyGroup.name));
const updated = setEmitFlags(
factory.updateSourceFile(
node,
setTextRange(
factory.createNodeArray([
factory.createExpressionStatement(
factory.createCallExpression(
factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"),
/*typeArguments*/ undefined,
moduleName
? [moduleName, dependencies, moduleBodyFunction]
: [dependencies, moduleBodyFunction]
)
)
]),
node.statements
)
), EmitFlags.NoTrailingComments);
if (!outFile(compilerOptions)) {
moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped);
}
if (noSubstitution) {
noSubstitutionMap[id] = noSubstitution;
noSubstitution = undefined;
}
currentSourceFile = undefined!;
moduleInfo = undefined!;
exportFunction = undefined!;
contextObject = undefined!;
hoistedStatements = undefined;
enclosingBlockScopedContainer = undefined!;
return updated;
}
/**
* Collects the dependency groups for this files imports.
*
* @param externalImports The imports for the file.
*/
function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) {
const groupIndices = new Map<string, number>();
const dependencyGroups: DependencyGroup[] = [];
for (const externalImport of externalImports) {
const externalModuleName = getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
if (externalModuleName) {
const text = externalModuleName.text;
const groupIndex = groupIndices.get(text);
if (groupIndex !== undefined) {
// deduplicate/group entries in dependency list by the dependency name
dependencyGroups[groupIndex].externalImports.push(externalImport);
}
else {
groupIndices.set(text, dependencyGroups.length);
dependencyGroups.push({
name: externalModuleName,
externalImports: [externalImport]
});
}
}
}
return dependencyGroups;
}
/**
* Adds the statements for the module body function for the source file.
*
* @param node The source file for the module.
* @param dependencyGroups The grouped dependencies of the module.
*/
function createSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[]) {
// Shape of the body in system modules:
//
// function (exports) {
// <list of local aliases for imports>
// <hoisted variable declarations>
// <hoisted function declarations>
// return {
// setters: [
// <list of setter function for imports>
// ],
// execute: function() {
// <module statements>
// }
// }
// <temp declarations>
// }
//
// i.e:
//
// import {x} from 'file1'
// var y = 1;
// export function foo() { return y + x(); }
// console.log(y);
//
// Will be transformed to:
//
// function(exports) {
// function foo() { return y + file_1.x(); }
// exports("foo", foo);
// var file_1, y;
// return {
// setters: [
// function(v) { file_1 = v }
// ],
// execute(): function() {
// y = 1;
// console.log(y);
// }
// };
// }
const statements: Statement[] = [];
// We start a new lexical environment in this function body, but *not* in the
// body of the execute function. This allows us to emit temporary declarations
// only in the outer module body and not in the inner one.
startLexicalEnvironment();
// Add any prologue directives.
const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, topLevelVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList([
factory.createVariableDeclaration(
"__moduleName",
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.createLogicalAnd(
contextObject,
factory.createPropertyAccessExpression(contextObject, "id")
)
)
])
)
);
// Visit the synthetic external helpers import declaration if present
visitNode(moduleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
// setters. This allows us to reduce the number of times we need to loop through the
// statements of the source file.
const executeStatements = visitNodes(node.statements, topLevelVisitor, isStatement, statementOffset);
// Emit early exports for function declarations.
addRange(statements, hoistedStatements);
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
const exportStarFunction = addExportStarIfNeeded(statements)!; // TODO: GH#18217
const modifiers = node.transformFlags & TransformFlags.ContainsAwait ?
factory.createModifiersFromModifierFlags(ModifierFlags.Async) :
undefined;
const moduleObject = factory.createObjectLiteralExpression([
factory.createPropertyAssignment("setters",
createSettersArray(exportStarFunction, dependencyGroups)
),
factory.createPropertyAssignment("execute",
factory.createFunctionExpression(
modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
factory.createBlock(executeStatements, /*multiLine*/ true)
)
)
], /*multiLine*/ true);
statements.push(factory.createReturnStatement(moduleObject));
return factory.createBlock(statements, /*multiLine*/ true);
}
/**
* Adds an exportStar function to a statement list if it is needed for the file.
*
* @param statements A statement list.
*/
function addExportStarIfNeeded(statements: Statement[]) {
if (!moduleInfo.hasExportStarsToExportValues) {
return;
}
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
// local names set should only be added if we have anything exported
if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
let hasExportDeclarationWithExportClause = false;
for (const externalImport of moduleInfo.externalImports) {
if (externalImport.kind === SyntaxKind.ExportDeclaration && externalImport.exportClause) {
hasExportDeclarationWithExportClause = true;
break;
}
}
if (!hasExportDeclarationWithExportClause) {
// we still need to emit exportStar helper
const exportStarFunction = createExportStarFunction(/*localNames*/ undefined);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
}
const exportedNames: ObjectLiteralElementLike[] = [];
if (moduleInfo.exportedNames) {
for (const exportedLocalName of moduleInfo.exportedNames) {
if (exportedLocalName.escapedText === "default") {
continue;
}
// write name of exported declaration, i.e 'export var x...'
exportedNames.push(
factory.createPropertyAssignment(
factory.createStringLiteralFromNode(exportedLocalName),
factory.createTrue()
)
);
}
}
const exportedNamesStorageRef = factory.createUniqueName("exportedNames");
statements.push(
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList([
factory.createVariableDeclaration(
exportedNamesStorageRef,
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true)
)
])
)
);
const exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
/**
* Creates an exportStar function for the file, with an optional set of excluded local
* names.
*
* @param localNames An optional reference to an object containing a set of excluded local
* names.
*/
function createExportStarFunction(localNames: Identifier | undefined) {
const exportStarFunction = factory.createUniqueName("exportStar");
const m = factory.createIdentifier("m");
const n = factory.createIdentifier("n");
const exports = factory.createIdentifier("exports");
let condition: Expression = factory.createStrictInequality(n, factory.createStringLiteral("default"));
if (localNames) {
condition = factory.createLogicalAnd(
condition,
factory.createLogicalNot(
factory.createCallExpression(
factory.createPropertyAccessExpression(localNames, "hasOwnProperty"),
/*typeArguments*/ undefined,
[n]
)
)
);
}
return factory.createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
exportStarFunction,
/*typeParameters*/ undefined,
[factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
/*type*/ undefined,
factory.createBlock([
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList([
factory.createVariableDeclaration(
exports,
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.createObjectLiteralExpression([])
)
])
),
factory.createForInStatement(
factory.createVariableDeclarationList([
factory.createVariableDeclaration(n)
]),
m,
factory.createBlock([
setEmitFlags(
factory.createIfStatement(
condition,
factory.createExpressionStatement(
factory.createAssignment(
factory.createElementAccessExpression(exports, n),
factory.createElementAccessExpression(m, n)
)
)
),
EmitFlags.SingleLine
)
])
),
factory.createExpressionStatement(
factory.createCallExpression(
exportFunction,
/*typeArguments*/ undefined,
[exports]
)
)
], /*multiline*/ true)
);
}
/**
* Creates an array setter callbacks for each dependency group.
*
* @param exportStarFunction A reference to an exportStarFunction for the file.
* @param dependencyGroups An array of grouped dependencies.
*/
function createSettersArray(exportStarFunction: Identifier, dependencyGroups: DependencyGroup[]) {
const setters: Expression[] = [];
for (const group of dependencyGroups) {
// derive a unique name for parameter from the first named entry in the group
const localName = forEach(group.externalImports, i => getLocalNameForExternalImport(factory, i, currentSourceFile));
const parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
const statements: Statement[] = [];
for (const entry of group.externalImports) {
const importVariableName = getLocalNameForExternalImport(factory, entry, currentSourceFile)!; // TODO: GH#18217
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!entry.importClause) {
// 'import "..."' case
// module is imported only for side-effects, no emit required
break;
}
// falls through
case SyntaxKind.ImportEqualsDeclaration:
Debug.assert(importVariableName !== undefined);
// save import into the local
statements.push(
factory.createExpressionStatement(
factory.createAssignment(importVariableName, parameterName)
)
);
break;
case SyntaxKind.ExportDeclaration:
Debug.assert(importVariableName !== undefined);
if (entry.exportClause) {
if (isNamedExports(entry.exportClause)) {
// export {a, b as c} from 'foo'
//
// emit as:
//
// exports_({
// "a": _["a"],
// "c": _["b"]
// });
const properties: PropertyAssignment[] = [];
for (const e of entry.exportClause.elements) {
properties.push(
factory.createPropertyAssignment(
factory.createStringLiteral(idText(e.name)),
factory.createElementAccessExpression(
parameterName,
factory.createStringLiteral(idText(e.propertyName || e.name))
)
)
);
}
statements.push(
factory.createExpressionStatement(
factory.createCallExpression(
exportFunction,
/*typeArguments*/ undefined,
[factory.createObjectLiteralExpression(properties, /*multiline*/ true)]
)
)
);
}
else {
statements.push(
factory.createExpressionStatement(
factory.createCallExpression(
exportFunction,
/*typeArguments*/ undefined,
[
factory.createStringLiteral(idText(entry.exportClause.name)),
parameterName
]
)
)
);
}
}
else {
// export * from 'foo'
//
// emit as:
//
// exportStar(foo_1_1);
statements.push(
factory.createExpressionStatement(
factory.createCallExpression(
exportStarFunction,
/*typeArguments*/ undefined,
[parameterName]
)
)
);
}
break;
}
}
setters.push(
factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
/*type*/ undefined,
factory.createBlock(statements, /*multiLine*/ true)
)
);
}
return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
}
//
// Top-level Source Element Visitors
//
/**
* Visit source elements at the top-level of a module.
*
* @param node The node to visit.
*/
function topLevelVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(node as ImportDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(node as ExportDeclaration);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(node as ExportAssignment);
default:
return topLevelNestedVisitor(node);
}
}
/**
* Visits an ImportDeclaration node.
*
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[] | undefined;
if (node.importClause) {
hoistVariableDeclaration(getLocalNameForExternalImport(factory, node, currentSourceFile)!); // TODO: GH#18217
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportDeclaration(statements, node);
}
return singleOrMany(statements);
}
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
Debug.assertIsDefined(node);
return undefined;
}
/**
* Visits an ImportEqualsDeclaration node.
*
* @param node The node to visit.
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[] | undefined;
hoistVariableDeclaration(getLocalNameForExternalImport(factory, node, currentSourceFile)!); // TODO: GH#18217
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportEqualsDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits an ExportAssignment node.
*
* @param node The node to visit.
*/
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (node.isExportEquals) {
// Elide `export=` as it is illegal in a SystemJS module.
return undefined;
}
const expression = visitNode(node.expression, visitor, isExpression);
const original = node.original;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
}
else {
return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
}
}
/**
* Visits a FunctionDeclaration, hoisting it to the outer module body function.
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
hoistedStatements = append(hoistedStatements,
factory.updateFunctionDeclaration(
node,
node.decorators,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameterDeclaration),
/*type*/ undefined,
visitNode(node.body, visitor, isBlock)));
}
else {
hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
}
return undefined;
}
/**
* Visits a ClassDeclaration, hoisting its name to the outer module body function.
*
* @param node The node to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
let statements: Statement[] | undefined;
// Hoist the name of the class declaration to the outer module body function.
const name = factory.getLocalName(node);
hoistVariableDeclaration(name);
// Rewrite the class declaration into an assignment of a class expression.
statements = append(statements,
setTextRange(
factory.createExpressionStatement(
factory.createAssignment(
name,
setTextRange(
factory.createClassExpression(
visitNodes(node.decorators, visitor, isDecorator),
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
visitNodes(node.members, visitor, isClassElement)
),
node
)
)
),
node
)
);
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfHoistedDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits a variable statement, hoisting declared names to the top-level module body.
* Each declaration is rewritten into an assignment expression.
*
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
if (!shouldHoistVariableDeclarationList(node.declarationList)) {
return visitNode(node, visitor, isStatement);
}
let expressions: Expression[] | undefined;
const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export);
const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
for (const variable of node.declarationList.declarations) {
if (variable.initializer) {
expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
}
else {
hoistBindingElement(variable);
}
}
let statements: Statement[] | undefined;
if (expressions) {
statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
}
if (isMarkedDeclaration) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
}
else {
statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
}
return singleOrMany(statements);
}
/**
* Hoists the declared names of a VariableDeclaration or BindingElement.
*
* @param node The declaration to hoist.
*/
function hoistBindingElement(node: VariableDeclaration | BindingElement): void {
if (isBindingPattern(node.name)) {
for (const element of node.name.elements) {
if (!isOmittedExpression(element)) {
hoistBindingElement(element);
}
}
}
else {
hoistVariableDeclaration(factory.cloneNode(node.name));
}
}
/**
* Determines whether a VariableDeclarationList should be hoisted.
*
* @param node The node to test.
*/
function shouldHoistVariableDeclarationList(node: VariableDeclarationList) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (getEmitFlags(node) & EmitFlags.NoHoisting) === 0
&& (enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile
|| (getOriginalNode(node).flags & NodeFlags.BlockScoped) === 0);
}
/**
* Transform an initialized variable declaration into an expression.
*
* @param node The node to transform.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression {
const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
return isBindingPattern(node.name)
? flattenDestructuringAssignment(
node,
visitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name;
}
/**
* Creates an assignment expression for an exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
}
/**
* Creates an assignment expression for a non-exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createNonExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
}
/**
* Creates an assignment expression for a variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function createVariableAssignment(name: Identifier, value: Expression, location: TextRange | undefined, isExportedDeclaration: boolean) {
hoistVariableDeclaration(factory.cloneNode(name));
return isExportedDeclaration
? createExportExpression(name, preventSubstitution(setTextRange(factory.createAssignment(name, value), location)))
: preventSubstitution(setTextRange(factory.createAssignment(name, value), location));
}
/**
* Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
* and transformed declaration.
*
* @param node The node to visit.
*/
function visitMergeDeclarationMarker(node: MergeDeclarationMarker): VisitResult<Statement> {
// For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
// declaration we do not emit a leading variable declaration. To preserve the
// begin/end semantics of the declararation and to properly handle exports
// we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
//
// To balance the declaration, we defer the exports of the elided variable
// statement until we visit this declaration's `EndOfDeclarationMarker`.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original!.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
const isExportedDeclaration = hasSyntacticModifier(node.original!, ModifierFlags.Export);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original as VariableStatement, isExportedDeclaration);
}
return node;
}
/**
* Determines whether a node has an associated EndOfDeclarationMarker.
*
* @param node The node to test.
*/
function hasAssociatedEndOfDeclarationMarker(node: Node) {
return (getEmitFlags(node) & EmitFlags.HasEndOfDeclarationMarker) !== 0;
}
/**
* Visits a DeclarationMarker used as a placeholder for the end of a transformed
* declaration.
*
* @param node The node to visit.
*/
function visitEndOfDeclarationMarker(node: EndOfDeclarationMarker): VisitResult<Statement> {
// For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
// end of the transformed declaration. We use this marker to emit any deferred exports
// of the declaration.
const id = getOriginalNodeId(node);
const statements = deferredExports[id];
if (statements) {
delete deferredExports[id];
return append(statements, node);
}
else {
const original = getOriginalNode(node);
if (isModuleOrEnumDeclaration(original)) {
return append(appendExportsOfDeclaration(statements, original), node);
}
}
return node;
}
/**
* Appends the exports of an ImportDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportDeclaration(statements: Statement[] | undefined, decl: ImportDeclaration) {
if (moduleInfo.exportEquals) {
return statements;
}
const importClause = decl.importClause;
if (!importClause) {
return statements;
}
if (importClause.name) {
statements = appendExportsOfDeclaration(statements, importClause);
}
const namedBindings = importClause.namedBindings;
if (namedBindings) {
switch (namedBindings.kind) {
case SyntaxKind.NamespaceImport:
statements = appendExportsOfDeclaration(statements, namedBindings);
break;
case SyntaxKind.NamedImports:
for (const importBinding of namedBindings.elements) {
statements = appendExportsOfDeclaration(statements, importBinding);
}
break;
}
}
return statements;
}
/**
* Appends the export of an ImportEqualsDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, decl: ImportEqualsDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
return appendExportsOfDeclaration(statements, decl);
}
/**
* Appends the exports of a VariableStatement to a statement list, returning the statement
* list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param node The VariableStatement whose exports are to be recorded.
* @param exportSelf A value indicating whether to also export each VariableDeclaration of
* `nodes` declaration list.
*/
function appendExportsOfVariableStatement(statements: Statement[] | undefined, node: VariableStatement, exportSelf: boolean): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}