forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converters.js
312 lines (254 loc) · 7.38 KB
/
converters.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
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
import isPlainObject from "lodash/isPlainObject";
import isNumber from "lodash/isNumber";
import isRegExp from "lodash/isRegExp";
import isString from "lodash/isString";
import type { Scope } from "babel-traverse";
import * as t from "./index";
export function toComputedKey(node: Object, key: Object = node.key || node.property): Object {
if (!node.computed) {
if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
}
return key;
}
/**
* Turn an array of statement `nodes` into a `SequenceExpression`.
*
* Variable declarations are turned into simple assignments and their
* declarations hoisted to the top of the current scope.
*
* Expression statements are just resolved to their expression.
*/
export function toSequenceExpression(nodes: Array<Object>, scope: Scope): ?Object {
if (!nodes || !nodes.length) return;
let declars = [];
let bailed = false;
let result = convert(nodes);
if (bailed) return;
for (let i = 0; i < declars.length; i++) {
scope.push(declars[i]);
}
return result;
function convert(nodes) {
let ensureLastUndefined = false;
let exprs = [];
for (let node of (nodes: Array)) {
if (t.isExpression(node)) {
exprs.push(node);
} else if (t.isExpressionStatement(node)) {
exprs.push(node.expression);
} else if (t.isVariableDeclaration(node)) {
if (node.kind !== "var") return bailed = true; // bailed
for (let declar of (node.declarations: Array)) {
let bindings = t.getBindingIdentifiers(declar);
for (let key in bindings) {
declars.push({
kind: node.kind,
id: bindings[key]
});
}
if (declar.init) {
exprs.push(t.assignmentExpression("=", declar.id, declar.init));
}
}
ensureLastUndefined = true;
continue;
} else if (t.isIfStatement(node)) {
let consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode();
let alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode();
if (!consequent || !alternate) return bailed = true;
exprs.push(t.conditionalExpression(node.test, consequent, alternate));
} else if (t.isBlockStatement(node)) {
exprs.push(convert(node.body));
} else if (t.isEmptyStatement(node)) {
// empty statement so ensure the last item is undefined if we're last
ensureLastUndefined = true;
continue;
} else {
// bailed, we can't turn this statement into an expression
return bailed = true;
}
ensureLastUndefined = false;
}
if (ensureLastUndefined || exprs.length === 0) {
exprs.push(scope.buildUndefinedNode());
}
//
if (exprs.length === 1) {
return exprs[0];
} else {
return t.sequenceExpression(exprs);
}
}
}
export function toKeyAlias(node: Object, key: Object = node.key): string {
let alias;
if (node.kind === "method") {
return toKeyAlias.increment() + "";
} else if (t.isIdentifier(key)) {
alias = key.name;
} else if (t.isStringLiteral(key)) {
alias = JSON.stringify(key.value);
} else {
alias = JSON.stringify(t.removePropertiesDeep(t.cloneDeep(key)));
}
if (node.computed) {
alias = `[${alias}]`;
}
if (node.static) {
alias = `static:${alias}`;
}
return alias;
}
toKeyAlias.uid = 0;
toKeyAlias.increment = function () {
if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) {
return toKeyAlias.uid = 0;
} else {
return toKeyAlias.uid++;
}
};
export function toIdentifier(name: string): string {
name = name + "";
// replace all non-valid identifiers with dashes
name = name.replace(/[^a-zA-Z0-9$_]/g, "-");
// remove all dashes and numbers from start of name
name = name.replace(/^[-0-9]+/, "");
// camel case
name = name.replace(/[-\s]+(.)?/g, function (match, c) {
return c ? c.toUpperCase() : "";
});
if (!t.isValidIdentifier(name)) {
name = `_${name}`;
}
return name || "_";
}
export function toBindingIdentifierName(name: string): string {
name = toIdentifier(name);
if (name === "eval" || name === "arguments") name = "_" + name;
return name;
}
/**
* [Please add a description.]
* @returns {Object|Boolean}
*/
export function toStatement(node: Object, ignore?: boolean) {
if (t.isStatement(node)) {
return node;
}
let mustHaveId = false;
let newType;
if (t.isClass(node)) {
mustHaveId = true;
newType = "ClassDeclaration";
} else if (t.isFunction(node)) {
mustHaveId = true;
newType = "FunctionDeclaration";
} else if (t.isAssignmentExpression(node)) {
return t.expressionStatement(node);
}
if (mustHaveId && !node.id) {
newType = false;
}
if (!newType) {
if (ignore) {
return false;
} else {
throw new Error(`cannot turn ${node.type} to a statement`);
}
}
node.type = newType;
return node;
}
export function toExpression(node: Object): Object {
if (t.isExpressionStatement(node)) {
node = node.expression;
}
// return unmodified node
// important for things like ArrowFunctions where
// type change from ArrowFunction to FunctionExpression
// produces bugs like -> `()=>a` to `function () a`
// without generating a BlockStatement for it
// ref: https://github.com/babel/babili/issues/130
if (t.isExpression(node)) {
return node;
}
// convert all classes and functions
// ClassDeclaration -> ClassExpression
// FunctionDeclaration, ObjectMethod, ClassMethod -> FunctionExpression
if (t.isClass(node)) {
node.type = "ClassExpression";
} else if (t.isFunction(node)) {
node.type = "FunctionExpression";
}
// if it's still not an expression
if (!t.isExpression(node)) {
throw new Error(`cannot turn ${node.type} to an expression`);
}
return node;
}
export function toBlock(node: Object, parent: Object): Object {
if (t.isBlockStatement(node)) {
return node;
}
if (t.isEmptyStatement(node)) {
node = [];
}
if (!Array.isArray(node)) {
if (!t.isStatement(node)) {
if (t.isFunction(parent)) {
node = t.returnStatement(node);
} else {
node = t.expressionStatement(node);
}
}
node = [node];
}
return t.blockStatement(node);
}
export function valueToNode(value: any): Object {
// undefined
if (value === undefined) {
return t.identifier("undefined");
}
// boolean
if (value === true || value === false) {
return t.booleanLiteral(value);
}
// null
if (value === null) {
return t.nullLiteral();
}
// strings
if (isString(value)) {
return t.stringLiteral(value);
}
// numbers
if (isNumber(value)) {
return t.numericLiteral(value);
}
// regexes
if (isRegExp(value)) {
let pattern = value.source;
let flags = value.toString().match(/\/([a-z]+|)$/)[1];
return t.regExpLiteral(pattern, flags);
}
// array
if (Array.isArray(value)) {
return t.arrayExpression(value.map(t.valueToNode));
}
// object
if (isPlainObject(value)) {
let props = [];
for (let key in value) {
let nodeKey;
if (t.isValidIdentifier(key)) {
nodeKey = t.identifier(key);
} else {
nodeKey = t.stringLiteral(key);
}
props.push(t.objectProperty(nodeKey, t.valueToNode(value[key])));
}
return t.objectExpression(props);
}
throw new Error("don't know how to turn this value into a node");
}