Ujjwal Sharma 2ac49ba7c4
add support for logical assignments with private properties (#11702)
* add support for logical assignments with private properties

Patches the logic for handling assignment operators and adds support for
handling the logical assignment operators appropriately.

Fixes: https://github.com/babel/babel/issues/11646

* replace hardcoded logical assignment operators with constant

Replace a hardcoded check for logical assignment operators with the
LOGICAL_OPERATORS constant in
plugin-proposal-logical-assignment-operators.

Refs: https://github.com/babel/babel/pull/11702#discussion_r438554423
2020-07-30 14:10:16 -04:00

54 lines
1.5 KiB
JavaScript

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;
const operatorTrunc = operator.slice(0, -1);
if (!t.LOGICAL_OPERATORS.includes(operatorTrunc)) {
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,
);
}
}
}
path.replaceWith(
t.logicalExpression(
operatorTrunc,
lhs,
t.assignmentExpression("=", left, right),
),
);
},
},
};
});