Debian Codegraph @

packages/babel-plugin-proposal-logical-assignment-operators/src/index.ts

raw
1 import { declare } from "@babel/helper-plugin-utils";
2 import syntaxLogicalAssignmentOperators from "@babel/plugin-syntax-logical-assignment-operators";
3 import { types as t } from "@babel/core";
4
5 export default declare(api => {
6 api.assertVersion(7);
7
8 return {
9 name: "proposal-logical-assignment-operators",
10 inherits: syntaxLogicalAssignmentOperators.default,
11
12 visitor: {
13 AssignmentExpression(path) {
14 const { node, scope } = path;
15 const { operator, left, right } = node;
16 const operatorTrunc = operator.slice(0, -1);
17 if (!t.LOGICAL_OPERATORS.includes(operatorTrunc)) {
18 return;
19 }
20
21 const lhs = t.cloneNode(left) as t.Identifier | t.MemberExpression;
22 if (t.isMemberExpression(left)) {
23 const { object, property, computed } = left;
24 const memo = scope.maybeGenerateMemoised(object);
25 if (memo) {
26 left.object = memo;
27 (lhs as t.MemberExpression).object = t.assignmentExpression(
28 "=",
29 t.cloneNode(memo),
30 // object must not be Super when `memo` is an identifier
31 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
32 object as t.Expression,
33 );
34 }
35
36 if (computed) {
37 const memo = scope.maybeGenerateMemoised(property);
38 if (memo) {
39 left.property = memo;
40 (lhs as t.MemberExpression).property = t.assignmentExpression(
41 "=",
42 t.cloneNode(memo),
43 // @ts-expect-error todo(flow->ts): property can be t.PrivateName
44 property,
45 );
46 }
47 }
48 }
49
50 path.replaceWith(
51 t.logicalExpression(
52 // @ts-expect-error operatorTrunc has been tested by t.LOGICAL_OPERATORS
53 operatorTrunc,
54 lhs,
55 t.assignmentExpression("=", left, right),
56 ),
57 );
58 },
59 },
60 };
61 });