/
evaluation.ts
497 lines (439 loc) 路 13.2 KB
/
evaluation.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
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
import type NodePath from "./index";
import type * as t from "@babel/types";
// This file contains Babels metainterpreter that can evaluate static code.
const VALID_CALLEES = ["String", "Number", "Math"] as const;
const INVALID_METHODS = ["random"] as const;
function isValidCallee(val: string): val is typeof VALID_CALLEES[number] {
return VALID_CALLEES.includes(
// @ts-expect-error val is a string
val,
);
}
function isInvalidMethod(val: string): val is typeof INVALID_METHODS[number] {
return INVALID_METHODS.includes(
// @ts-expect-error val is a string
val,
);
}
/**
* Walk the input `node` and statically evaluate if it's truthy.
*
* Returning `true` when we're sure that the expression will evaluate to a
* truthy value, `false` if we're sure that it will evaluate to a falsy
* value and `undefined` if we aren't sure. Because of this please do not
* rely on coercion when using this method and check with === if it's false.
*
* For example do:
*
* if (t.evaluateTruthy(node) === false) falsyLogic();
*
* **AND NOT**
*
* if (!t.evaluateTruthy(node)) falsyLogic();
*
*/
export function evaluateTruthy(this: NodePath): boolean {
const res = this.evaluate();
if (res.confident) return !!res.value;
}
type State = {
confident: boolean;
deoptPath: NodePath | null;
seen: Map<t.Node, Result>;
};
type Result = {
resolved: boolean;
value?: any;
};
/**
* Deopts the evaluation
*/
function deopt(path: NodePath, state: State) {
if (!state.confident) return;
state.deoptPath = path;
state.confident = false;
}
/**
* We wrap the _evaluate method so we can track `seen` nodes, we push an item
* to the map before we actually evaluate it so we can deopt on self recursive
* nodes such as:
*
* var g = a ? 1 : 2,
* a = g * this.foo
*/
function evaluateCached(path: NodePath, state: State): any {
const { node } = path;
const { seen } = state;
if (seen.has(node)) {
const existing = seen.get(node);
if (existing.resolved) {
return existing.value;
} else {
deopt(path, state);
return;
}
} else {
const item: Result = { resolved: false };
seen.set(node, item);
const val = _evaluate(path, state);
if (state.confident) {
item.resolved = true;
item.value = val;
}
return val;
}
}
function _evaluate(path: NodePath, state: State): any {
if (!state.confident) return;
if (path.isSequenceExpression()) {
const exprs = path.get("expressions");
return evaluateCached(exprs[exprs.length - 1], state);
}
if (
path.isStringLiteral() ||
path.isNumericLiteral() ||
path.isBooleanLiteral()
) {
return path.node.value;
}
if (path.isNullLiteral()) {
return null;
}
if (path.isTemplateLiteral()) {
return evaluateQuasis(path, path.node.quasis, state);
}
if (
path.isTaggedTemplateExpression() &&
path.get("tag").isMemberExpression()
) {
const object = path.get("tag.object") as NodePath;
const {
// @ts-expect-error todo(flow->ts): possible bug, object is can be any expression and so name might be undefined
node: { name },
} = object;
const property = path.get("tag.property") as NodePath;
if (
object.isIdentifier() &&
name === "String" &&
// todo(flow->ts): was changed from getBinding(name, true)
// should this be hasBinding(name, true) as the binding is never used later?
!path.scope.getBinding(name) &&
property.isIdentifier() &&
property.node.name === "raw"
) {
return evaluateQuasis(path, path.node.quasi.quasis, state, true);
}
}
if (path.isConditionalExpression()) {
const testResult = evaluateCached(path.get("test"), state);
if (!state.confident) return;
if (testResult) {
return evaluateCached(path.get("consequent"), state);
} else {
return evaluateCached(path.get("alternate"), state);
}
}
if (path.isExpressionWrapper()) {
// TypeCastExpression, ExpressionStatement etc
return evaluateCached(path.get("expression"), state);
}
// "foo".length, "foo"[0]
if (
path.isMemberExpression() &&
!path.parentPath.isCallExpression({ callee: path.node })
) {
const property = path.get("property");
const object = path.get("object");
if (object.isLiteral()) {
// @ts-expect-error todo(flow->ts): instead of typeof - would it be better to check type of ast node?
const value = object.node.value;
const type = typeof value;
let key = null;
if (path.node.computed) {
key = evaluateCached(property, state);
if (!state.confident) return;
} else if (property.isIdentifier()) {
key = property.node.name;
}
if (
(type === "number" || type === "string") &&
key != null &&
(typeof key === "number" || typeof key === "string")
) {
return value[key];
}
}
}
if (path.isReferencedIdentifier()) {
const binding = path.scope.getBinding(path.node.name);
if (binding && binding.constantViolations.length > 0) {
return deopt(binding.path, state);
}
if (binding && path.node.start < binding.path.node.end) {
return deopt(binding.path, state);
}
if (binding?.hasValue) {
return binding.value;
} else {
if (path.node.name === "undefined") {
return binding ? deopt(binding.path, state) : undefined;
} else if (path.node.name === "Infinity") {
return binding ? deopt(binding.path, state) : Infinity;
} else if (path.node.name === "NaN") {
return binding ? deopt(binding.path, state) : NaN;
}
const resolved = path.resolve();
if (resolved === path) {
return deopt(path, state);
} else {
return evaluateCached(resolved, state);
}
}
}
if (path.isUnaryExpression({ prefix: true })) {
if (path.node.operator === "void") {
// we don't need to evaluate the argument to know what this will return
return undefined;
}
const argument = path.get("argument");
if (
path.node.operator === "typeof" &&
(argument.isFunction() || argument.isClass())
) {
return "function";
}
const arg = evaluateCached(argument, state);
if (!state.confident) return;
switch (path.node.operator) {
case "!":
return !arg;
case "+":
return +arg;
case "-":
return -arg;
case "~":
return ~arg;
case "typeof":
return typeof arg;
}
}
if (path.isArrayExpression()) {
const arr = [];
const elems: Array<NodePath> = path.get("elements");
for (const elem of elems) {
const elemValue = elem.evaluate();
if (elemValue.confident) {
arr.push(elemValue.value);
} else {
return deopt(elemValue.deopt, state);
}
}
return arr;
}
if (path.isObjectExpression()) {
const obj = {};
const props = path.get("properties");
for (const prop of props) {
if (prop.isObjectMethod() || prop.isSpreadElement()) {
return deopt(prop, state);
}
const keyPath = (prop as NodePath<t.ObjectProperty>).get("key");
let key;
// @ts-expect-error todo(flow->ts): type refinement issues ObjectMethod and SpreadElement somehow not excluded
if (prop.node.computed) {
key = keyPath.evaluate();
if (!key.confident) {
return deopt(key.deopt, state);
}
key = key.value;
} else if (keyPath.isIdentifier()) {
key = keyPath.node.name;
} else {
key = (
keyPath.node as t.StringLiteral | t.NumericLiteral | t.BigIntLiteral
).value;
}
const valuePath = (prop as NodePath<t.ObjectProperty>).get("value");
let value = valuePath.evaluate();
if (!value.confident) {
return deopt(value.deopt, state);
}
value = value.value;
// @ts-expect-error key is any type
obj[key] = value;
}
return obj;
}
if (path.isLogicalExpression()) {
// If we are confident that the left side of an && is false, or the left
// side of an || is true, we can be confident about the entire expression
const wasConfident = state.confident;
const left = evaluateCached(path.get("left"), state);
const leftConfident = state.confident;
state.confident = wasConfident;
const right = evaluateCached(path.get("right"), state);
const rightConfident = state.confident;
switch (path.node.operator) {
case "||":
// TODO consider having a "truthy type" that doesn't bail on
// left uncertainty but can still evaluate to truthy.
state.confident = leftConfident && (!!left || rightConfident);
if (!state.confident) return;
return left || right;
case "&&":
state.confident = leftConfident && (!left || rightConfident);
if (!state.confident) return;
return left && right;
case "??":
state.confident = leftConfident && (left != null || rightConfident);
if (!state.confident) return;
return left ?? right;
}
}
if (path.isBinaryExpression()) {
const left = evaluateCached(path.get("left"), state);
if (!state.confident) return;
const right = evaluateCached(path.get("right"), state);
if (!state.confident) return;
switch (path.node.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; // eslint-disable-line eqeqeq
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;
}
}
if (path.isCallExpression()) {
const callee = path.get("callee");
let context;
let func;
// Number(1);
if (
callee.isIdentifier() &&
!path.scope.getBinding(callee.node.name) &&
isValidCallee(callee.node.name)
) {
func = global[callee.node.name];
}
if (callee.isMemberExpression()) {
const object = callee.get("object");
const property = callee.get("property");
// Math.min(1, 2)
if (
object.isIdentifier() &&
property.isIdentifier() &&
isValidCallee(object.node.name) &&
!isInvalidMethod(property.node.name)
) {
context = global[object.node.name];
// @ts-expect-error property may not exist in context object
func = context[property.node.name];
}
// "abc".charCodeAt(4)
if (object.isLiteral() && property.isIdentifier()) {
// @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type (StringLiteral and NumberLiteral)
const type = typeof object.node.value;
if (type === "string" || type === "number") {
// @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type
context = object.node.value;
func = context[property.node.name];
}
}
}
if (func) {
const args = path.get("arguments").map(arg => evaluateCached(arg, state));
if (!state.confident) return;
return func.apply(context, args);
}
}
deopt(path, state);
}
function evaluateQuasis(
path: NodePath<t.TaggedTemplateExpression | t.TemplateLiteral>,
quasis: Array<any>,
state: State,
raw = false,
) {
let str = "";
let i = 0;
const exprs = path.get("expressions");
for (const elem of quasis) {
// not confident, evaluated an expression we don't like
if (!state.confident) break;
// add on element
str += raw ? elem.value.raw : elem.value.cooked;
// add on interpolated expression if it's present
const expr = exprs[i++];
if (expr) str += String(evaluateCached(expr, state));
}
if (!state.confident) return;
return str;
}
/**
* Walk the input `node` and statically evaluate it.
*
* Returns an object in the form `{ confident, value, deopt }`. `confident`
* indicates whether or not we had to drop out of evaluating the expression
* because of hitting an unknown node that we couldn't confidently find the
* value of, in which case `deopt` is the path of said node.
*
* Example:
*
* t.evaluate(parse("5 + 5")) // { confident: true, value: 10 }
* t.evaluate(parse("!true")) // { confident: true, value: false }
* t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath }
*
*/
export function evaluate(this: NodePath): {
confident: boolean;
value: any;
deopt?: NodePath;
} {
const state: State = {
confident: true,
deoptPath: null,
seen: new Map(),
};
let value = evaluateCached(this, state);
if (!state.confident) value = undefined;
return {
confident: state.confident,
deopt: state.deoptPath,
value: value,
};
}