-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
get-static-value.js
538 lines (489 loc) · 16.7 KB
/
get-static-value.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/* globals BigInt, globalThis, global, self, window */
import { findVariable } from "./find-variable"
const globalObject =
typeof globalThis !== "undefined"
? globalThis
: typeof self !== "undefined"
? self
: typeof window !== "undefined"
? window
: typeof global !== "undefined"
? global
: {}
const builtinNames = Object.freeze(
new Set([
"Array",
"ArrayBuffer",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
"decodeURI",
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"escape",
"Float32Array",
"Float64Array",
"Function",
"Infinity",
"Int16Array",
"Int32Array",
"Int8Array",
"isFinite",
"isNaN",
"isPrototypeOf",
"JSON",
"Map",
"Math",
"NaN",
"Number",
"Object",
"parseFloat",
"parseInt",
"Promise",
"Proxy",
"Reflect",
"RegExp",
"Set",
"String",
"Symbol",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"undefined",
"unescape",
"WeakMap",
"WeakSet",
])
)
const callAllowed = new Set(
[
Array.isArray,
typeof BigInt === "function" ? BigInt : undefined,
Boolean,
Date,
Date.parse,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
escape,
isFinite,
isNaN,
isPrototypeOf,
...Object.getOwnPropertyNames(Math)
.map(k => Math[k])
.filter(f => typeof f === "function"),
Number,
Number.isFinite,
Number.isNaN,
Number.parseFloat,
Number.parseInt,
Object,
Object.entries,
Object.is,
Object.isExtensible,
Object.isFrozen,
Object.isSealed,
Object.keys,
Object.values,
parseFloat,
parseInt,
RegExp,
String,
String.fromCharCode,
String.fromCodePoint,
String.raw,
Symbol,
Symbol.for,
Symbol.keyFor,
unescape,
].filter(f => typeof f === "function")
)
const callPassThrough = new Set([
Object.freeze,
Object.preventExtensions,
Object.seal,
])
/**
* Get the property descriptor.
* @param {object} object The object to get.
* @param {string|number|symbol} name The property name to get.
*/
function getPropertyDescriptor(object, name) {
let x = object
while ((typeof x === "object" || typeof x === "function") && x !== null) {
const d = Object.getOwnPropertyDescriptor(x, name)
if (d) {
return d
}
x = Object.getPrototypeOf(x)
}
return null
}
/**
* Check if a property is getter or not.
* @param {object} object The object to check.
* @param {string|number|symbol} name The property name to check.
*/
function isGetter(object, name) {
const d = getPropertyDescriptor(object, name)
return d != null && d.get != null
}
/**
* Get the element values of a given node list.
* @param {Node[]} nodeList The node list to get values.
* @param {Scope|undefined} initialScope The initial scope to find variables.
* @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
*/
function getElementValues(nodeList, initialScope) {
const valueList = []
for (let i = 0; i < nodeList.length; ++i) {
const elementNode = nodeList[i]
if (elementNode == null) {
valueList.length = i + 1
} else if (elementNode.type === "SpreadElement") {
const argument = getStaticValueR(elementNode.argument, initialScope)
if (argument == null) {
return null
}
valueList.push(...argument.value)
} else {
const element = getStaticValueR(elementNode, initialScope)
if (element == null) {
return null
}
valueList.push(element.value)
}
}
return valueList
}
const operations = Object.freeze({
ArrayExpression(node, initialScope) {
const elements = getElementValues(node.elements, initialScope)
return elements != null ? { value: elements } : null
},
AssignmentExpression(node, initialScope) {
if (node.operator === "=") {
return getStaticValueR(node.right, initialScope)
}
return null
},
//eslint-disable-next-line complexity
BinaryExpression(node, initialScope) {
if (node.operator === "in" || node.operator === "instanceof") {
// Not supported.
return null
}
const left = getStaticValueR(node.left, initialScope)
const right = getStaticValueR(node.right, initialScope)
if (left != null && right != null) {
switch (node.operator) {
case "==":
return { value: left.value == right.value } //eslint-disable-line eqeqeq
case "!=":
return { value: left.value != right.value } //eslint-disable-line eqeqeq
case "===":
return { value: left.value === right.value }
case "!==":
return { value: left.value !== right.value }
case "<":
return { value: left.value < right.value }
case "<=":
return { value: left.value <= right.value }
case ">":
return { value: left.value > right.value }
case ">=":
return { value: left.value >= right.value }
case "<<":
return { value: left.value << right.value }
case ">>":
return { value: left.value >> right.value }
case ">>>":
return { value: left.value >>> right.value }
case "+":
return { value: left.value + right.value }
case "-":
return { value: left.value - right.value }
case "*":
return { value: left.value * right.value }
case "/":
return { value: left.value / right.value }
case "%":
return { value: left.value % right.value }
case "**":
return { value: Math.pow(left.value, right.value) }
case "|":
return { value: left.value | right.value }
case "^":
return { value: left.value ^ right.value }
case "&":
return { value: left.value & right.value }
// no default
}
}
return null
},
CallExpression(node, initialScope) {
const calleeNode = node.callee
const args = getElementValues(node.arguments, initialScope)
if (args != null) {
if (calleeNode.type === "MemberExpression") {
const object = getStaticValueR(calleeNode.object, initialScope)
if (object != null) {
if (
object.value == null &&
(object.optional || node.optional)
) {
return { value: undefined, optional: true }
}
const property = calleeNode.computed
? getStaticValueR(calleeNode.property, initialScope)
: { value: calleeNode.property.name }
if (property != null) {
const receiver = object.value
const methodName = property.value
if (callAllowed.has(receiver[methodName])) {
return { value: receiver[methodName](...args) }
}
if (callPassThrough.has(receiver[methodName])) {
return { value: args[0] }
}
}
}
} else {
const callee = getStaticValueR(calleeNode, initialScope)
if (callee != null) {
if (callee.value == null && node.optional) {
return { value: undefined, optional: true }
}
const func = callee.value
if (callAllowed.has(func)) {
return { value: func(...args) }
}
if (callPassThrough.has(func)) {
return { value: args[0] }
}
}
}
}
return null
},
ConditionalExpression(node, initialScope) {
const test = getStaticValueR(node.test, initialScope)
if (test != null) {
return test.value
? getStaticValueR(node.consequent, initialScope)
: getStaticValueR(node.alternate, initialScope)
}
return null
},
ExpressionStatement(node, initialScope) {
return getStaticValueR(node.expression, initialScope)
},
Identifier(node, initialScope) {
if (initialScope != null) {
const variable = findVariable(initialScope, node)
// Built-in globals.
if (
variable != null &&
variable.defs.length === 0 &&
builtinNames.has(variable.name) &&
variable.name in globalObject
) {
return { value: globalObject[variable.name] }
}
// Constants.
if (variable != null && variable.defs.length === 1) {
const def = variable.defs[0]
if (
def.parent &&
def.parent.kind === "const" &&
// TODO(mysticatea): don't support destructuring here.
def.node.id.type === "Identifier"
) {
return getStaticValueR(def.node.init, initialScope)
}
}
}
return null
},
Literal(node) {
//istanbul ignore if : this is implementation-specific behavior.
if ((node.regex != null || node.bigint != null) && node.value == null) {
// It was a RegExp/BigInt literal, but Node.js didn't support it.
return null
}
return { value: node.value }
},
LogicalExpression(node, initialScope) {
const left = getStaticValueR(node.left, initialScope)
if (left != null) {
if (
(node.operator === "||" && Boolean(left.value) === true) ||
(node.operator === "&&" && Boolean(left.value) === false) ||
(node.operator === "??" && left.value != null)
) {
return left
}
const right = getStaticValueR(node.right, initialScope)
if (right != null) {
return right
}
}
return null
},
MemberExpression(node, initialScope) {
const object = getStaticValueR(node.object, initialScope)
if (object != null) {
if (object.value == null && (object.optional || node.optional)) {
return { value: undefined, optional: true }
}
const property = node.computed
? getStaticValueR(node.property, initialScope)
: { value: node.property.name }
if (property != null && !isGetter(object.value, property.value)) {
return { value: object.value[property.value] }
}
}
return null
},
ChainExpression(node, initialScope) {
const expression = getStaticValueR(node.expression, initialScope)
if (expression != null) {
return { value: expression.value }
}
return null
},
NewExpression(node, initialScope) {
const callee = getStaticValueR(node.callee, initialScope)
const args = getElementValues(node.arguments, initialScope)
if (callee != null && args != null) {
const Func = callee.value
if (callAllowed.has(Func)) {
return { value: new Func(...args) }
}
}
return null
},
ObjectExpression(node, initialScope) {
const object = {}
for (const propertyNode of node.properties) {
if (propertyNode.type === "Property") {
if (propertyNode.kind !== "init") {
return null
}
const key = propertyNode.computed
? getStaticValueR(propertyNode.key, initialScope)
: { value: propertyNode.key.name }
const value = getStaticValueR(propertyNode.value, initialScope)
if (key == null || value == null) {
return null
}
object[key.value] = value.value
} else if (
propertyNode.type === "SpreadElement" ||
propertyNode.type === "ExperimentalSpreadProperty"
) {
const argument = getStaticValueR(
propertyNode.argument,
initialScope
)
if (argument == null) {
return null
}
Object.assign(object, argument.value)
} else {
return null
}
}
return { value: object }
},
SequenceExpression(node, initialScope) {
const last = node.expressions[node.expressions.length - 1]
return getStaticValueR(last, initialScope)
},
TaggedTemplateExpression(node, initialScope) {
const tag = getStaticValueR(node.tag, initialScope)
const expressions = getElementValues(
node.quasi.expressions,
initialScope
)
if (tag != null && expressions != null) {
const func = tag.value
const strings = node.quasi.quasis.map(q => q.value.cooked)
strings.raw = node.quasi.quasis.map(q => q.value.raw)
if (func === String.raw) {
return { value: func(strings, ...expressions) }
}
}
return null
},
TemplateLiteral(node, initialScope) {
const expressions = getElementValues(node.expressions, initialScope)
if (expressions != null) {
let value = node.quasis[0].value.cooked
for (let i = 0; i < expressions.length; ++i) {
value += expressions[i]
value += node.quasis[i + 1].value.cooked
}
return { value }
}
return null
},
UnaryExpression(node, initialScope) {
if (node.operator === "delete") {
// Not supported.
return null
}
if (node.operator === "void") {
return { value: undefined }
}
const arg = getStaticValueR(node.argument, initialScope)
if (arg != null) {
switch (node.operator) {
case "-":
return { value: -arg.value }
case "+":
return { value: +arg.value } //eslint-disable-line no-implicit-coercion
case "!":
return { value: !arg.value }
case "~":
return { value: ~arg.value }
case "typeof":
return { value: typeof arg.value }
// no default
}
}
return null
},
})
/**
* Get the value of a given node if it's a static value.
* @param {Node} node The node to get.
* @param {Scope|undefined} initialScope The scope to start finding variable.
* @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
*/
function getStaticValueR(node, initialScope) {
if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
return operations[node.type](node, initialScope)
}
return null
}
/**
* Get the value of a given node if it's a static value.
* @param {Node} node The node to get.
* @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
* @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
*/
export function getStaticValue(node, initialScope = null) {
try {
return getStaticValueR(node, initialScope)
} catch (_error) {
return null
}
}