Debian Codegraph @

packages/babel-traverse/src/path/evaluation.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 import type NodePath from "./index";
2 import type * as t from "@babel/types";
3
4 // This file contains Babels metainterpreter that can evaluate static code.
5
6 const VALID_CALLEES = ["String", "Number", "Math"] as const;
7 const INVALID_METHODS = ["random"] as const;
8
9 function isValidCallee(val: string): val is typeof VALID_CALLEES[number] {
10 return VALID_CALLEES.includes(
11 // @ts-expect-error val is a string
12 val,
13 );
14 }
15
16 function isInvalidMethod(val: string): val is typeof INVALID_METHODS[number] {
17 return INVALID_METHODS.includes(
18 // @ts-expect-error val is a string
19 val,
20 );
21 }
22
23 /**
24 * Walk the input `node` and statically evaluate if it's truthy.
25 *
26 * Returning `true` when we're sure that the expression will evaluate to a
27 * truthy value, `false` if we're sure that it will evaluate to a falsy
28 * value and `undefined` if we aren't sure. Because of this please do not
29 * rely on coercion when using this method and check with === if it's false.
30 *
31 * For example do:
32 *
33 * if (t.evaluateTruthy(node) === false) falsyLogic();
34 *
35 * **AND NOT**
36 *
37 * if (!t.evaluateTruthy(node)) falsyLogic();
38 *
39 */
40
41 export function evaluateTruthy(this: NodePath): boolean {
42 const res = this.evaluate();
43 if (res.confident) return !!res.value;
44 }
45
46 type State = {
47 confident: boolean;
48 deoptPath: NodePath | null;
49 seen: Map<t.Node, Result>;
50 };
51
52 type Result = {
53 resolved: boolean;
54 value?: any;
55 };
56 /**
57 * Deopts the evaluation
58 */
59 function deopt(path: NodePath, state: State) {
60 if (!state.confident) return;
61 state.deoptPath = path;
62 state.confident = false;
63 }
64
65 /**
66 * We wrap the _evaluate method so we can track `seen` nodes, we push an item
67 * to the map before we actually evaluate it so we can deopt on self recursive
68 * nodes such as:
69 *
70 * var g = a ? 1 : 2,
71 * a = g * this.foo
72 */
73 function evaluateCached(path: NodePath, state: State): any {
74 const { node } = path;
75 const { seen } = state;
76
77 if (seen.has(node)) {
78 const existing = seen.get(node);
79 if (existing.resolved) {
80 return existing.value;
81 } else {
82 deopt(path, state);
83 return;
84 }
85 } else {
86 const item: Result = { resolved: false };
87 seen.set(node, item);
88
89 const val = _evaluate(path, state);
90 if (state.confident) {
91 item.resolved = true;
92 item.value = val;
93 }
94 return val;
95 }
96 }
97
98 function _evaluate(path: NodePath, state: State): any {
99 if (!state.confident) return;
100
101 if (path.isSequenceExpression()) {
102 const exprs = path.get("expressions");
103 return evaluateCached(exprs[exprs.length - 1], state);
104 }
105
106 if (
107 path.isStringLiteral() ||
108 path.isNumericLiteral() ||
109 path.isBooleanLiteral()
110 ) {
111 return path.node.value;
112 }
113
114 if (path.isNullLiteral()) {
115 return null;
116 }
117
118 if (path.isTemplateLiteral()) {
119 return evaluateQuasis(path, path.node.quasis, state);
120 }
121
122 if (
123 path.isTaggedTemplateExpression() &&
124 path.get("tag").isMemberExpression()
125 ) {
126 const object = path.get("tag.object") as NodePath;
127 const {
128 // @ts-expect-error todo(flow->ts): possible bug, object is can be any expression and so name might be undefined
129 node: { name },
130 } = object;
131 const property = path.get("tag.property") as NodePath;
132
133 if (
134 object.isIdentifier() &&
135 name === "String" &&
136 // todo(flow->ts): was changed from getBinding(name, true)
137 // should this be hasBinding(name, true) as the binding is never used later?
138 !path.scope.getBinding(name) &&
139 property.isIdentifier() &&
140 property.node.name === "raw"
141 ) {
142 return evaluateQuasis(path, path.node.quasi.quasis, state, true);
143 }
144 }
145
146 if (path.isConditionalExpression()) {
147 const testResult = evaluateCached(path.get("test"), state);
148 if (!state.confident) return;
149 if (testResult) {
150 return evaluateCached(path.get("consequent"), state);
151 } else {
152 return evaluateCached(path.get("alternate"), state);
153 }
154 }
155
156 if (path.isExpressionWrapper()) {
157 // TypeCastExpression, ExpressionStatement etc
158 return evaluateCached(path.get("expression"), state);
159 }
160
161 // "foo".length, "foo"[0]
162 if (
163 path.isMemberExpression() &&
164 !path.parentPath.isCallExpression({ callee: path.node })
165 ) {
166 const property = path.get("property");
167 const object = path.get("object");
168
169 if (object.isLiteral()) {
170 // @ts-expect-error todo(flow->ts): instead of typeof - would it be better to check type of ast node?
171 const value = object.node.value;
172 const type = typeof value;
173
174 let key = null;
175 if (path.node.computed) {
176 key = evaluateCached(property, state);
177 if (!state.confident) return;
178 } else if (property.isIdentifier()) {
179 key = property.node.name;
180 }
181 if (
182 (type === "number" || type === "string") &&
183 key != null &&
184 (typeof key === "number" || typeof key === "string")
185 ) {
186 return value[key];
187 }
188 }
189 }
190
191 if (path.isReferencedIdentifier()) {
192 const binding = path.scope.getBinding(path.node.name);
193
194 if (binding && binding.constantViolations.length > 0) {
195 return deopt(binding.path, state);
196 }
197
198 if (binding && path.node.start < binding.path.node.end) {
199 return deopt(binding.path, state);
200 }
201
202 if (binding?.hasValue) {
203 return binding.value;
204 } else {
205 if (path.node.name === "undefined") {
206 return binding ? deopt(binding.path, state) : undefined;
207 } else if (path.node.name === "Infinity") {
208 return binding ? deopt(binding.path, state) : Infinity;
209 } else if (path.node.name === "NaN") {
210 return binding ? deopt(binding.path, state) : NaN;
211 }
212
213 const resolved = path.resolve();
214 if (resolved === path) {
215 return deopt(path, state);
216 } else {
217 return evaluateCached(resolved, state);
218 }
219 }
220 }
221
222 if (path.isUnaryExpression({ prefix: true })) {
223 if (path.node.operator === "void") {
224 // we don't need to evaluate the argument to know what this will return
225 return undefined;
226 }
227
228 const argument = path.get("argument");
229 if (
230 path.node.operator === "typeof" &&
231 (argument.isFunction() || argument.isClass())
232 ) {
233 return "function";
234 }
235
236 const arg = evaluateCached(argument, state);
237 if (!state.confident) return;
238 switch (path.node.operator) {
239 case "!":
240 return !arg;
241 case "+":
242 return +arg;
243 case "-":
244 return -arg;
245 case "~":
246 return ~arg;
247 case "typeof":
248 return typeof arg;
249 }
250 }
251
252 if (path.isArrayExpression()) {
253 const arr = [];
254 const elems: Array<NodePath> = path.get("elements");
255 for (const elem of elems) {
256 const elemValue = elem.evaluate();
257
258 if (elemValue.confident) {
259 arr.push(elemValue.value);
260 } else {
261 return deopt(elemValue.deopt, state);
262 }
263 }
264 return arr;
265 }
266
267 if (path.isObjectExpression()) {
268 const obj = {};
269 const props = path.get("properties");
270 for (const prop of props) {
271 if (prop.isObjectMethod() || prop.isSpreadElement()) {
272 return deopt(prop, state);
273 }
274 const keyPath = (prop as NodePath<t.ObjectProperty>).get("key");
275 let key;
276 // @ts-expect-error todo(flow->ts): type refinement issues ObjectMethod and SpreadElement somehow not excluded
277 if (prop.node.computed) {
278 key = keyPath.evaluate();
279 if (!key.confident) {
280 return deopt(key.deopt, state);
281 }
282 key = key.value;
283 } else if (keyPath.isIdentifier()) {
284 key = keyPath.node.name;
285 } else {
286 key = (
287 keyPath.node as t.StringLiteral | t.NumericLiteral | t.BigIntLiteral
288 ).value;
289 }
290 const valuePath = (prop as NodePath<t.ObjectProperty>).get("value");
291 let value = valuePath.evaluate();
292 if (!value.confident) {
293 return deopt(value.deopt, state);
294 }
295 value = value.value;
296 // @ts-expect-error key is any type
297 obj[key] = value;
298 }
299 return obj;
300 }
301
302 if (path.isLogicalExpression()) {
303 // If we are confident that the left side of an && is false, or the left
304 // side of an || is true, we can be confident about the entire expression
305 const wasConfident = state.confident;
306 const left = evaluateCached(path.get("left"), state);
307 const leftConfident = state.confident;
308 state.confident = wasConfident;
309 const right = evaluateCached(path.get("right"), state);
310 const rightConfident = state.confident;
311
312 switch (path.node.operator) {
313 case "||":
314 // TODO consider having a "truthy type" that doesn't bail on
315 // left uncertainty but can still evaluate to truthy.
316 state.confident = leftConfident && (!!left || rightConfident);
317 if (!state.confident) return;
318
319 return left || right;
320 case "&&":
321 state.confident = leftConfident && (!left || rightConfident);
322 if (!state.confident) return;
323
324 return left && right;
325 case "??":
326 state.confident = leftConfident && (left != null || rightConfident);
327 if (!state.confident) return;
328
329 return left ?? right;
330 }
331 }
332
333 if (path.isBinaryExpression()) {
334 const left = evaluateCached(path.get("left"), state);
335 if (!state.confident) return;
336 const right = evaluateCached(path.get("right"), state);
337 if (!state.confident) return;
338
339 switch (path.node.operator) {
340 case "-":
341 return left - right;
342 case "+":
343 return left + right;
344 case "/":
345 return left / right;
346 case "*":
347 return left * right;
348 case "%":
349 return left % right;
350 case "**":
351 return left ** right;
352 case "<":
353 return left < right;
354 case ">":
355 return left > right;
356 case "<=":
357 return left <= right;
358 case ">=":
359 return left >= right;
360 case "==":
361 return left == right; // eslint-disable-line eqeqeq
362 case "!=":
363 return left != right;
364 case "===":
365 return left === right;
366 case "!==":
367 return left !== right;
368 case "|":
369 return left | right;
370 case "&":
371 return left & right;
372 case "^":
373 return left ^ right;
374 case "<<":
375 return left << right;
376 case ">>":
377 return left >> right;
378 case ">>>":
379 return left >>> right;
380 }
381 }
382
383 if (path.isCallExpression()) {
384 const callee = path.get("callee");
385 let context;
386 let func;
387
388 // Number(1);
389 if (
390 callee.isIdentifier() &&
391 !path.scope.getBinding(callee.node.name) &&
392 isValidCallee(callee.node.name)
393 ) {
394 func = global[callee.node.name];
395 }
396
397 if (callee.isMemberExpression()) {
398 const object = callee.get("object");
399 const property = callee.get("property");
400
401 // Math.min(1, 2)
402 if (
403 object.isIdentifier() &&
404 property.isIdentifier() &&
405 isValidCallee(object.node.name) &&
406 !isInvalidMethod(property.node.name)
407 ) {
408 context = global[object.node.name];
409 // @ts-expect-error property may not exist in context object
410 func = context[property.node.name];
411 }
412
413 // "abc".charCodeAt(4)
414 if (object.isLiteral() && property.isIdentifier()) {
415 // @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type (StringLiteral and NumberLiteral)
416 const type = typeof object.node.value;
417 if (type === "string" || type === "number") {
418 // @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type
419 context = object.node.value;
420 func = context[property.node.name];
421 }
422 }
423 }
424
425 if (func) {
426 const args = path.get("arguments").map(arg => evaluateCached(arg, state));
427 if (!state.confident) return;
428
429 return func.apply(context, args);
430 }
431 }
432
433 deopt(path, state);
434 }
435
436 function evaluateQuasis(
437 path: NodePath<t.TaggedTemplateExpression | t.TemplateLiteral>,
438 quasis: Array<any>,
439 state: State,
440 raw = false,
441 ) {
442 let str = "";
443
444 let i = 0;
445 const exprs: Array<NodePath<t.Node>> = path.isTemplateLiteral()
446 ? path.get("expressions")
447 : path.get("quasi.expressions");
448
449 for (const elem of quasis) {
450 // not confident, evaluated an expression we don't like
451 if (!state.confident) break;
452
453 // add on element
454 str += raw ? elem.value.raw : elem.value.cooked;
455
456 // add on interpolated expression if it's present
457 const expr = exprs[i++];
458 if (expr) str += String(evaluateCached(expr, state));
459 }
460
461 if (!state.confident) return;
462 return str;
463 }
464
465 /**
466 * Walk the input `node` and statically evaluate it.
467 *
468 * Returns an object in the form `{ confident, value, deopt }`. `confident`
469 * indicates whether or not we had to drop out of evaluating the expression
470 * because of hitting an unknown node that we couldn't confidently find the
471 * value of, in which case `deopt` is the path of said node.
472 *
473 * Example:
474 *
475 * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 }
476 * t.evaluate(parse("!true")) // { confident: true, value: false }
477 * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath }
478 *
479 */
480
481 export function evaluate(this: NodePath): {
482 confident: boolean;
483 value: any;
484 deopt?: NodePath;
485 } {
486 const state: State = {
487 confident: true,
488 deoptPath: null,
489 seen: new Map(),
490 };
491 let value = evaluateCached(this, state);
492 if (!state.confident) value = undefined;
493
494 return {
495 confident: state.confident,
496 deopt: state.deoptPath,
497 value: value,
498 };
499 }