Debian Codegraph @

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

raw symbols ◀ ▶ SCIP
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 // @ts-ignore
193 const binding = path.scope.getBinding(path.node.name);
194
195 if (binding && binding.constantViolations.length > 0) {
196 return deopt(binding.path, state);
197 }
198
199 if (binding && path.node.start < binding.path.node.end) {
200 return deopt(binding.path, state);
201 }
202
203 if (binding?.hasValue) {
204 return binding.value;
205 } else {
•206 // @ts-ignore
207 if (path.node.name === "undefined") {
208 return binding ? deopt(binding.path, state) : undefined;
•209 // @ts-ignore
210 } else if (path.node.name === "Infinity") {
211 return binding ? deopt(binding.path, state) : Infinity;
•212 // @ts-ignore
213 } else if (path.node.name === "NaN") {
214 return binding ? deopt(binding.path, state) : NaN;
215 }
216
217 const resolved = path.resolve();
218 if (resolved === path) {
219 return deopt(path, state);
220 } else {
221 return evaluateCached(resolved, state);
222 }
223 }
224 }
225
•226 // @ts-ignore
227 if (path.isUnaryExpression({ prefix: true })) {
•228 // @ts-ignore
229 if (path.node.operator === "void") {
230 // we don't need to evaluate the argument to know what this will return
231 return undefined;
232 }
233
•234 // @ts-ignore
235 const argument = path.get("argument");
236 if (
•237 // @ts-ignore
238 path.node.operator === "typeof" &&
239 (argument.isFunction() || argument.isClass())
240 ) {
241 return "function";
242 }
243
244 const arg = evaluateCached(argument, state);
245 if (!state.confident) return;
•246 // @ts-ignore
247 switch (path.node.operator) {
248 case "!":
249 return !arg;
250 case "+":
251 return +arg;
252 case "-":
253 return -arg;
254 case "~":
255 return ~arg;
256 case "typeof":
257 return typeof arg;
258 }
259 }
260
•261 // @ts-ignore
262 if (path.isArrayExpression()) {
263 const arr = [];
•264 // @ts-ignore
265 const elems: Array<NodePath> = path.get("elements");
266 for (const elem of elems) {
267 const elemValue = elem.evaluate();
268
269 if (elemValue.confident) {
270 arr.push(elemValue.value);
271 } else {
272 return deopt(elemValue.deopt, state);
273 }
274 }
275 return arr;
276 }
277
•278 // @ts-ignore
279 if (path.isObjectExpression()) {
280 const obj = {};
•281 // @ts-ignore
282 const props = path.get("properties");
283 for (const prop of props) {
284 if (prop.isObjectMethod() || prop.isSpreadElement()) {
285 return deopt(prop, state);
286 }
287 const keyPath = (prop as NodePath<t.ObjectProperty>).get("key");
288 let key;
•289 // @ts-ignore
290 if (prop.node.computed) {
291 key = keyPath.evaluate();
292 if (!key.confident) {
293 return deopt(key.deopt, state);
294 }
295 key = key.value;
296 } else if (keyPath.isIdentifier()) {
297 key = keyPath.node.name;
298 } else {
299 key = (
300 keyPath.node as t.StringLiteral | t.NumericLiteral | t.BigIntLiteral
301 ).value;
302 }
303 const valuePath = (prop as NodePath<t.ObjectProperty>).get("value");
304 let value = valuePath.evaluate();
305 if (!value.confident) {
306 return deopt(value.deopt, state);
307 }
308 value = value.value;
309 // @ts-expect-error key is any type
310 obj[key] = value;
311 }
312 return obj;
313 }
314
•315 // @ts-ignore
316 if (path.isLogicalExpression()) {
317 // If we are confident that the left side of an && is false, or the left
318 // side of an || is true, we can be confident about the entire expression
319 const wasConfident = state.confident;
•320 // @ts-ignore
321 const left = evaluateCached(path.get("left"), state);
322 const leftConfident = state.confident;
323 state.confident = wasConfident;
•324 // @ts-ignore
325 const right = evaluateCached(path.get("right"), state);
326 const rightConfident = state.confident;
327
•328 // @ts-ignore
329 switch (path.node.operator) {
330 case "||":
331 // TODO consider having a "truthy type" that doesn't bail on
332 // left uncertainty but can still evaluate to truthy.
333 state.confident = leftConfident && (!!left || rightConfident);
334 if (!state.confident) return;
335
336 return left || right;
337 case "&&":
338 state.confident = leftConfident && (!left || rightConfident);
339 if (!state.confident) return;
340
341 return left && right;
342 case "??":
343 state.confident = leftConfident && (left != null || rightConfident);
344 if (!state.confident) return;
345
346 return left ?? right;
347 }
348 }
349
•350 // @ts-ignore
351 if (path.isBinaryExpression()) {
•352 // @ts-ignore
353 const left = evaluateCached(path.get("left"), state);
354 if (!state.confident) return;
•355 // @ts-ignore
356 const right = evaluateCached(path.get("right"), state);
357 if (!state.confident) return;
358
•359 // @ts-ignore
360 switch (path.node.operator) {
361 case "-":
362 return left - right;
363 case "+":
364 return left + right;
365 case "/":
366 return left / right;
367 case "*":
368 return left * right;
369 case "%":
370 return left % right;
371 case "**":
372 return left ** right;
373 case "<":
374 return left < right;
375 case ">":
376 return left > right;
377 case "<=":
378 return left <= right;
379 case ">=":
380 return left >= right;
381 case "==":
382 return left == right; // eslint-disable-line eqeqeq
383 case "!=":
384 return left != right;
385 case "===":
386 return left === right;
387 case "!==":
388 return left !== right;
389 case "|":
390 return left | right;
391 case "&":
392 return left & right;
393 case "^":
394 return left ^ right;
395 case "<<":
396 return left << right;
397 case ">>":
398 return left >> right;
399 case ">>>":
400 return left >>> right;
401 }
402 }
403
•404 // @ts-ignore
405 if (path.isCallExpression()) {
•406 // @ts-ignore
407 const callee = path.get("callee");
408 let context;
409 let func;
410
411 // Number(1);
412 if (
413 callee.isIdentifier() &&
•414 // @ts-ignore
415 !path.scope.getBinding(callee.node.name) &&
416 isValidCallee(callee.node.name)
417 ) {
•418 // @ts-ignore
419 func = global[callee.node.name];
420 }
421
422 if (callee.isMemberExpression()) {
423 const object = callee.get("object");
424 const property = callee.get("property");
425
426 // Math.min(1, 2)
427 if (
428 object.isIdentifier() &&
429 property.isIdentifier() &&
430 isValidCallee(object.node.name) &&
431 !isInvalidMethod(property.node.name)
432 ) {
•433 // @ts-ignore
434 context = global[object.node.name];
•435 // @ts-ignore
436 func = context[property.node.name];
437 }
438
439 // "abc".charCodeAt(4)
440 if (object.isLiteral() && property.isIdentifier()) {
•441 // @ts-ignore todo(flow->ts): consider checking ast node type instead of value type (StringLiteral and NumberLiteral)
442 const type = typeof object.node.value;
443 if (type === "string" || type === "number") {
•444 // @ts-ignore todo(flow->ts): consider checking ast node type instead of value type
445 context = object.node.value;
•446 const key = property.node.name;
447 if (Object.hasOwnProperty.call(context, key)) {
448 func = context[key as keyof typeof context];
449 }
450 }
451 }
452 }
453
454 if (func) {
•455 // @ts-ignore
456 const args = path.get("arguments").map(arg => evaluateCached(arg, state));
457 if (!state.confident) return;
458
459 return func.apply(context, args);
460 }
461 }
462
463 deopt(path, state);
464 }
465
466 function evaluateQuasis(
467 path: NodePath<t.TaggedTemplateExpression | t.TemplateLiteral>,
468 quasis: Array<any>,
469 state: State,
470 raw = false,
471 ) {
472 let str = "";
473
474 let i = 0;
475 const exprs: Array<NodePath<t.Node>> = path.isTemplateLiteral()
476 ? path.get("expressions")
477 : path.get("quasi.expressions");
478
479 for (const elem of quasis) {
480 // not confident, evaluated an expression we don't like
481 if (!state.confident) break;
482
483 // add on element
484 str += raw ? elem.value.raw : elem.value.cooked;
485
486 // add on interpolated expression if it's present
487 const expr = exprs[i++];
488 if (expr) str += String(evaluateCached(expr, state));
489 }
490
491 if (!state.confident) return;
492 return str;
493 }
494
495 /**
496 * Walk the input `node` and statically evaluate it.
497 *
498 * Returns an object in the form `{ confident, value, deopt }`. `confident`
499 * indicates whether or not we had to drop out of evaluating the expression
500 * because of hitting an unknown node that we couldn't confidently find the
501 * value of, in which case `deopt` is the path of said node.
502 *
503 * Example:
504 *
505 * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 }
506 * t.evaluate(parse("!true")) // { confident: true, value: false }
507 * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath }
508 *
509 */
510
511 export function evaluate(this: NodePath): {
512 confident: boolean;
513 value: any;
514 deopt?: NodePath;
515 } {
516 const state: State = {
517 confident: true,
518 deoptPath: null,
519 seen: new Map(),
520 };
521 let value = evaluateCached(this, state);
522 if (!state.confident) value = undefined;
523
524 return {
525 confident: state.confident,
526 deopt: state.deoptPath,
527 value: value,
528 };
529 }