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