/
index.js
65 lines (59 loc) 路 1.84 KB
/
index.js
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
import { declare } from "@babel/helper-plugin-utils";
import syntaxLogicalAssignmentOperators from "@babel/plugin-syntax-logical-assignment-operators";
import { types as t } from "@babel/core";
export default declare(api => {
api.assertVersion(7);
return {
name: "proposal-logical-assignment-operators",
inherits: syntaxLogicalAssignmentOperators,
visitor: {
AssignmentExpression(path) {
const { node, scope } = path;
const { operator, left, right } = node;
if (operator !== "||=" && operator !== "&&=" && operator !== "??=") {
return;
}
const lhs = t.cloneNode(left);
if (t.isMemberExpression(left)) {
const { object, property, computed } = left;
const memo = scope.maybeGenerateMemoised(object);
if (memo) {
left.object = memo;
lhs.object = t.assignmentExpression("=", t.cloneNode(memo), object);
}
if (computed) {
const memo = scope.maybeGenerateMemoised(property);
if (memo) {
left.property = memo;
lhs.property = t.assignmentExpression(
"=",
t.cloneNode(memo),
property,
);
}
}
}
const isRHSAnonymousFunction = t.isFunctionExpression(right, {
id: null,
});
if (isRHSAnonymousFunction && operator === "??=") {
path.replaceWith(
t.assignmentExpression(
"=",
lhs,
t.logicalExpression("??", left, right),
),
);
} else {
path.replaceWith(
t.logicalExpression(
operator.slice(0, -1),
lhs,
t.assignmentExpression("=", left, right),
),
);
}
},
},
};
});