@babel/plugin-transform-exponentiation-operator
Version:
Compile exponentiation operator to ES5
74 lines (71 loc) • 2.17 kB
JavaScript
import { declare } from '@babel/helper-plugin-utils';
import { skipTransparentExprWrapperNodes } from '@babel/helper-skip-transparent-expression-wrappers';
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;
const left = skipTransparentExprWrapperNodes(node.left);
if (t.isMemberExpression(left)) {
const {
property,
computed
} = left;
const object = maybeMemoize(left.object, scope);
const prop = computed ? maybeMemoize(property, scope) : {
assign: property,
ref: t.cloneNode(property)
};
if (!object || !prop) {
path.replaceWith(template.expression.ast`(() => ${path.node})()`);
return;
}
path.replaceWith(t.assignmentExpression("=", t.memberExpression(object.assign, prop.assign, computed), build(t.memberExpression(object.ref, prop.ref, computed), node.right)));
} else {
path.replaceWith(t.assignmentExpression("=", left, build(t.cloneNode(left), node.right)));
}
},
BinaryExpression(path) {
const {
node
} = path;
if (node.operator === "**") {
path.replaceWith(build(node.left, node.right));
}
}
}
};
});
export { index as default };