forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.ts
More file actions
983 lines (873 loc) · 41.7 KB
/
Copy pathmodule.ts
File metadata and controls
983 lines (873 loc) · 41.7 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
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformModule(context: TransformationContext) {
const transformModuleDelegates: Map<(node: SourceFile) => SourceFile> = {
[ModuleKind.None]: transformCommonJSModule,
[ModuleKind.CommonJS]: transformCommonJSModule,
[ModuleKind.AMD]: transformAMDModule,
[ModuleKind.UMD]: transformUMDModule,
};
const {
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
setNodeEmitFlags,
getNodeEmitFlags,
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(SyntaxKind.Identifier);
context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment);
let currentSourceFile: SourceFile;
let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
let exportSpecifiers: Map<ExportSpecifier[]>;
let exportEquals: ExportAssignment;
let hasExportStarsToExportValues: boolean;
return transformSourceFile;
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
// Collect information about the external module.
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
// Perform the transformation.
const updated = transformModuleDelegates[moduleKind](node);
aggregateTransformFlags(updated);
currentSourceFile = undefined;
externalImports = undefined;
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStarsToExportValues = false;
return updated;
}
return node;
}
/**
* Transforms a SourceFile into a CommonJS module.
*
* @param node The SourceFile node.
*/
function transformCommonJSModule(node: SourceFile) {
startLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
const updated = updateSourceFile(node, statements);
if (hasExportStarsToExportValues) {
setNodeEmitFlags(updated, NodeEmitFlags.EmitExportStar | getNodeEmitFlags(node));
}
return updated;
}
/**
* Transforms a SourceFile into an AMD module.
*
* @param node The SourceFile node.
*/
function transformAMDModule(node: SourceFile) {
const define = createIdentifier("define");
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true);
}
/**
* Transforms a SourceFile into a UMD module.
*
* @param node The SourceFile node.
*/
function transformUMDModule(node: SourceFile) {
const define = createIdentifier("define");
setNodeEmitFlags(define, NodeEmitFlags.UMDDefine);
return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false);
}
/**
* Transforms a SourceFile into an AMD or UMD module.
*
* @param node The SourceFile node.
* @param define The expression used to define the module.
* @param moduleName An expression for the module name, if available.
* @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies.
*/
function transformAsynchronousModule(node: SourceFile, define: Expression, moduleName: Expression, includeNonAmdDependencies: boolean) {
// An AMD define function has the following shape:
//
// define(id?, dependencies?, factory);
//
// This has the shape of the following:
//
// define(name, ["module1", "module2"], function (module1Alias) { ... }
//
// The location of the alias in the parameter list in the factory function needs to
// match the position of the module name in the dependency list.
//
// To ensure this is true in cases of modules with no aliases, e.g.:
//
// import "module"
//
// or
//
// /// <amd-dependency path= "a.css" />
//
// we need to add modules without alias names to the end of the dependencies list
const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies(node, includeNonAmdDependencies);
// Create an updated SourceFile:
//
// define(moduleName?, ["module1", "module2"], function ...
return updateSourceFile(node, [
createStatement(
createCall(
define,
[
// Add the module name (if provided).
...(moduleName ? [moduleName] : []),
// Add the dependency array argument:
//
// ["require", "exports", module1", "module2", ...]
createArrayLiteral([
createLiteral("require"),
createLiteral("exports"),
...aliasedModuleNames,
...unaliasedModuleNames
]),
// Add the module body function argument:
//
// function (require, exports, module1, module2) ...
createFunctionExpression(
/*asteriskToken*/ undefined,
/*name*/ undefined,
[
createParameter("require"),
createParameter("exports"),
...importAliasNames
],
transformAsynchronousModuleBody(node)
)
]
)
)
]);
}
/**
* Transforms a SourceFile into an AMD or UMD module body.
*
* @param node The SourceFile node.
*/
function transformAsynchronousModuleBody(node: SourceFile) {
startLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
// Visit each statement of the module body.
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
// End the lexical environment for the module body
// and merge any new lexical declarations.
addRange(statements, endLexicalEnvironment());
// Append the 'export =' statement if provided.
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
const body = createBlock(statements, /*location*/ undefined, /*multiLine*/ true);
if (hasExportStarsToExportValues) {
// If we have any `export * from ...` declarations
// we need to inform the emitter to add the __export helper.
setNodeEmitFlags(body, NodeEmitFlags.EmitExportStar);
}
return body;
}
function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) {
if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) {
if (emitAsReturn) {
statements.push(createReturn(exportEquals.expression));
}
else {
statements.push(
createStatement(
createAssignment(
createPropertyAccess(
createIdentifier("module"),
"exports"
),
exportEquals.expression
)
)
);
}
}
}
/**
* Visits a node at the top level of the source file.
*
* @param node The node.
*/
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(<ExpressionStatement>node);
default:
// This visitor does not descend into the tree, as export/import statements
// are only transformed at the top level of a file.
return node;
}
}
/**
* Visits an ImportDeclaration node.
*
* @param node The ImportDeclaration node.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
if (!contains(externalImports, node)) {
return undefined;
}
const statements: Statement[] = [];
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (moduleKind !== ModuleKind.AMD) {
if (!node.importClause) {
// import "mod";
statements.push(
createStatement(
createRequireCall(node),
/*location*/ node
)
);
}
else {
const variables: VariableDeclaration[] = [];
if (namespaceDeclaration && !isDefaultImport(node)) {
// import * as n from "mod";
variables.push(
createVariableDeclaration(
getSynthesizedClone(namespaceDeclaration.name),
createRequireCall(node)
)
);
}
else {
// import d from "mod";
// import { x, y } from "mod";
// import d, { x, y } from "mod";
// import d, * as n from "mod";
variables.push(
createVariableDeclaration(
getGeneratedNameForNode(node),
createRequireCall(node)
)
);
if (namespaceDeclaration && isDefaultImport(node)) {
variables.push(
createVariableDeclaration(
getSynthesizedClone(namespaceDeclaration.name),
getGeneratedNameForNode(node)
)
);
}
}
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createConstDeclarationList(variables),
/*location*/ node
)
);
}
}
else if (namespaceDeclaration && isDefaultImport(node)) {
// import d, * as n from "mod";
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
getSynthesizedClone(namespaceDeclaration.name),
getGeneratedNameForNode(node),
/*location*/ node
)
])
)
);
}
addExportImportAssignments(statements, node);
return singleOrMany(statements);
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
if (!contains(externalImports, node)) {
return undefined;
}
// Set emitFlags on the name of the importEqualsDeclaration
// This is so the printer will not substitute the identifier
setNodeEmitFlags(node.name, NodeEmitFlags.NoSubstitution);
const statements: Statement[] = [];
if (moduleKind !== ModuleKind.AMD) {
if (hasModifier(node, ModifierFlags.Export)) {
statements.push(
createStatement(
createExportAssignment(
node.name,
createRequireCall(node)
),
/*location*/ node
)
);
}
else {
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
getSynthesizedClone(node.name),
createRequireCall(node)
)
],
/*location*/ undefined,
/*flags*/ languageVersion >= ScriptTarget.ES6 ? NodeFlags.Const : NodeFlags.None),
/*location*/ node
)
);
}
}
else {
if (hasModifier(node, ModifierFlags.Export)) {
statements.push(
createStatement(
createExportAssignment(node.name, node.name),
/*location*/ node
)
);
}
}
addExportImportAssignments(statements, node);
return statements;
}
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
if (!contains(externalImports, node)) {
return undefined;
}
const generatedName = getGeneratedNameForNode(node);
if (node.exportClause) {
const statements: Statement[] = [];
// export { x, y } from "mod";
if (moduleKind !== ModuleKind.AMD) {
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
generatedName,
createRequireCall(node)
)
]),
/*location*/ node
)
);
}
for (const specifier of node.exportClause.elements) {
if (resolver.isValueAliasDeclaration(specifier)) {
const exportedValue = createPropertyAccess(
generatedName,
specifier.propertyName || specifier.name
);
statements.push(
createStatement(
createExportAssignment(specifier.name, exportedValue),
/*location*/ specifier
)
);
}
}
return singleOrMany(statements);
}
else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) {
// export * from "mod";
return createStatement(
createCall(
createIdentifier("__export"),
[
moduleKind !== ModuleKind.AMD
? createRequireCall(node)
: generatedName
]
),
/*location*/ node
);
}
}
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
const statements: Statement[] = [];
addExportDefault(statements, node.expression, /*location*/ node);
return statements;
}
}
return undefined;
}
function addExportDefault(statements: Statement[], expression: Expression, location: TextRange): void {
tryAddExportDefaultCompat(statements);
statements.push(
createStatement(
createExportAssignment(
createIdentifier("default"),
expression
),
location
)
);
}
function tryAddExportDefaultCompat(statements: Statement[]) {
const original = getOriginalNode(currentSourceFile);
Debug.assert(original.kind === SyntaxKind.SourceFile);
if (!original.symbol.exports["___esModule"]) {
if (languageVersion === ScriptTarget.ES3) {
statements.push(
createStatement(
createExportAssignment(
createIdentifier("__esModule"),
createLiteral(true)
)
)
);
}
else {
statements.push(
createStatement(
createObjectDefineProperty(
createIdentifier("exports"),
createLiteral("__esModule"),
{ value: createLiteral(true) }
)
)
);
}
}
}
function addExportImportAssignments(statements: Statement[], node: ImportEqualsDeclaration | ImportDeclaration) {
if (isImportEqualsDeclaration(node)) {
addExportMemberAssignments(statements, node.name);
}
else {
const names = reduceEachChild(node, collectExportMembers, []);
for (const name of names) {
addExportMemberAssignments(statements, name);
}
}
}
function collectExportMembers(names: Identifier[], node: Node): Identifier[] {
if (isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && isDeclaration(node)) {
const name = node.name;
if (isIdentifier(name)) {
names.push(name);
}
}
return reduceEachChild(node, collectExportMembers, names);
}
function addExportMemberAssignments(statements: Statement[], name: Identifier): void {
if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) {
for (const specifier of exportSpecifiers[name.text]) {
statements.push(
startOnNewLine(
createStatement(
createExportAssignment(specifier.name, name),
/*location*/ specifier.name
)
)
);
}
}
}
function addExportMemberAssignment(statements: Statement[], node: DeclarationStatement) {
if (hasModifier(node, ModifierFlags.Default)) {
addExportDefault(statements, getDeclarationName(node), /*location*/ node);
}
else {
statements.push(
createExportStatement(node.name, setNodeEmitFlags(getSynthesizedClone(node.name), NodeEmitFlags.LocalName), /*location*/ node)
);
}
}
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
// If the variable is for a generated declaration,
// we should maintain it and just strip off the 'export' modifier if necessary.
const originalKind = getOriginalNode(node).kind;
if (originalKind === SyntaxKind.ModuleDeclaration ||
originalKind === SyntaxKind.EnumDeclaration ||
originalKind === SyntaxKind.ClassDeclaration) {
if (!hasModifier(node, ModifierFlags.Export)) {
return node;
}
return setOriginalNode(
createVariableStatement(
/*modifiers*/ undefined,
node.declarationList
),
node
);
}
const resultStatements: Statement[] = [];
// If we're exporting these variables, then these just become assignments to 'exports.blah'.
// We only want to emit assignments for variables with initializers.
if (hasModifier(node, ModifierFlags.Export)) {
const variables = getInitializedVariables(node.declarationList);
if (variables.length > 0) {
let inlineAssignments = createStatement(
inlineExpressions(
map(variables, transformInitializedVariable)
),
node
);
resultStatements.push(inlineAssignments);
}
}
else {
resultStatements.push(node);
}
// While we might not have been exported here, each variable might have been exported
// later on in an export specifier (e.g. `export {foo as blah, bar}`).
for (const decl of node.declarationList.declarations) {
addExportMemberAssignmentsForBindingName(resultStatements, decl.name);
}
return resultStatements;
}
/**
* Creates appropriate assignments for each binding identifier that is exported in an export specifier,
* and inserts it into 'resultStatements'.
*/
function addExportMemberAssignmentsForBindingName(resultStatements: Statement[], name: BindingName): void {
if (isBindingPattern(name)) {
for (const element of name.elements) {
addExportMemberAssignmentsForBindingName(resultStatements, element.name)
}
}
else {
addExportMemberAssignments(resultStatements, name);
}
}
function transformInitializedVariable(node: VariableDeclaration): Expression {
const name = node.name;
if (isBindingPattern(name)) {
return flattenVariableDestructuringToExpression(
context,
node,
hoistVariableDeclaration,
getModuleMemberName,
visitor
);
}
else {
return createAssignment(
getModuleMemberName(name),
visitNode(node.initializer, visitor, isExpression)
);
}
}
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
const statements: Statement[] = [];
const name = node.name || getGeneratedNameForNode(node);
if (hasModifier(node, ModifierFlags.Export)) {
statements.push(
createFunctionDeclaration(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
name,
node.parameters,
node.body,
/*location*/ node
)
);
addExportMemberAssignment(statements, node);
}
else {
statements.push(node);
}
if (node.name) {
addExportMemberAssignments(statements, node.name);
}
return singleOrMany(statements);
}
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
const statements: Statement[] = [];
const name = node.name || getGeneratedNameForNode(node);
// Set emitFlags on the name of the classDeclaration
// This is so that when printer will not substitute the identifier
setNodeEmitFlags(name, NodeEmitFlags.NoSubstitution);
if (hasModifier(node, ModifierFlags.Export)) {
statements.push(
setOriginalNode(
createClassDeclaration(
/*modifiers*/ undefined,
name,
node.heritageClauses,
node.members,
/*location*/ node
),
/*original*/ node
)
);
addExportMemberAssignment(statements, node);
}
else {
statements.push(node);
}
// Decorators end up creating a series of assignment expressions which overwrite
// the local binding that we export, so we need to defer from exporting decorated classes
// until the decoration assignments take place. We do this when visiting expression-statements.
if (node.name && !(node.decorators && node.decorators.length)) {
addExportMemberAssignments(statements, node.name);
}
return singleOrMany(statements);
}
function visitExpressionStatement(node: ExpressionStatement): VisitResult<Statement> {
const original = getOriginalNode(node);
const origKind = original.kind;
if (origKind === SyntaxKind.EnumDeclaration || origKind === SyntaxKind.ModuleDeclaration) {
return visitExpressionStatementForEnumOrNamespaceDeclaration(node, <EnumDeclaration | ModuleDeclaration>original);
}
else if (origKind === SyntaxKind.ClassDeclaration) {
// The decorated assignment for a class name may need to be transformed.
const classDecl = original as ClassDeclaration;
if (classDecl.name) {
const statements = [node];
// Avoid emitting a default because a decorated default-exported class will have been rewritten in the TS transformer to
// a decorator assignment (`foo = __decorate(...)`) followed by a separate default export declaration (`export default foo`).
// We will eventually take care of that default export assignment when we transform the generated default export declaration.
if (hasModifier(classDecl, ModifierFlags.Export) && !hasModifier(classDecl, ModifierFlags.Default)) {
addExportMemberAssignment(statements, classDecl)
}
addExportMemberAssignments(statements, classDecl.name);
return statements;
}
}
return node;
}
function visitExpressionStatementForEnumOrNamespaceDeclaration(node: ExpressionStatement, original: EnumDeclaration | ModuleDeclaration): VisitResult<Statement> {
const statements: Statement[] = [node];
// Preserve old behavior for enums in which a variable statement is emitted after the body itself.
if (hasModifier(original, ModifierFlags.Export) &&
original.kind === SyntaxKind.EnumDeclaration &&
isFirstDeclarationOfKind(original, SyntaxKind.EnumDeclaration)) {
addVarForExportedEnumOrNamespaceDeclaration(statements, original);
}
addExportMemberAssignments(statements, original.name);
return statements;
}
/**
* Adds a trailing VariableStatement for an enum or module declaration.
*/
function addVarForExportedEnumOrNamespaceDeclaration(statements: Statement[], node: EnumDeclaration | ModuleDeclaration) {
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
[createVariableDeclaration(
getDeclarationName(node),
createPropertyAccess(createIdentifier("exports"), getDeclarationName(node))
)],
/*location*/ node
)
);
}
function getDeclarationName(node: DeclarationStatement) {
return node.name ? getSynthesizedClone(node.name) : getGeneratedNameForNode(node);
}
/**
* Hooks node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(node: Node, isExpression: boolean) {
node = previousOnSubstituteNode(node, isExpression);
if (isExpression) {
return substituteExpression(<Expression>node);
}
else if (isShorthandPropertyAssignment(node)) {
return substituteShorthandPropertyAssignment(node);
}
return node;
}
function substituteShorthandPropertyAssignment(node: ShorthandPropertyAssignment): ObjectLiteralElement {
const name = node.name;
const exportedOrImportedName = substituteExpressionIdentifier(name);
if (exportedOrImportedName !== name) {
// A shorthand property with an assignment initializer is probably part of a
// destructuring assignment
if (node.objectAssignmentInitializer) {
const initializer = createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
return createPropertyAssignment(name, initializer, /*location*/ node);
}
return createPropertyAssignment(name, exportedOrImportedName, /*location*/ node);
}
return node;
}
function substituteExpression(node: Expression) {
if (isIdentifier(node)) {
return substituteExpressionIdentifier(node);
}
return node;
}
function substituteExpressionIdentifier(node: Identifier): Expression {
return trySubstituteExportedName(node)
|| trySubstituteImportedName(node)
|| node;
}
function trySubstituteExportedName(node: Identifier) {
const emitFlags = getNodeEmitFlags(node);
if ((emitFlags & NodeEmitFlags.LocalName) === 0) {
const container = resolver.getReferencedExportContainer(node, (emitFlags & NodeEmitFlags.ExportName) !== 0);
if (container) {
if (container.kind === SyntaxKind.SourceFile) {
return createPropertyAccess(
createIdentifier("exports"),
getSynthesizedClone(node),
/*location*/ node
);
}
}
}
return undefined;
}
function trySubstituteImportedName(node: Identifier): Expression {
if ((getNodeEmitFlags(node) & NodeEmitFlags.LocalName) === 0) {
const declaration = resolver.getReferencedImportDeclaration(node);
if (declaration) {
if (isImportClause(declaration)) {
if (languageVersion >= ScriptTarget.ES5) {
return createPropertyAccess(
getGeneratedNameForNode(declaration.parent),
createIdentifier("default"),
/*location*/ node
);
}
else {
// TODO: ES3 transform to handle x.default -> x["default"]
return createElementAccess(
getGeneratedNameForNode(declaration.parent),
createLiteral("default"),
/*location*/ node
);
}
}
else if (isImportSpecifier(declaration)) {
const name = declaration.propertyName || declaration.name;
if (name.originalKeywordKind === SyntaxKind.DefaultKeyword && languageVersion <= ScriptTarget.ES3) {
// TODO: ES3 transform to handle x.default -> x["default"]
return createElementAccess(
getGeneratedNameForNode(declaration.parent.parent.parent),
createLiteral(name.text),
/*location*/ node
);
}
else {
return createPropertyAccess(
getGeneratedNameForNode(declaration.parent.parent.parent),
getSynthesizedClone(name),
/*location*/ node
);
}
}
}
}
return undefined;
}
function getModuleMemberName(name: Identifier) {
return createPropertyAccess(
createIdentifier("exports"),
name,
/*location*/ name
);
}
function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) {
const moduleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
const args: Expression[] = [];
if (isDefined(moduleName)) {
args.push(moduleName);
}
return createCall(createIdentifier("require"), args);
}
function createExportStatement(name: Identifier, value: Expression, location?: TextRange) {
return startOnNewLine(createStatement(createExportAssignment(name, value), location));
}
function createExportAssignment(name: Identifier, value: Expression) {
return createAssignment(
name.originalKeywordKind === SyntaxKind.DefaultKeyword && languageVersion === ScriptTarget.ES3
? createElementAccess(
createIdentifier("exports"),
createLiteral(name.text)
)
: createPropertyAccess(
createIdentifier("exports"),
getSynthesizedClone(name)
),
value
);
}
interface AsynchronousDependencies {
aliasedModuleNames: Expression[];
unaliasedModuleNames: Expression[];
importAliasNames: ParameterDeclaration[];
}
function collectAsynchronousDependencies(node: SourceFile, includeNonAmdDependencies: boolean): AsynchronousDependencies {
// names of modules with corresponding parameter in the factory function
const aliasedModuleNames: Expression[] = [];
// names of modules with no corresponding parameters in factory function
const unaliasedModuleNames: Expression[] = [];
// names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
const importAliasNames: ParameterDeclaration[] = [];
// Fill in amd-dependency tags
for (const amdDependency of node.amdDependencies) {
if (amdDependency.name) {
aliasedModuleNames.push(createLiteral(amdDependency.path));
importAliasNames.push(createParameter(amdDependency.name));
}
else {
unaliasedModuleNames.push(createLiteral(amdDependency.path));
}
}
for (const importNode of externalImports) {
// Find the name of the external module
const externalModuleName = getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(importNode, currentSourceFile);
if (includeNonAmdDependencies && importAliasName) {
// Set emitFlags on the name of the classDeclaration
// This is so that when printer will not substitute the identifier
setNodeEmitFlags(importAliasName, NodeEmitFlags.NoSubstitution);
aliasedModuleNames.push(externalModuleName);
importAliasNames.push(createParameter(importAliasName));
}
else {
unaliasedModuleNames.push(externalModuleName);
}
}
return { aliasedModuleNames, unaliasedModuleNames, importAliasNames };
}
function updateSourceFile(node: SourceFile, statements: Statement[]) {
const updated = getMutableClone(node);
updated.statements = createNodeArray(statements, node.statements);
return updated;
}
}
}