/
index.ts
59 lines (53 loc) 路 1.8 KB
/
index.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
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.default,
visitor: {
AssignmentExpression(path) {
const { node, scope } = path;
const { operator, left, right } = node;
const operatorTrunc = operator.slice(0, -1);
if (!t.LOGICAL_OPERATORS.includes(operatorTrunc)) {
return;
}
const lhs = t.cloneNode(left) as t.Identifier | t.MemberExpression;
if (t.isMemberExpression(left)) {
const { object, property, computed } = left;
const memo = scope.maybeGenerateMemoised(object);
if (memo) {
left.object = memo;
(lhs as t.MemberExpression).object = t.assignmentExpression(
"=",
t.cloneNode(memo),
object,
);
}
if (computed) {
const memo = scope.maybeGenerateMemoised(property);
if (memo) {
left.property = memo;
(lhs as t.MemberExpression).property = t.assignmentExpression(
"=",
t.cloneNode(memo),
// @ts-expect-error todo(flow->ts): property can be t.PrivateName
property,
);
}
}
}
path.replaceWith(
t.logicalExpression(
// @ts-ignore operatorTrunc has been tested by t.LOGICAL_OPERATORS
operatorTrunc,
lhs,
t.assignmentExpression("=", left, right),
),
);
},
},
};
});