prefer-exponentiation-operator.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /**
  2. * @fileoverview Rule to disallow Math.pow in favor of the ** operator
  3. * @author Milos Djermanovic
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const { CALL, ReferenceTracker } = require("eslint-utils");
  11. //------------------------------------------------------------------------------
  12. // Helpers
  13. //------------------------------------------------------------------------------
  14. const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" });
  15. /**
  16. * Determines whether the given node needs parens if used as the base in an exponentiation binary expression.
  17. * @param {ASTNode} base The node to check.
  18. * @returns {boolean} `true` if the node needs to be parenthesised.
  19. */
  20. function doesBaseNeedParens(base) {
  21. return (
  22. // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c
  23. astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR ||
  24. // An unary operator cannot be used immediately before an exponentiation expression
  25. base.type === "AwaitExpression" ||
  26. base.type === "UnaryExpression"
  27. );
  28. }
  29. /**
  30. * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression.
  31. * @param {ASTNode} exponent The node to check.
  32. * @returns {boolean} `true` if the node needs to be parenthesised.
  33. */
  34. function doesExponentNeedParens(exponent) {
  35. // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c
  36. return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR;
  37. }
  38. /**
  39. * Determines whether an exponentiation binary expression at the place of the given node would need parens.
  40. * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression.
  41. * @param {SourceCode} sourceCode A SourceCode object.
  42. * @returns {boolean} `true` if the expression needs to be parenthesised.
  43. */
  44. function doesExponentiationExpressionNeedParens(node, sourceCode) {
  45. const parent = node.parent.type === "ChainExpression" ? node.parent.parent : node.parent;
  46. const needsParens = (
  47. parent.type === "ClassDeclaration" ||
  48. (
  49. parent.type.endsWith("Expression") &&
  50. astUtils.getPrecedence(parent) >= PRECEDENCE_OF_EXPONENTIATION_EXPR &&
  51. !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) &&
  52. !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) &&
  53. !(parent.type === "MemberExpression" && parent.computed && parent.property === node) &&
  54. !(parent.type === "ArrayExpression")
  55. )
  56. );
  57. return needsParens && !astUtils.isParenthesised(sourceCode, node);
  58. }
  59. /**
  60. * Optionally parenthesizes given text.
  61. * @param {string} text The text to parenthesize.
  62. * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised.
  63. * @returns {string} parenthesised or unchanged text.
  64. */
  65. function parenthesizeIfShould(text, shouldParenthesize) {
  66. return shouldParenthesize ? `(${text})` : text;
  67. }
  68. //------------------------------------------------------------------------------
  69. // Rule Definition
  70. //------------------------------------------------------------------------------
  71. /** @type {import('../shared/types').Rule} */
  72. module.exports = {
  73. meta: {
  74. type: "suggestion",
  75. docs: {
  76. description: "Disallow the use of `Math.pow` in favor of the `**` operator",
  77. recommended: false,
  78. url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
  79. },
  80. schema: [],
  81. fixable: "code",
  82. messages: {
  83. useExponentiation: "Use the '**' operator instead of 'Math.pow'."
  84. }
  85. },
  86. create(context) {
  87. const sourceCode = context.getSourceCode();
  88. /**
  89. * Reports the given node.
  90. * @param {ASTNode} node 'Math.pow()' node to report.
  91. * @returns {void}
  92. */
  93. function report(node) {
  94. context.report({
  95. node,
  96. messageId: "useExponentiation",
  97. fix(fixer) {
  98. if (
  99. node.arguments.length !== 2 ||
  100. node.arguments.some(arg => arg.type === "SpreadElement") ||
  101. sourceCode.getCommentsInside(node).length > 0
  102. ) {
  103. return null;
  104. }
  105. const base = node.arguments[0],
  106. exponent = node.arguments[1],
  107. baseText = sourceCode.getText(base),
  108. exponentText = sourceCode.getText(exponent),
  109. shouldParenthesizeBase = doesBaseNeedParens(base),
  110. shouldParenthesizeExponent = doesExponentNeedParens(exponent),
  111. shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode);
  112. let prefix = "",
  113. suffix = "";
  114. if (!shouldParenthesizeAll) {
  115. if (!shouldParenthesizeBase) {
  116. const firstReplacementToken = sourceCode.getFirstToken(base),
  117. tokenBefore = sourceCode.getTokenBefore(node);
  118. if (
  119. tokenBefore &&
  120. tokenBefore.range[1] === node.range[0] &&
  121. !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
  122. ) {
  123. prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c
  124. }
  125. }
  126. if (!shouldParenthesizeExponent) {
  127. const lastReplacementToken = sourceCode.getLastToken(exponent),
  128. tokenAfter = sourceCode.getTokenAfter(node);
  129. if (
  130. tokenAfter &&
  131. node.range[1] === tokenAfter.range[0] &&
  132. !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter)
  133. ) {
  134. suffix = " "; // Math.pow(a, b)in c -> a**b in c
  135. }
  136. }
  137. }
  138. const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase),
  139. exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent),
  140. replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll);
  141. return fixer.replaceText(node, `${prefix}${replacement}${suffix}`);
  142. }
  143. });
  144. }
  145. return {
  146. Program() {
  147. const scope = context.getScope();
  148. const tracker = new ReferenceTracker(scope);
  149. const trackMap = {
  150. Math: {
  151. pow: { [CALL]: true }
  152. }
  153. };
  154. for (const { node } of tracker.iterateGlobalReferences(trackMap)) {
  155. report(node);
  156. }
  157. }
  158. };
  159. }
  160. };