Debian Codegraph @

packages/babel-helper-member-expression-to-functions/src/util.ts

raw symbols SCIP
1 import type { NodePath } from "@babel/traverse";
2
3 /**
4 * Test if a NodePath will be cast to boolean when evaluated.
5 *
6 * @example
7 * // returns true
8 * const nodePathAQDotB = NodePath("if (a?.#b) {}").get("test"); // a?.#b
9 * willPathCastToBoolean(nodePathAQDotB)
10 * @example
11 * // returns false
12 * willPathCastToBoolean(NodePath("a?.#b"))
13 * @todo Respect transparent expression wrappers
14 * @see {@link packages/babel-plugin-proposal-optional-chaining/src/util.js}
15 * @param {NodePath} path
16 * @returns {boolean}
17 */
18 export function willPathCastToBoolean(path: NodePath): boolean {
19 const maybeWrapped = path;
20 const { node, parentPath } = maybeWrapped;
21 if (parentPath.isLogicalExpression()) {
22 const { operator, right } = parentPath.node;
23 if (
24 operator === "&&" ||
25 operator === "||" ||
26 (operator === "??" && node === right)
27 ) {
28 return willPathCastToBoolean(parentPath);
29 }
30 }
31 if (parentPath.isSequenceExpression()) {
32 const { expressions } = parentPath.node;
33 if (expressions[expressions.length - 1] === node) {
34 return willPathCastToBoolean(parentPath);
35 } else {
36 // if it is in the middle of a sequence expression, we don't
37 // care the return value so just cast to boolean for smaller
38 // output
39 return true;
40 }
41 }
42 return (
43 parentPath.isConditional({ test: node }) ||
44 parentPath.isUnaryExpression({ operator: "!" }) ||
45 parentPath.isLoop({ test: node })
46 );
47 }