operator-assignment.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 ["*", "&", "^", "|"].indexOf(operator) >= 0;
  22. }
  23. /**
  24. * Checks whether an operator is not commuatative and has an operator assignment
  25. * shorthand form.
  26. * @param {string} operator Operator to check.
  27. * @returns {boolean} True if the operator is not commuatative and has
  28. * a shorthand form.
  29. */
  30. function isNonCommutativeOperatorWithShorthand(operator) {
  31. return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].indexOf(operator) >= 0;
  32. }
  33. //------------------------------------------------------------------------------
  34. // Rule Definition
  35. //------------------------------------------------------------------------------
  36. /**
  37. * Checks whether two expressions reference the same value. For example:
  38. * a = a
  39. * a.b = a.b
  40. * a[0] = a[0]
  41. * a['b'] = a['b']
  42. * @param {ASTNode} a Left side of the comparison.
  43. * @param {ASTNode} b Right side of the comparison.
  44. * @returns {boolean} True if both sides match and reference the same value.
  45. */
  46. function same(a, b) {
  47. if (a.type !== b.type) {
  48. return false;
  49. }
  50. switch (a.type) {
  51. case "Identifier":
  52. return a.name === b.name;
  53. case "Literal":
  54. return a.value === b.value;
  55. case "MemberExpression":
  56. /*
  57. * x[0] = x[0]
  58. * x[y] = x[y]
  59. * x.y = x.y
  60. */
  61. return same(a.object, b.object) && same(a.property, b.property);
  62. case "ThisExpression":
  63. return true;
  64. default:
  65. return false;
  66. }
  67. }
  68. /**
  69. * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
  70. * toString calls regardless of whether assignment shorthand is used)
  71. * @param {ASTNode} node The node on the left side of the expression
  72. * @returns {boolean} `true` if the node can be fixed
  73. */
  74. function canBeFixed(node) {
  75. return (
  76. node.type === "Identifier" ||
  77. (
  78. node.type === "MemberExpression" &&
  79. (node.object.type === "Identifier" || node.object.type === "ThisExpression") &&
  80. (!node.computed || node.property.type === "Literal")
  81. )
  82. );
  83. }
  84. module.exports = {
  85. meta: {
  86. type: "suggestion",
  87. docs: {
  88. description: "require or disallow assignment operator shorthand where possible",
  89. category: "Stylistic Issues",
  90. recommended: false,
  91. url: "https://eslint.org/docs/rules/operator-assignment"
  92. },
  93. schema: [
  94. {
  95. enum: ["always", "never"]
  96. }
  97. ],
  98. fixable: "code",
  99. messages: {
  100. replaced: "Assignment can be replaced with operator assignment.",
  101. unexpected: "Unexpected operator assignment shorthand."
  102. }
  103. },
  104. create(context) {
  105. const sourceCode = context.getSourceCode();
  106. /**
  107. * Returns the operator token of an AssignmentExpression or BinaryExpression
  108. * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
  109. * @returns {Token} The operator token in the node
  110. */
  111. function getOperatorToken(node) {
  112. return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  113. }
  114. /**
  115. * Ensures that an assignment uses the shorthand form where possible.
  116. * @param {ASTNode} node An AssignmentExpression node.
  117. * @returns {void}
  118. */
  119. function verify(node) {
  120. if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
  121. return;
  122. }
  123. const left = node.left;
  124. const expr = node.right;
  125. const operator = expr.operator;
  126. if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
  127. if (same(left, expr.left)) {
  128. context.report({
  129. node,
  130. messageId: "replaced",
  131. fix(fixer) {
  132. if (canBeFixed(left)) {
  133. const equalsToken = getOperatorToken(node);
  134. const operatorToken = getOperatorToken(expr);
  135. const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
  136. const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
  137. // Check for comments that would be removed.
  138. if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) {
  139. return null;
  140. }
  141. return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
  142. }
  143. return null;
  144. }
  145. });
  146. } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
  147. /*
  148. * This case can't be fixed safely.
  149. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
  150. * change the execution order of the valueOf() functions.
  151. */
  152. context.report({
  153. node,
  154. messageId: "replaced"
  155. });
  156. }
  157. }
  158. }
  159. /**
  160. * Warns if an assignment expression uses operator assignment shorthand.
  161. * @param {ASTNode} node An AssignmentExpression node.
  162. * @returns {void}
  163. */
  164. function prohibit(node) {
  165. if (node.operator !== "=") {
  166. context.report({
  167. node,
  168. messageId: "unexpected",
  169. fix(fixer) {
  170. if (canBeFixed(node.left)) {
  171. const firstToken = sourceCode.getFirstToken(node);
  172. const operatorToken = getOperatorToken(node);
  173. const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
  174. const newOperator = node.operator.slice(0, -1);
  175. let rightText;
  176. // Check for comments that would be duplicated.
  177. if (sourceCode.commentsExistBetween(firstToken, operatorToken)) {
  178. return null;
  179. }
  180. // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
  181. if (
  182. astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
  183. !astUtils.isParenthesised(sourceCode, node.right)
  184. ) {
  185. rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
  186. } else {
  187. const firstRightToken = sourceCode.getFirstToken(node.right);
  188. let rightTextPrefix = "";
  189. if (
  190. operatorToken.range[1] === firstRightToken.range[0] &&
  191. !astUtils.canTokensBeAdjacent(newOperator, firstRightToken)
  192. ) {
  193. rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
  194. }
  195. rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
  196. }
  197. return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
  198. }
  199. return null;
  200. }
  201. });
  202. }
  203. }
  204. return {
  205. AssignmentExpression: context.options[0] !== "never" ? verify : prohibit
  206. };
  207. }
  208. };