forked from babel/babel
/
enum.js
227 lines (204 loc) 路 5.53 KB
/
enum.js
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
import assert from "assert";
import { template } from "@babel/core";
export default function transpileEnum(path, t) {
const { node } = path;
if (node.declare) {
path.remove();
return;
}
if (node.const) {
throw path.buildCodeFrameError("'const' enums are not supported.");
}
const name = node.id.name;
const fill = enumFill(path, t, node.id);
switch (path.parent.type) {
case "BlockStatement":
case "ExportNamedDeclaration":
case "Program": {
path.insertAfter(fill);
if (seen(path.parentPath)) {
path.remove();
} else {
const isGlobal = t.isProgram(path.parent); // && !path.parent.body.some(t.isModuleDeclaration);
path.scope.registerDeclaration(
path.replaceWith(makeVar(node.id, t, isGlobal ? "var" : "let"))[0],
);
}
break;
}
default:
throw new Error(`Unexpected enum parent '${path.parent.type}`);
}
function seen(parentPath: Path<Node>) {
if (parentPath.isExportDeclaration()) {
return seen(parentPath.parentPath);
}
if (parentPath.getData(name)) {
return true;
} else {
parentPath.setData(name, true);
return false;
}
}
}
function makeVar(id, t, kind): VariableDeclaration {
return t.variableDeclaration(kind, [t.variableDeclarator(id)]);
}
const buildEnumWrapper = template(`
(function (ID) {
ASSIGNMENTS;
})(ID || (ID = {}));
`);
const buildStringAssignment = template(`
ENUM["NAME"] = VALUE;
`);
const buildNumericAssignment = template(`
ENUM[ENUM["NAME"] = VALUE] = "NAME";
`);
const buildEnumMember = (isString, options) =>
(isString ? buildStringAssignment : buildNumericAssignment)(options);
/**
* Generates the statement that fills in the variable declared by the enum.
* `(function (E) { ... assignments ... })(E || (E = {}));`
*/
function enumFill(path, t, id) {
const x = translateEnumValues(path, t);
const assignments = x.map(([memberName, memberValue]) =>
buildEnumMember(t.isStringLiteral(memberValue), {
ENUM: t.cloneNode(id),
NAME: memberName,
VALUE: memberValue,
}),
);
return buildEnumWrapper({
ID: t.cloneNode(id),
ASSIGNMENTS: assignments,
});
}
/**
* Maps the name of an enum member to its value.
* We keep track of the previous enum members so you can write code like:
* enum E {
* X = 1 << 0,
* Y = 1 << 1,
* Z = X | Y,
* }
*/
type PreviousEnumMembers = { [name: string]: number | string };
function translateEnumValues(path, t) {
const seen: PreviousEnumMembers = Object.create(null);
// Start at -1 so the first enum member is its increment, 0.
let prev: number | typeof undefined = -1;
return path.node.members.map(member => {
const name = t.isIdentifier(member.id) ? member.id.name : member.id.value;
const initializer = member.initializer;
let value: Expression;
if (initializer) {
const constValue = evaluate(initializer, seen);
if (constValue !== undefined) {
seen[name] = constValue;
if (typeof constValue === "number") {
value = t.numericLiteral(constValue);
prev = constValue;
} else {
assert(typeof constValue === "string");
value = t.stringLiteral(constValue);
prev = undefined;
}
} else {
value = initializer;
prev = undefined;
}
} else {
if (prev !== undefined) {
prev++;
value = t.numericLiteral(prev);
seen[name] = prev;
} else {
throw path.buildCodeFrameError("Enum member must have initializer.");
}
}
return [name, value];
});
}
// Based on the TypeScript repository's `evalConstant` in `checker.ts`.
function evaluate(
expr,
seen: PreviousEnumMembers,
): number | string | typeof undefined {
if (expr.type === "StringLiteral") {
return expr.value;
}
return evalConstant(expr);
function evalConstant(expr): number | typeof undefined {
switch (expr.type) {
case "UnaryExpression":
return evalUnaryExpression(expr);
case "BinaryExpression":
return evalBinaryExpression(expr);
case "NumericLiteral":
return expr.value;
case "ParenthesizedExpression":
return evalConstant(expr.expression);
case "Identifier":
return seen[expr.name];
default:
return undefined;
}
}
function evalUnaryExpression({
argument,
operator,
}): number | typeof undefined {
const value = evalConstant(argument);
if (value === undefined) {
return undefined;
}
switch (operator) {
case "+":
return value;
case "-":
return -value;
case "~":
return ~value;
default:
return undefined;
}
}
function evalBinaryExpression(expr): number | typeof undefined {
const left = evalConstant(expr.left);
if (left === undefined) {
return undefined;
}
const right = evalConstant(expr.right);
if (right === undefined) {
return undefined;
}
switch (expr.operator) {
case "|":
return left | right;
case "&":
return left & right;
case ">>":
return left >> right;
case ">>>":
return left >>> right;
case "<<":
return left << right;
case "^":
return left ^ right;
case "*":
return left * right;
case "/":
return left / right;
case "+":
return left + right;
case "-":
return left - right;
case "%":
return left % right;
default:
return undefined;
}
}
}