forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.ts
More file actions
304 lines (277 loc) · 13.5 KB
/
transform.ts
File metadata and controls
304 lines (277 loc) · 13.5 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
/// <reference path="..\..\services\transform.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
describe("TransformAPI", () => {
function replaceUndefinedWithVoid0(context: TransformationContext) {
const previousOnSubstituteNode = context.onSubstituteNode;
context.enableSubstitution(SyntaxKind.Identifier);
context.onSubstituteNode = (hint, node) => {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression && isIdentifier(node) && node.escapedText === "undefined") {
node = createPartiallyEmittedExpression(
addSyntheticTrailingComment(
setTextRange(
createVoidZero(),
node),
SyntaxKind.MultiLineCommentTrivia, "undefined"));
}
return node;
};
return (file: SourceFile) => file;
}
function replaceNumberWith2(context: TransformationContext) {
function visitor(node: Node): Node {
if (isNumericLiteral(node)) {
return createNumericLiteral("2");
}
return visitEachChild(node, visitor, context);
}
return (file: SourceFile) => visitNode(file, visitor);
}
function replaceIdentifiersNamedOldNameWithNewName(context: TransformationContext) {
const previousOnSubstituteNode = context.onSubstituteNode;
context.enableSubstitution(SyntaxKind.Identifier);
context.onSubstituteNode = (hint, node) => {
node = previousOnSubstituteNode(hint, node);
if (isIdentifier(node) && node.escapedText === "oldName") {
node = setTextRange(createIdentifier("newName"), node);
}
return node;
};
return (file: SourceFile) => file;
}
function transformSourceFile(sourceText: string, transformers: TransformerFactory<SourceFile>[]) {
const transformed = transform(createSourceFile("source.ts", sourceText, ScriptTarget.ES2015), transformers);
const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed }, {
onEmitNode: transformed.emitNodeWithNotification,
substituteNode: transformed.substituteNode
});
const result = printer.printBundle(createBundle(transformed.transformed));
transformed.dispose();
return result;
}
function testBaseline(testName: string, test: () => string) {
it(testName, () => {
Harness.Baseline.runBaseline(`transformApi/transformsCorrectly.${testName}.js`, test);
});
}
testBaseline("substitution", () => {
return transformSourceFile(`var a = undefined;`, [replaceUndefinedWithVoid0]);
});
testBaseline("types", () => {
return transformSourceFile(`let a: () => void`, [
context => file => visitNode(file, function visitor(node: Node): VisitResult<Node> {
return visitEachChild(node, visitor, context);
})
]);
});
testBaseline("fromTranspileModule", () => {
return transpileModule(`var oldName = undefined;`, {
transformers: {
before: [replaceUndefinedWithVoid0],
after: [replaceIdentifiersNamedOldNameWithNewName]
},
compilerOptions: {
newLine: NewLineKind.CarriageReturnLineFeed
}
}).outputText;
});
testBaseline("rewrittenNamespace", () => {
return transpileModule(`namespace Reflect { const x = 1; }`, {
transformers: {
before: [forceNamespaceRewrite],
},
compilerOptions: {
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("rewrittenNamespaceFollowingClass", () => {
return transpileModule(`
class C { foo = 10; static bar = 20 }
namespace C { export let x = 10; }
`, {
transformers: {
before: [forceNamespaceRewrite],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("transformTypesInExportDefault", () => {
return transpileModule(`
export default (foo: string) => { return 1; }
`, {
transformers: {
before: [replaceNumberWith2],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("synthesizedClassAndNamespaceCombination", () => {
return transpileModule("", {
transformers: {
before: [replaceWithClassAndNamespace],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
function replaceWithClassAndNamespace() {
return (sourceFile: SourceFile) => {
const result = getMutableClone(sourceFile);
result.statements = createNodeArray([
createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, /*members*/ undefined!), // TODO: GH#18217
createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createIdentifier("Foo"), createModuleBlock([createEmptyStatement()]))
]);
return result;
};
}
});
function forceNamespaceRewrite(context: TransformationContext) {
return (sourceFile: SourceFile): SourceFile => {
return visitNode(sourceFile);
function visitNode<T extends Node>(node: T): T {
if (node.kind === SyntaxKind.ModuleBlock) {
const block = node as T & ModuleBlock;
const statements = createNodeArray([...block.statements]);
return updateModuleBlock(block, statements) as typeof block;
}
return visitEachChild(node, visitNode, context);
}
};
}
testBaseline("transformAwayExportStar", () => {
return transpileModule("export * from './helper';", {
transformers: {
before: [expandExportStar],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
function expandExportStar(context: TransformationContext) {
return (sourceFile: SourceFile): SourceFile => {
return visitNode(sourceFile);
function visitNode<T extends Node>(node: T): T {
if (node.kind === SyntaxKind.ExportDeclaration) {
const ed = node as Node as ExportDeclaration;
const exports = [{ name: "x" }];
const exportSpecifiers = exports.map(e => createExportSpecifier(e.name, e.name));
const exportClause = createNamedExports(exportSpecifiers);
const newEd = updateExportDeclaration(ed, ed.decorators, ed.modifiers, exportClause, ed.moduleSpecifier);
return newEd as Node as T;
}
return visitEachChild(node, visitNode, context);
}
};
}
});
// https://github.com/Microsoft/TypeScript/issues/19618
testBaseline("transformAddImportStar", () => {
return transpileModule("", {
transformers: {
before: [transformAddImportStar],
},
compilerOptions: {
target: ScriptTarget.ES5,
module: ModuleKind.System,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
function transformAddImportStar(_context: TransformationContext) {
return (sourceFile: SourceFile): SourceFile => {
return visitNode(sourceFile);
};
function visitNode(sf: SourceFile) {
// produce `import * as i0 from './comp';
const importStar = createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*importClause*/ createImportClause(
/*name*/ undefined,
createNamespaceImport(createIdentifier("i0"))
),
/*moduleSpecifier*/ createLiteral("./comp1"));
return updateSourceFileNode(sf, [importStar]);
}
}
});
// https://github.com/Microsoft/TypeScript/issues/17384
testBaseline("transformAddDecoratedNode", () => {
return transpileModule("", {
transformers: {
before: [transformAddDecoratedNode],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
function transformAddDecoratedNode(_context: TransformationContext) {
return (sourceFile: SourceFile): SourceFile => {
return visitNode(sourceFile);
};
function visitNode(sf: SourceFile) {
// produce `class Foo { @Bar baz() {} }`;
const classDecl = createClassDeclaration([], [], "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [
createMethod([createDecorator(createIdentifier("Bar"))], [], /**/ undefined, "baz", /**/ undefined, /**/ undefined, [], /**/ undefined, createBlock([]))
]);
return updateSourceFileNode(sf, [classDecl]);
}
}
});
testBaseline("transformDeclarationFile", () => {
return baselineDeclarationTransform(`var oldName = undefined;`, {
transformers: {
afterDeclarations: [replaceIdentifiersNamedOldNameWithNewName]
},
compilerOptions: {
newLine: NewLineKind.CarriageReturnLineFeed,
declaration: true
}
});
});
function baselineDeclarationTransform(text: string, opts: TranspileOptions) {
const fs = vfs.createFromFileSystem(Harness.IO, /*caseSensitive*/ true, { documents: [new documents.TextDocument("/.src/index.ts", text)] });
const host = new fakes.CompilerHost(fs, opts.compilerOptions);
const program = createProgram(["/.src/index.ts"], opts.compilerOptions!, host);
program.emit(program.getSourceFile("/.src/index.ts"), (p, s, bom) => host.writeFile(p, s, bom), /*cancellationToken*/ undefined, /*onlyDts*/ true, opts.transformers);
return fs.readFileSync("/.src/index.d.ts").toString();
}
// https://github.com/Microsoft/TypeScript/issues/24096
testBaseline("transformAddCommentToArrowReturnValue", () => {
return transpileModule(`const foo = () =>
void 0
`, {
transformers: {
before: [addSyntheticComment],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
function addSyntheticComment(context: TransformationContext) {
return (sourceFile: SourceFile): SourceFile => {
return visitNode(sourceFile, rootTransform, isSourceFile);
};
function rootTransform<T extends Node>(node: T): VisitResult<T> {
if (isVoidExpression(node)) {
setEmitFlags(node, EmitFlags.NoLeadingComments);
setSyntheticLeadingComments(node, [{ kind: SyntaxKind.SingleLineCommentTrivia, text: "// comment!", pos: -1, end: -1, hasTrailingNewLine: true }]);
return node;
}
return visitEachChild(node, rootTransform, context);
}
}
});
});
}