| 1 | // this file contains hooks that handle ancestry cleanup of parent nodes when removing children |
| 2 | |
| 3 | import type NodePath from ".."; |
| 4 | import type * as t from "@babel/types"; |
| 5 | /** |
| 6 | * Pre hooks should be used for either rejecting removal or delegating removal |
| 7 | */ |
| 8 | |
| 9 | export const hooks = [ |
| 10 | function (self: NodePath, parent: NodePath) { |
| 11 | const removeParent = |
| 12 | // while (NODE); |
| 13 | // removing the test of a while/switch, we can either just remove it entirely *or* turn the |
| 14 | // `test` into `true` unlikely that the latter will ever be what's wanted so we just remove |
| 15 | // the loop to avoid infinite recursion |
| 16 | (self.key === "test" && (parent.isWhile() || parent.isSwitchCase())) || |
| 17 | // export NODE; |
| 18 | // just remove a declaration for an export as this is no longer valid |
| 19 | (self.key === "declaration" && parent.isExportDeclaration()) || |
| 20 | // label: NODE |
| 21 | // stray labeled statement with no body |
| 22 | (self.key === "body" && parent.isLabeledStatement()) || |
| 23 | // let NODE; |
| 24 | // remove an entire declaration if there are no declarators left |
| 25 | (self.listKey === "declarations" && |
| 26 | parent.isVariableDeclaration() && |
| 27 | parent.node.declarations.length === 1) || |
| 28 | // NODE; |
| 29 | // remove the entire expression statement if there's no expression |
| 30 | (self.key === "expression" && parent.isExpressionStatement()); |
| 31 | |
| 32 | if (removeParent) { |
| 33 | parent.remove(); |
| 34 | return true; |
| 35 | } |
| 36 | }, |
| 37 | |
| 38 | function (self: NodePath, parent: NodePath) { |
| 39 | if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { |
| 40 | // (node, NODE); |
| 41 | // we've just removed the second element of a sequence expression so let's turn that sequence |
| 42 | // expression into a regular expression |
| 43 | parent.replaceWith(parent.node.expressions[0]); |
| 44 | return true; |
| 45 | } |
| 46 | }, |
| 47 | |
| 48 | function (self: NodePath, parent: NodePath) { |
| 49 | if (parent.isBinary()) { |
| 50 | // left + NODE; |
| 51 | // NODE + right; |
| 52 | // we're in a binary expression, better remove it and replace it with the last expression |
| 53 | if (self.key === "left") { |
| 54 | parent.replaceWith(parent.node.right); |
| 55 | } else { |
| 56 | // key === "right" |
| 57 | parent.replaceWith(parent.node.left); |
| 58 | } |
| 59 | return true; |
| 60 | } |
| 61 | }, |
| 62 | |
| 63 | function (self: NodePath, parent: NodePath) { |
| 64 | if ( |
| 65 | (parent.isIfStatement() && self.key === "consequent") || |
| 66 | (self.key === "body" && |
| 67 | (parent.isLoop() || parent.isArrowFunctionExpression())) |
| 68 | ) { |
| 69 | self.replaceWith({ |
| 70 | type: "BlockStatement", |
| 71 | body: [], |
| 72 | } as t.BlockStatement); |
| 73 | return true; |
| 74 | } |
| 75 | }, |
| 76 | ]; |