forked from babel/babel
/
namespace.ts
260 lines (241 loc) 路 7.59 KB
/
namespace.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
import { template, types as t } from "@babel/core";
import type { NodePath } from "@babel/traverse";
export default function transpileNamespace(
path: NodePath<t.TSModuleDeclaration>,
allowNamespaces: boolean,
) {
if (path.node.declare || path.node.id.type === "StringLiteral") {
path.remove();
return;
}
if (!allowNamespaces) {
throw path
.get("id")
.buildCodeFrameError(
"Namespace not marked type-only declare." +
" Non-declarative namespaces are only supported experimentally in Babel." +
" To enable and review caveats see:" +
" https://babeljs.io/docs/en/babel-plugin-transform-typescript",
);
}
const name = path.node.id.name;
const value = handleNested(path, t.cloneNode(path.node, true));
const bound = path.scope.hasOwnBinding(name);
if (path.parent.type === "ExportNamedDeclaration") {
if (!bound) {
path.parentPath.insertAfter(value);
path.replaceWith(getDeclaration(name));
path.scope.registerDeclaration(path.parentPath);
} else {
path.parentPath.replaceWith(value);
}
} else if (bound) {
path.replaceWith(value);
} else {
path.scope.registerDeclaration(
path.replaceWithMultiple([getDeclaration(name), value])[0],
);
}
}
function getDeclaration(name: string) {
return t.variableDeclaration("let", [
t.variableDeclarator(t.identifier(name)),
]);
}
function getMemberExpression(name: string, itemName: string) {
return t.memberExpression(t.identifier(name), t.identifier(itemName));
}
/**
* Convert export const foo = 1 to Namepsace.foo = 1;
*
* @param {t.VariableDeclaration} node given variable declaration, e.g. `const foo = 1`
* @param {string} name the generated unique namespace member name
* @param {*} hub An instance implements HubInterface defined in `@babel/traverse` that can throw a code frame error
*/
function handleVariableDeclaration(
node: t.VariableDeclaration,
name: string,
hub: any,
): t.Statement[] {
if (node.kind !== "const") {
throw hub.file.buildCodeFrameError(
node,
"Namespaces exporting non-const are not supported by Babel." +
" Change to const or see:" +
" https://babeljs.io/docs/en/babel-plugin-transform-typescript",
);
}
const { declarations } = node;
if (
declarations.every(
(declarator): declarator is t.VariableDeclarator & { id: t.Identifier } =>
t.isIdentifier(declarator.id),
)
) {
// `export const a = 1` transforms to `const a = N.a = 1`, the output
// is smaller than `const a = 1; N.a = a`;
for (const declarator of declarations) {
declarator.init = t.assignmentExpression(
"=",
getMemberExpression(name, declarator.id.name),
declarator.init,
);
}
return [node];
}
// Now we have pattern in declarators
// `export const [a] = 1` transforms to `const [a] = 1; N.a = a`
const bindingIdentifiers = t.getBindingIdentifiers(node);
const assignments = [];
// getBindingIdentifiers returns an object without prototype.
// eslint-disable-next-line guard-for-in
for (const idName in bindingIdentifiers) {
assignments.push(
t.assignmentExpression(
"=",
getMemberExpression(name, idName),
t.cloneNode(bindingIdentifiers[idName]),
),
);
}
return [node, t.expressionStatement(t.sequenceExpression(assignments))];
}
function buildNestedAmbiendModuleError(path: NodePath, node: t.Node) {
throw path.hub.buildError(
node,
"Ambient modules cannot be nested in other modules or namespaces.",
Error,
);
}
function handleNested(
path: NodePath,
node: t.TSModuleDeclaration,
parentExport?: t.Expression,
) {
const names = new Set();
const realName = node.id;
t.assertIdentifier(realName);
const name = path.scope.generateUid(realName.name);
const namespaceTopLevel: t.Statement[] = t.isTSModuleBlock(node.body)
? node.body.body
: // We handle `namespace X.Y {}` as if it was
// namespace X {
// export namespace Y {}
// }
[t.exportNamedDeclaration(node.body)];
for (let i = 0; i < namespaceTopLevel.length; i++) {
const subNode = namespaceTopLevel[i];
// The first switch is mainly to detect name usage. Only export
// declarations require further transformation.
switch (subNode.type) {
case "TSModuleDeclaration": {
if (!t.isIdentifier(subNode.id)) {
throw buildNestedAmbiendModuleError(path, subNode);
}
const transformed = handleNested(path, subNode);
const moduleName = subNode.id.name;
if (names.has(moduleName)) {
namespaceTopLevel[i] = transformed;
} else {
names.add(moduleName);
namespaceTopLevel.splice(
i++,
1,
getDeclaration(moduleName),
transformed,
);
}
continue;
}
case "TSEnumDeclaration":
case "FunctionDeclaration":
case "ClassDeclaration":
names.add(subNode.id.name);
continue;
case "VariableDeclaration": {
// getBindingIdentifiers returns an object without prototype.
// eslint-disable-next-line guard-for-in
for (const name in t.getBindingIdentifiers(subNode)) {
names.add(name);
}
continue;
}
default:
// Neither named declaration nor export, continue to next item.
continue;
case "ExportNamedDeclaration":
// Export declarations get parsed using the next switch.
}
if ("declare" in subNode.declaration && subNode.declaration.declare) {
continue;
}
// Transform the export declarations that occur inside of a namespace.
switch (subNode.declaration.type) {
case "TSEnumDeclaration":
case "FunctionDeclaration":
case "ClassDeclaration": {
const itemName = subNode.declaration.id.name;
names.add(itemName);
namespaceTopLevel.splice(
i++,
1,
subNode.declaration,
t.expressionStatement(
t.assignmentExpression(
"=",
getMemberExpression(name, itemName),
t.identifier(itemName),
),
),
);
break;
}
case "VariableDeclaration": {
const nodes = handleVariableDeclaration(
subNode.declaration,
name,
path.hub,
);
namespaceTopLevel.splice(i, nodes.length, ...nodes);
i += nodes.length - 1;
break;
}
case "TSModuleDeclaration": {
if (!t.isIdentifier(subNode.declaration.id)) {
throw buildNestedAmbiendModuleError(path, subNode.declaration);
}
const transformed = handleNested(
path,
subNode.declaration,
t.identifier(name),
);
const moduleName = subNode.declaration.id.name;
if (names.has(moduleName)) {
namespaceTopLevel[i] = transformed;
} else {
names.add(moduleName);
namespaceTopLevel.splice(
i++,
1,
getDeclaration(moduleName),
transformed,
);
}
}
}
}
// {}
let fallthroughValue: t.Expression = t.objectExpression([]);
if (parentExport) {
const memberExpr = t.memberExpression(parentExport, realName);
fallthroughValue = template.expression.ast`
${t.cloneNode(memberExpr)} ||
(${t.cloneNode(memberExpr)} = ${fallthroughValue})
`;
}
return template.statement.ast`
(function (${t.identifier(name)}) {
${namespaceTopLevel}
})(${realName} || (${t.cloneNode(realName)} = ${fallthroughValue}));
`;
}