@babel/plugin-transform-exponentiation-operator
Version:
Compile exponentiation operator to ES5
79 lines (76 loc) • 2.27 kB
JavaScript
import { declare } from '@babel/helper-plugin-utils';
const index = declare(api => {
api.assertVersion("^7.0.0-0 || ^8.0.0");
const {
types: t,
template
} = api;
function build(left, right) {
return t.callExpression(t.memberExpression(t.identifier("Math"), t.identifier("pow")), [left, right]);
}
function maybeMemoize(node, scope) {
if (scope.isStatic(node)) {
return {
assign: node,
ref: t.cloneNode(node)
};
}
if (scope.path.isPattern()) {
return null;
}
const id = scope.generateUidIdentifierBasedOnNode(node);
scope.push({
id
});
return {
assign: t.assignmentExpression("=", t.cloneNode(id), node),
ref: t.cloneNode(id)
};
}
return {
name: "transform-exponentiation-operator",
visitor: {
AssignmentExpression(path) {
const {
node,
scope
} = path;
if (node.operator !== "**=") return;
if (t.isMemberExpression(node.left)) {
let member1;
let member2;
const object = maybeMemoize(node.left.object, scope);
if (!object) {
path.replaceWith(template.expression.ast`(() => ${path.node})()`);
return;
}
const {
property,
computed
} = node.left;
if (computed) {
const prop = maybeMemoize(property, scope);
member1 = t.memberExpression(object.assign, prop.assign, true);
member2 = t.memberExpression(object.ref, prop.ref, true);
} else {
member1 = t.memberExpression(object.assign, property, false);
member2 = t.memberExpression(object.ref, t.cloneNode(property), false);
}
path.replaceWith(t.assignmentExpression("=", member1, build(member2, node.right)));
} else {
path.replaceWith(t.assignmentExpression("=", node.left, build(t.cloneNode(node.left), node.right)));
}
},
BinaryExpression(path) {
const {
node
} = path;
if (node.operator === "**") {
path.replaceWith(build(node.left, node.right));
}
}
}
};
});
export { index as default };
//# sourceMappingURL=index.js.map