operator-assignment.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /**
  2. * @fileoverview Rule to replace assignment expressions with operator assignment
  3. * @author Brandon Mills
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Checks whether an operator is commutative and has an operator assignment
  15. * shorthand form.
  16. * @param {string} operator Operator to check.
  17. * @returns {boolean} True if the operator is commutative and has a
  18. * shorthand form.
  19. */
  20. function isCommutativeOperatorWithShorthand(operator) {
  21. return ["*", "&", "^", "|"].includes(operator);
  22. }
  23. /**
  24. * Checks whether an operator is not commutative and has an operator assignment
  25. * shorthand form.
  26. * @param {string} operator Operator to check.
  27. * @returns {boolean} True if the operator is not commutative and has
  28. * a shorthand form.
  29. */
  30. function isNonCommutativeOperatorWithShorthand(operator) {
  31. return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator);
  32. }
  33. //------------------------------------------------------------------------------
  34. // Rule Definition
  35. //------------------------------------------------------------------------------
  36. /**
  37. * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
  38. * toString calls regardless of whether assignment shorthand is used)
  39. * @param {ASTNode} node The node on the left side of the expression
  40. * @returns {boolean} `true` if the node can be fixed
  41. */
  42. function canBeFixed(node) {
  43. return (
  44. node.type === "Identifier" ||
  45. (
  46. node.type === "MemberExpression" &&
  47. (node.object.type === "Identifier" || node.object.type === "ThisExpression") &&
  48. (!node.computed || node.property.type === "Literal")
  49. )
  50. );
  51. }
  52. /** @type {import('../shared/types').Rule} */
  53. module.exports = {
  54. meta: {
  55. type: "suggestion",
  56. docs: {
  57. description: "Require or disallow assignment operator shorthand where possible",
  58. recommended: false,
  59. url: "https://eslint.org/docs/rules/operator-assignment"
  60. },
  61. schema: [
  62. {
  63. enum: ["always", "never"]
  64. }
  65. ],
  66. fixable: "code",
  67. messages: {
  68. replaced: "Assignment (=) can be replaced with operator assignment ({{operator}}).",
  69. unexpected: "Unexpected operator assignment ({{operator}}) shorthand."
  70. }
  71. },
  72. create(context) {
  73. const sourceCode = context.getSourceCode();
  74. /**
  75. * Returns the operator token of an AssignmentExpression or BinaryExpression
  76. * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
  77. * @returns {Token} The operator token in the node
  78. */
  79. function getOperatorToken(node) {
  80. return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  81. }
  82. /**
  83. * Ensures that an assignment uses the shorthand form where possible.
  84. * @param {ASTNode} node An AssignmentExpression node.
  85. * @returns {void}
  86. */
  87. function verify(node) {
  88. if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
  89. return;
  90. }
  91. const left = node.left;
  92. const expr = node.right;
  93. const operator = expr.operator;
  94. if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
  95. const replacementOperator = `${operator}=`;
  96. if (astUtils.isSameReference(left, expr.left, true)) {
  97. context.report({
  98. node,
  99. messageId: "replaced",
  100. data: { operator: replacementOperator },
  101. fix(fixer) {
  102. if (canBeFixed(left) && canBeFixed(expr.left)) {
  103. const equalsToken = getOperatorToken(node);
  104. const operatorToken = getOperatorToken(expr);
  105. const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
  106. const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
  107. // Check for comments that would be removed.
  108. if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) {
  109. return null;
  110. }
  111. return fixer.replaceText(node, `${leftText}${replacementOperator}${rightText}`);
  112. }
  113. return null;
  114. }
  115. });
  116. } else if (astUtils.isSameReference(left, expr.right, true) && isCommutativeOperatorWithShorthand(operator)) {
  117. /*
  118. * This case can't be fixed safely.
  119. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
  120. * change the execution order of the valueOf() functions.
  121. */
  122. context.report({
  123. node,
  124. messageId: "replaced",
  125. data: { operator: replacementOperator }
  126. });
  127. }
  128. }
  129. }
  130. /**
  131. * Warns if an assignment expression uses operator assignment shorthand.
  132. * @param {ASTNode} node An AssignmentExpression node.
  133. * @returns {void}
  134. */
  135. function prohibit(node) {
  136. if (node.operator !== "=" && !astUtils.isLogicalAssignmentOperator(node.operator)) {
  137. context.report({
  138. node,
  139. messageId: "unexpected",
  140. data: { operator: node.operator },
  141. fix(fixer) {
  142. if (canBeFixed(node.left)) {
  143. const firstToken = sourceCode.getFirstToken(node);
  144. const operatorToken = getOperatorToken(node);
  145. const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
  146. const newOperator = node.operator.slice(0, -1);
  147. let rightText;
  148. // Check for comments that would be duplicated.
  149. if (sourceCode.commentsExistBetween(firstToken, operatorToken)) {
  150. return null;
  151. }
  152. // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
  153. if (
  154. astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
  155. !astUtils.isParenthesised(sourceCode, node.right)
  156. ) {
  157. rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
  158. } else {
  159. const tokenAfterOperator = sourceCode.getTokenAfter(operatorToken, { includeComments: true });
  160. let rightTextPrefix = "";
  161. if (
  162. operatorToken.range[1] === tokenAfterOperator.range[0] &&
  163. !astUtils.canTokensBeAdjacent({ type: "Punctuator", value: newOperator }, tokenAfterOperator)
  164. ) {
  165. rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
  166. }
  167. rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
  168. }
  169. return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
  170. }
  171. return null;
  172. }
  173. });
  174. }
  175. }
  176. return {
  177. AssignmentExpression: context.options[0] !== "never" ? verify : prohibit
  178. };
  179. }
  180. };