2 * @fileoverview Rule to disallow Math.pow in favor of the ** operator
3 * @author Milos Djermanovic
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
13 const { CALL, ReferenceTracker } = require("eslint-utils");
15 //------------------------------------------------------------------------------
17 //------------------------------------------------------------------------------
19 const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" });
22 * Determines whether the given node needs parens if used as the base in an exponentiation binary expression.
23 * @param {ASTNode} base The node to check.
24 * @returns {boolean} `true` if the node needs to be parenthesised.
26 function doesBaseNeedParens(base) {
29 // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c
30 astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR ||
32 // An unary operator cannot be used immediately before an exponentiation expression
33 base.type === "AwaitExpression" ||
34 base.type === "UnaryExpression"
39 * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression.
40 * @param {ASTNode} exponent The node to check.
41 * @returns {boolean} `true` if the node needs to be parenthesised.
43 function doesExponentNeedParens(exponent) {
45 // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c
46 return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR;
50 * Determines whether an exponentiation binary expression at the place of the given node would need parens.
51 * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression.
52 * @param {SourceCode} sourceCode A SourceCode object.
53 * @returns {boolean} `true` if the expression needs to be parenthesised.
55 function doesExponentiationExpressionNeedParens(node, sourceCode) {
56 const parent = node.parent.type === "ChainExpression" ? node.parent.parent : node.parent;
59 parent.type === "ClassDeclaration" ||
61 parent.type.endsWith("Expression") &&
62 astUtils.getPrecedence(parent) >= PRECEDENCE_OF_EXPONENTIATION_EXPR &&
63 !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) &&
64 !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) &&
65 !(parent.type === "MemberExpression" && parent.computed && parent.property === node) &&
66 !(parent.type === "ArrayExpression")
70 return needsParens && !astUtils.isParenthesised(sourceCode, node);
74 * Optionally parenthesizes given text.
75 * @param {string} text The text to parenthesize.
76 * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised.
77 * @returns {string} parenthesised or unchanged text.
79 function parenthesizeIfShould(text, shouldParenthesize) {
80 return shouldParenthesize ? `(${text})` : text;
83 //------------------------------------------------------------------------------
85 //------------------------------------------------------------------------------
92 description: "disallow the use of `Math.pow` in favor of the `**` operator",
93 category: "Stylistic Issues",
95 url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
102 useExponentiation: "Use the '**' operator instead of 'Math.pow'."
107 const sourceCode = context.getSourceCode();
110 * Reports the given node.
111 * @param {ASTNode} node 'Math.pow()' node to report.
114 function report(node) {
117 messageId: "useExponentiation",
120 node.arguments.length !== 2 ||
121 node.arguments.some(arg => arg.type === "SpreadElement") ||
122 sourceCode.getCommentsInside(node).length > 0
127 const base = node.arguments[0],
128 exponent = node.arguments[1],
129 baseText = sourceCode.getText(base),
130 exponentText = sourceCode.getText(exponent),
131 shouldParenthesizeBase = doesBaseNeedParens(base),
132 shouldParenthesizeExponent = doesExponentNeedParens(exponent),
133 shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode);
138 if (!shouldParenthesizeAll) {
139 if (!shouldParenthesizeBase) {
140 const firstReplacementToken = sourceCode.getFirstToken(base),
141 tokenBefore = sourceCode.getTokenBefore(node);
145 tokenBefore.range[1] === node.range[0] &&
146 !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
148 prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c
151 if (!shouldParenthesizeExponent) {
152 const lastReplacementToken = sourceCode.getLastToken(exponent),
153 tokenAfter = sourceCode.getTokenAfter(node);
157 node.range[1] === tokenAfter.range[0] &&
158 !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter)
160 suffix = " "; // Math.pow(a, b)in c -> a**b in c
165 const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase),
166 exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent),
167 replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll);
169 return fixer.replaceText(node, `${prefix}${replacement}${suffix}`);
176 const scope = context.getScope();
177 const tracker = new ReferenceTracker(scope);
180 pow: { [CALL]: true }
184 for (const { node } of tracker.iterateGlobalReferences(trackMap)) {