prefer-exponentiation-operator.js 7.4 KB

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