forked from babel/babel
/
index.ts
345 lines (295 loc) · 9.57 KB
/
index.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
import type { File } from "@babel/core";
import type { NodePath, Visitor } from "@babel/traverse";
import traverse from "@babel/traverse";
import {
assignmentExpression,
cloneNode,
expressionStatement,
file,
identifier,
} from "@babel/types";
import type * as t from "@babel/types";
import helpers from "./helpers";
function makePath(path: NodePath) {
const parts = [];
for (; path.parentPath; path = path.parentPath) {
parts.push(path.key);
if (path.inList) parts.push(path.listKey);
}
return parts.reverse().join(".");
}
let FileClass: typeof File | undefined = undefined;
interface HelperMetadata {
globals: string[];
localBindingNames: string[];
dependencies: Map<t.Identifier, string>;
exportBindingAssignments: string[];
exportPath: string;
exportName: string;
importBindingsReferences: string[];
importPaths: string[];
}
/**
* Given a file AST for a given helper, get a bunch of metadata about it so that Babel can quickly render
* the helper is whatever context it is needed in.
*/
function getHelperMetadata(file: File): HelperMetadata {
const globals = new Set<string>();
const localBindingNames = new Set<string>();
// Maps imported identifier -> helper name
const dependencies = new Map<t.Identifier, string>();
let exportName: string | undefined;
let exportPath: string | undefined;
const exportBindingAssignments: string[] = [];
const importPaths: string[] = [];
const importBindingsReferences: string[] = [];
const dependencyVisitor: Visitor = {
ImportDeclaration(child) {
const name = child.node.source.value;
if (!helpers[name]) {
throw child.buildCodeFrameError(`Unknown helper ${name}`);
}
if (
child.get("specifiers").length !== 1 ||
!child.get("specifiers.0").isImportDefaultSpecifier()
) {
throw child.buildCodeFrameError(
"Helpers can only import a default value",
);
}
const bindingIdentifier = child.node.specifiers[0].local;
dependencies.set(bindingIdentifier, name);
importPaths.push(makePath(child));
},
ExportDefaultDeclaration(child) {
const decl = child.get("declaration");
if (!decl.isFunctionDeclaration() || !decl.node.id) {
throw decl.buildCodeFrameError(
"Helpers can only export named function declarations",
);
}
exportName = decl.node.id.name;
exportPath = makePath(child);
},
ExportAllDeclaration(child) {
throw child.buildCodeFrameError("Helpers can only export default");
},
ExportNamedDeclaration(child) {
throw child.buildCodeFrameError("Helpers can only export default");
},
Statement(child) {
if (child.isModuleDeclaration()) return;
child.skip();
},
};
const referenceVisitor: Visitor = {
Program(path) {
const bindings = path.scope.getAllBindings();
Object.keys(bindings).forEach(name => {
if (name === exportName) return;
if (dependencies.has(bindings[name].identifier)) return;
localBindingNames.add(name);
});
},
ReferencedIdentifier(child) {
const name = child.node.name;
const binding = child.scope.getBinding(name);
if (!binding) {
globals.add(name);
} else if (dependencies.has(binding.identifier)) {
importBindingsReferences.push(makePath(child));
}
},
AssignmentExpression(child) {
const left = child.get("left");
if (!(exportName in left.getBindingIdentifiers())) return;
if (!left.isIdentifier()) {
throw left.buildCodeFrameError(
"Only simple assignments to exports are allowed in helpers",
);
}
const binding = child.scope.getBinding(exportName);
if (binding?.scope.path.isProgram()) {
exportBindingAssignments.push(makePath(child));
}
},
};
traverse(file.ast, dependencyVisitor, file.scope);
traverse(file.ast, referenceVisitor, file.scope);
if (!exportPath) throw new Error("Helpers must have a default export.");
// Process these in reverse so that mutating the references does not invalidate any later paths in
// the list.
exportBindingAssignments.reverse();
return {
globals: Array.from(globals),
localBindingNames: Array.from(localBindingNames),
dependencies,
exportBindingAssignments,
exportPath,
exportName,
importBindingsReferences,
importPaths,
};
}
type GetDependency = (name: string) => t.Expression;
/**
* Given a helper AST and information about how it will be used, update the AST to match the usage.
*/
function permuteHelperAST(
file: File,
metadata: HelperMetadata,
id?: t.Identifier | t.MemberExpression,
localBindings?: string[],
getDependency?: GetDependency,
) {
if (localBindings && !id) {
throw new Error("Unexpected local bindings for module-based helpers.");
}
if (!id) return;
const {
localBindingNames,
dependencies,
exportBindingAssignments,
exportPath,
exportName,
importBindingsReferences,
importPaths,
} = metadata;
const dependenciesRefs: Record<string, t.Expression> = {};
dependencies.forEach((name, id) => {
dependenciesRefs[id.name] =
(typeof getDependency === "function" && getDependency(name)) || id;
});
const toRename: Record<string, string> = {};
const bindings = new Set(localBindings || []);
localBindingNames.forEach(name => {
let newName = name;
while (bindings.has(newName)) newName = "_" + newName;
if (newName !== name) toRename[name] = newName;
});
if (id.type === "Identifier" && exportName !== id.name) {
toRename[exportName] = id.name;
}
const { path } = file;
// We need to compute these in advance because removing nodes would
// invalidate the paths.
const exp: NodePath<t.ExportDefaultDeclaration> = path.get(exportPath);
const imps: NodePath<t.ImportDeclaration>[] = importPaths.map(p =>
path.get(p),
);
const impsBindingRefs: NodePath<t.Identifier>[] =
importBindingsReferences.map(p => path.get(p));
// We assert that this is a FunctionDeclaration in dependencyVisitor.
const decl = exp.get("declaration") as NodePath<t.FunctionDeclaration>;
if (id.type === "Identifier") {
exp.replaceWith(decl);
} else if (id.type === "MemberExpression") {
exportBindingAssignments.forEach(assignPath => {
const assign: NodePath<t.Expression> = path.get(assignPath);
assign.replaceWith(assignmentExpression("=", id, assign.node));
});
exp.replaceWith(decl);
path.pushContainer(
"body",
expressionStatement(
assignmentExpression("=", id, identifier(exportName)),
),
);
} else {
throw new Error("Unexpected helper format.");
}
Object.keys(toRename).forEach(name => {
path.scope.rename(name, toRename[name]);
});
for (const path of imps) path.remove();
for (const path of impsBindingRefs) {
const node = cloneNode(dependenciesRefs[path.node.name]);
path.replaceWith(node);
}
}
interface HelperData {
build: (
getDependency: GetDependency,
id: t.Identifier | t.MemberExpression,
localBindings: string[],
) => {
nodes: t.Program["body"];
globals: string[];
};
minVersion: string;
getDependencies: () => string[];
}
const helperData: Record<string, HelperData> = Object.create(null);
function loadHelper(name: string) {
if (!helperData[name]) {
const helper = helpers[name];
if (!helper) {
throw Object.assign(new ReferenceError(`Unknown helper ${name}`), {
code: "BABEL_HELPER_UNKNOWN",
helper: name,
});
}
const fn = (): File => {
if (!process.env.BABEL_8_BREAKING) {
if (!FileClass) {
const fakeFile = { ast: file(helper.ast()), path: null } as File;
traverse(fakeFile.ast, {
Program: path => (fakeFile.path = path).stop(),
});
return fakeFile;
}
}
return new FileClass(
{ filename: `babel-helper://${name}` },
{
ast: file(helper.ast()),
code: "[internal Babel helper code]",
inputMap: null,
},
);
};
// We compute the helper metadata lazily, so that we skip that
// work if we only need the `.minVersion` (for example because
// of a call to `.availableHelper` when `@babel/rutime`).
let metadata: HelperMetadata | null = null;
helperData[name] = {
minVersion: helper.minVersion,
build(getDependency, id, localBindings) {
const file = fn();
metadata ||= getHelperMetadata(file);
permuteHelperAST(file, metadata, id, localBindings, getDependency);
return {
nodes: file.ast.program.body,
globals: metadata.globals,
};
},
getDependencies() {
metadata ||= getHelperMetadata(fn());
return Array.from(metadata.dependencies.values());
},
};
}
return helperData[name];
}
export function get(
name: string,
getDependency?: GetDependency,
id?: t.Identifier | t.MemberExpression,
localBindings?: string[],
) {
return loadHelper(name).build(getDependency, id, localBindings);
}
export function minVersion(name: string) {
return loadHelper(name).minVersion;
}
export function getDependencies(name: string): ReadonlyArray<string> {
return loadHelper(name).getDependencies();
}
export function ensure(name: string, newFileClass: typeof File) {
// We inject the File class here rather than importing it to avoid
// circular dependencies between @babel/core and @babel/helpers.
FileClass ||= newFileClass;
loadHelper(name);
}
export const list = Object.keys(helpers).map(name => name.replace(/^_/, ""));
export default get;