| 1 |
import type { NodePath } from "@babel/traverse"; |
| 2 |
import { isTransparentExprWrapper } from "@babel/helper-skip-transparent-expression-wrappers"; |
| 3 |
/** |
| 4 |
* Test if a NodePath will be cast to boolean when evaluated. |
| 5 |
* It respects transparent expression wrappers defined in |
| 6 |
* "@babel/helper-skip-transparent-expression-wrappers" |
| 7 |
* |
| 8 |
* @example |
| 9 |
* // returns true |
| 10 |
* const nodePathADotB = NodePath("if (a.b) {}").get("test"); // a.b |
| 11 |
* willPathCastToBoolean(nodePathADotB) |
| 12 |
* @example |
| 13 |
* // returns false |
| 14 |
* willPathCastToBoolean(NodePath("a.b")) |
| 15 |
* @param {NodePath} path |
| 16 |
* @returns {boolean} |
| 17 |
*/ |
| 18 |
export function willPathCastToBoolean(path: NodePath): boolean { |
| 19 |
const maybeWrapped = findOutermostTransparentParent(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 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Return the outermost transparent expression wrapper of a given path, |
| 51 |
* otherwise returns path itself. |
| 52 |
* @example |
| 53 |
* const nodePathADotB = NodePath("(a.b as any)").get("expression"); // a.b |
| 54 |
* // returns NodePath("(a.b as any)") |
| 55 |
* findOutermostTransparentParent(nodePathADotB); |
| 56 |
* @param {NodePath} path |
| 57 |
* @returns {NodePath} |
| 58 |
*/ |
| 59 |
export function findOutermostTransparentParent(path: NodePath): NodePath { |
| 60 |
let maybeWrapped = path; |
| 61 |
path.findParent(p => { |
| 62 |
if (!isTransparentExprWrapper(p.node)) return true; |
| 63 |
maybeWrapped = p; |
| 64 |
}); |
| 65 |
return maybeWrapped; |
| 66 |
} |