forked from babel/babel
/
const-enum.ts
94 lines (82 loc) 路 2.51 KB
/
const-enum.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
import type * as t from "@babel/types";
import type { NodePath } from "@babel/traverse";
import { translateEnumValues } from "./enum";
export type NodePathConstEnum = NodePath<t.TSEnumDeclaration & { const: true }>;
export default function transpileConstEnum(
path: NodePathConstEnum,
t: typeof import("@babel/types"),
) {
const { name } = path.node.id;
const parentIsExport = path.parentPath.isExportNamedDeclaration();
let isExported = parentIsExport;
if (!isExported && t.isProgram(path.parent)) {
isExported = path.parent.body.some(
stmt =>
t.isExportNamedDeclaration(stmt) &&
stmt.exportKind !== "type" &&
!stmt.source &&
stmt.specifiers.some(
spec =>
t.isExportSpecifier(spec) &&
spec.exportKind !== "type" &&
spec.local.name === name,
),
);
}
const { enumValues: entries } = translateEnumValues(path, t);
if (isExported) {
const obj = t.objectExpression(
entries.map(([name, value]) =>
t.objectProperty(
t.isValidIdentifier(name)
? t.identifier(name)
: t.stringLiteral(name),
value,
),
),
);
if (path.scope.hasOwnBinding(name)) {
(parentIsExport ? path.parentPath : path).replaceWith(
t.expressionStatement(
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("assign")),
[path.node.id, obj],
),
),
);
} else {
path.replaceWith(
t.variableDeclaration("var", [t.variableDeclarator(path.node.id, obj)]),
);
path.scope.registerDeclaration(path);
}
return;
}
const entriesMap = new Map(entries);
// TODO: After fixing https://github.com/babel/babel/pull/11065, we can
// use path.scope.getBinding(name).referencePaths rather than doing
// a full traversal.
path.scope.path.traverse({
Scope(path) {
if (path.scope.hasOwnBinding(name)) path.skip();
},
MemberExpression(path) {
if (!t.isIdentifier(path.node.object, { name })) return;
let key: string;
if (path.node.computed) {
if (t.isStringLiteral(path.node.property)) {
key = path.node.property.value;
} else {
return;
}
} else if (t.isIdentifier(path.node.property)) {
key = path.node.property.name;
} else {
return;
}
if (!entriesMap.has(key)) return;
path.replaceWith(t.cloneNode(entriesMap.get(key)));
},
});
path.remove();
}