UNPKG

7.64 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow Math.pow in favor of the ** operator
3 * @author Milos Djermanovic
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("./utils/ast-utils");
13const { CALL, ReferenceTracker } = require("eslint-utils");
14
15//------------------------------------------------------------------------------
16// Helpers
17//------------------------------------------------------------------------------
18
19const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" });
20
21/**
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.
25 */
26function doesBaseNeedParens(base) {
27 return (
28
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 ||
31
32 // An unary operator cannot be used immediately before an exponentiation expression
33 base.type === "AwaitExpression" ||
34 base.type === "UnaryExpression"
35 );
36}
37
38/**
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.
42 */
43function doesExponentNeedParens(exponent) {
44
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;
47}
48
49/**
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.
54 */
55function doesExponentiationExpressionNeedParens(node, sourceCode) {
56 const parent = node.parent.type === "ChainExpression" ? node.parent.parent : node.parent;
57
58 const needsParens = (
59 parent.type === "ClassDeclaration" ||
60 (
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")
67 )
68 );
69
70 return needsParens && !astUtils.isParenthesised(sourceCode, node);
71}
72
73/**
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.
78 */
79function parenthesizeIfShould(text, shouldParenthesize) {
80 return shouldParenthesize ? `(${text})` : text;
81}
82
83//------------------------------------------------------------------------------
84// Rule Definition
85//------------------------------------------------------------------------------
86
87module.exports = {
88 meta: {
89 type: "suggestion",
90
91 docs: {
92 description: "disallow the use of `Math.pow` in favor of the `**` operator",
93 category: "Stylistic Issues",
94 recommended: false,
95 url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
96 },
97
98 schema: [],
99 fixable: "code",
100
101 messages: {
102 useExponentiation: "Use the '**' operator instead of 'Math.pow'."
103 }
104 },
105
106 create(context) {
107 const sourceCode = context.getSourceCode();
108
109 /**
110 * Reports the given node.
111 * @param {ASTNode} node 'Math.pow()' node to report.
112 * @returns {void}
113 */
114 function report(node) {
115 context.report({
116 node,
117 messageId: "useExponentiation",
118 fix(fixer) {
119 if (
120 node.arguments.length !== 2 ||
121 node.arguments.some(arg => arg.type === "SpreadElement") ||
122 sourceCode.getCommentsInside(node).length > 0
123 ) {
124 return null;
125 }
126
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);
134
135 let prefix = "",
136 suffix = "";
137
138 if (!shouldParenthesizeAll) {
139 if (!shouldParenthesizeBase) {
140 const firstReplacementToken = sourceCode.getFirstToken(base),
141 tokenBefore = sourceCode.getTokenBefore(node);
142
143 if (
144 tokenBefore &&
145 tokenBefore.range[1] === node.range[0] &&
146 !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
147 ) {
148 prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c
149 }
150 }
151 if (!shouldParenthesizeExponent) {
152 const lastReplacementToken = sourceCode.getLastToken(exponent),
153 tokenAfter = sourceCode.getTokenAfter(node);
154
155 if (
156 tokenAfter &&
157 node.range[1] === tokenAfter.range[0] &&
158 !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter)
159 ) {
160 suffix = " "; // Math.pow(a, b)in c -> a**b in c
161 }
162 }
163 }
164
165 const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase),
166 exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent),
167 replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll);
168
169 return fixer.replaceText(node, `${prefix}${replacement}${suffix}`);
170 }
171 });
172 }
173
174 return {
175 Program() {
176 const scope = context.getScope();
177 const tracker = new ReferenceTracker(scope);
178 const trackMap = {
179 Math: {
180 pow: { [CALL]: true }
181 }
182 };
183
184 for (const { node } of tracker.iterateGlobalReferences(trackMap)) {
185 report(node);
186 }
187 }
188 };
189 }
190};