/
index.js
57 lines (50 loc) 路 1.68 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
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.isFunction(right, { id: null });
const rightExpression = isRHSAnonymousFunction
? t.sequenceExpression([t.numericLiteral(0), right])
: right;
path.replaceWith(
t.logicalExpression(
operator.slice(0, -1),
lhs,
t.assignmentExpression("=", left, rightExpression),
),
);
},
},
};
});