forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcustomTransforms.ts
More file actions
212 lines (200 loc) · 9 KB
/
customTransforms.ts
File metadata and controls
212 lines (200 loc) · 9 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
import * as Harness from "../_namespaces/Harness.js";
import * as ts from "../_namespaces/ts.js";
describe("unittests:: customTransforms", () => {
function emitsCorrectly(name: string, sources: { file: string; text: string; }[], customTransformers: ts.CustomTransformers, options: ts.CompilerOptions = {}) {
it(name, () => {
const roots = sources.map(source => ts.createSourceFile(source.file, source.text, ts.ScriptTarget.ES2015));
const fileMap = ts.arrayToMap(roots, file => file.fileName);
const outputs = new Map<string, string>();
const host: ts.CompilerHost = {
getSourceFile: fileName => fileMap.get(fileName),
getDefaultLibFileName: () => "lib.d.ts",
getCurrentDirectory: () => "",
getDirectories: () => [],
getCanonicalFileName: fileName => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => "\n",
fileExists: fileName => fileMap.has(fileName),
readFile: fileName => fileMap.has(fileName) ? fileMap.get(fileName)!.text : undefined,
writeFile: (fileName, text) => outputs.set(fileName, text),
};
const program = ts.createProgram(ts.arrayFrom(fileMap.keys()), { newLine: ts.NewLineKind.LineFeed, ...options }, host);
program.emit(/*targetSourceFile*/ undefined, host.writeFile, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ false, customTransformers);
let content = "";
for (const [file, text] of outputs.entries()) {
if (content) content += "\n\n";
content += `// [${file}]\n`;
content += text;
}
Harness.Baseline.runBaseline(`customTransforms/${name}.js`, content);
});
}
const sources = [{
file: "source.ts",
text: `
function f1() { }
class c() { }
enum e { }
// leading
function f2() { } // trailing
`,
}];
const before: ts.TransformerFactory<ts.SourceFile> = context => {
return file => ts.visitEachChild(file, visit, context);
function visit(node: ts.Node): ts.VisitResult<ts.Node> {
switch (node.kind) {
case ts.SyntaxKind.FunctionDeclaration:
return visitFunction(node as ts.FunctionDeclaration);
default:
return ts.visitEachChild(node, visit, context);
}
}
function visitFunction(node: ts.FunctionDeclaration) {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, "@before", /*hasTrailingNewLine*/ true);
return node;
}
};
const after: ts.TransformerFactory<ts.SourceFile> = context => {
return file => ts.visitEachChild(file, visit, context);
function visit(node: ts.Node): ts.VisitResult<ts.Node> {
switch (node.kind) {
case ts.SyntaxKind.VariableStatement:
return visitVariableStatement(node as ts.VariableStatement);
default:
return ts.visitEachChild(node, visit, context);
}
}
function visitVariableStatement(node: ts.VariableStatement) {
ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, "@after");
return node;
}
};
emitsCorrectly("before", sources, { before: [before] });
emitsCorrectly("after", sources, { after: [after] });
emitsCorrectly("both", sources, { before: [before], after: [after] });
emitsCorrectly("before+decorators", [{
file: "source.ts",
text: `
declare const dec: any;
class B {}
@dec export class C { constructor(b: B) { } }
'change'
`,
}], {
before: [
context => node =>
ts.visitNode(node, function visitor(node: ts.Node): ts.Node {
if (ts.isStringLiteral(node) && node.text === "change") return ts.factory.createStringLiteral("changed");
return ts.visitEachChild(node, visitor, context);
}, ts.isSourceFile),
],
}, {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.ES2015,
emitDecoratorMetadata: true,
experimentalDecorators: true,
});
emitsCorrectly("sourceMapExternalSourceFiles", [
{
file: "source.ts",
// The text of length 'changed' is made to be on two lines so we know the line map change
text: `\`multi
line\`
'change'`,
},
], {
before: [
context => node =>
ts.visitNode(node, function visitor(node: ts.Node): ts.Node {
if (ts.isStringLiteral(node) && node.text === "change") {
const text = "'changed'";
const lineMap = ts.computeLineStarts(text);
ts.setSourceMapRange(node, {
pos: 0,
end: text.length,
source: {
text,
fileName: "another.html",
lineMap,
getLineAndCharacterOfPosition: pos => ts.computeLineAndCharacterOfPosition(lineMap, pos),
},
});
return node;
}
return ts.visitEachChild(node, visitor, context);
}, ts.isSourceFile),
],
}, { sourceMap: true });
emitsCorrectly("skipTriviaExternalSourceFiles", [
{
file: "source.ts",
// The source file contains preceding trivia (e.g. whitespace) to try to confuse the `skipSourceTrivia` function.
text: " original;",
},
], {
before: [
context => {
const transformSourceFile: ts.Transformer<ts.SourceFile> = node =>
ts.visitNode(node, function visitor(node: ts.Node): ts.Node {
if (ts.isIdentifier(node) && node.text === "original") {
const newNode = ts.factory.createIdentifier("changed");
ts.setSourceMapRange(newNode, {
pos: 0,
end: 7,
// Do not provide a custom skipTrivia function for `source`.
source: ts.createSourceMapSource("another.html", "changed;"),
});
return newNode;
}
return ts.visitEachChild(node, visitor, context);
}, ts.isSourceFile);
return {
transformSourceFile,
transformBundle: node => ts.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile)),
};
},
],
}, { sourceMap: true, outFile: "source.js" });
emitsCorrectly("importDeclarationBeforeTransformElision", [
{
file: "a.ts",
text: "export type A = string;",
},
{
file: "index.ts",
text: "import { A } from './a.js';\nexport { A } from './a.js';",
},
], {
before: [
context => {
const { factory } = context;
return (s: ts.SourceFile) => ts.visitEachChild(s, visitor, context);
function visitor(node: ts.Node): ts.Node {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
return factory.updateImportDeclaration(
node,
node.modifiers,
node.importClause,
factory.createStringLiteral(node.moduleSpecifier.text),
node.attributes,
);
}
if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
return factory.updateExportDeclaration(
node,
node.modifiers,
node.isTypeOnly,
node.exportClause,
factory.createStringLiteral(node.moduleSpecifier.text),
node.attributes,
);
}
return node;
}
},
],
}, {
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.ESNext,
});
});