operator-assignment.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. (node.type === "MemberExpression" &&
  46. (node.object.type === "Identifier" ||
  47. node.object.type === "ThisExpression") &&
  48. (!node.computed || node.property.type === "Literal"))
  49. );
  50. }
  51. /** @type {import('../types').Rule.RuleModule} */
  52. module.exports = {
  53. meta: {
  54. type: "suggestion",
  55. defaultOptions: ["always"],
  56. docs: {
  57. description:
  58. "Require or disallow assignment operator shorthand where possible",
  59. recommended: false,
  60. frozen: true,
  61. url: "https://eslint.org/docs/latest/rules/operator-assignment",
  62. },
  63. schema: [
  64. {
  65. enum: ["always", "never"],
  66. },
  67. ],
  68. fixable: "code",
  69. messages: {
  70. replaced:
  71. "Assignment (=) can be replaced with operator assignment ({{operator}}).",
  72. unexpected:
  73. "Unexpected operator assignment ({{operator}}) shorthand.",
  74. },
  75. },
  76. create(context) {
  77. const never = context.options[0] === "never";
  78. const sourceCode = context.sourceCode;
  79. /**
  80. * Returns the operator token of an AssignmentExpression or BinaryExpression
  81. * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
  82. * @returns {Token} The operator token in the node
  83. */
  84. function getOperatorToken(node) {
  85. return sourceCode.getFirstTokenBetween(
  86. node.left,
  87. node.right,
  88. token => token.value === node.operator,
  89. );
  90. }
  91. /**
  92. * Ensures that an assignment uses the shorthand form where possible.
  93. * @param {ASTNode} node An AssignmentExpression node.
  94. * @returns {void}
  95. */
  96. function verify(node) {
  97. if (
  98. node.operator !== "=" ||
  99. node.right.type !== "BinaryExpression"
  100. ) {
  101. return;
  102. }
  103. const left = node.left;
  104. const expr = node.right;
  105. const operator = expr.operator;
  106. if (
  107. isCommutativeOperatorWithShorthand(operator) ||
  108. isNonCommutativeOperatorWithShorthand(operator)
  109. ) {
  110. const replacementOperator = `${operator}=`;
  111. if (astUtils.isSameReference(left, expr.left, true)) {
  112. context.report({
  113. node,
  114. messageId: "replaced",
  115. data: { operator: replacementOperator },
  116. fix(fixer) {
  117. if (canBeFixed(left) && canBeFixed(expr.left)) {
  118. const equalsToken = getOperatorToken(node);
  119. const operatorToken = getOperatorToken(expr);
  120. const leftText = sourceCode
  121. .getText()
  122. .slice(node.range[0], equalsToken.range[0]);
  123. const rightText = sourceCode
  124. .getText()
  125. .slice(
  126. operatorToken.range[1],
  127. node.right.range[1],
  128. );
  129. // Check for comments that would be removed.
  130. if (
  131. sourceCode.commentsExistBetween(
  132. equalsToken,
  133. operatorToken,
  134. )
  135. ) {
  136. return null;
  137. }
  138. return fixer.replaceText(
  139. node,
  140. `${leftText}${replacementOperator}${rightText}`,
  141. );
  142. }
  143. return null;
  144. },
  145. });
  146. } else if (
  147. astUtils.isSameReference(left, expr.right, true) &&
  148. isCommutativeOperatorWithShorthand(operator)
  149. ) {
  150. /*
  151. * This case can't be fixed safely.
  152. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
  153. * change the execution order of the valueOf() functions.
  154. */
  155. context.report({
  156. node,
  157. messageId: "replaced",
  158. data: { operator: replacementOperator },
  159. });
  160. }
  161. }
  162. }
  163. /**
  164. * Warns if an assignment expression uses operator assignment shorthand.
  165. * @param {ASTNode} node An AssignmentExpression node.
  166. * @returns {void}
  167. */
  168. function prohibit(node) {
  169. if (
  170. node.operator !== "=" &&
  171. !astUtils.isLogicalAssignmentOperator(node.operator)
  172. ) {
  173. context.report({
  174. node,
  175. messageId: "unexpected",
  176. data: { operator: node.operator },
  177. fix(fixer) {
  178. if (canBeFixed(node.left)) {
  179. const firstToken = sourceCode.getFirstToken(node);
  180. const operatorToken = getOperatorToken(node);
  181. const leftText = sourceCode
  182. .getText()
  183. .slice(node.range[0], operatorToken.range[0]);
  184. const newOperator = node.operator.slice(0, -1);
  185. let rightText;
  186. // Check for comments that would be duplicated.
  187. if (
  188. sourceCode.commentsExistBetween(
  189. firstToken,
  190. operatorToken,
  191. )
  192. ) {
  193. return null;
  194. }
  195. // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
  196. if (
  197. astUtils.getPrecedence(node.right) <=
  198. astUtils.getPrecedence({
  199. type: "BinaryExpression",
  200. operator: newOperator,
  201. }) &&
  202. !astUtils.isParenthesised(
  203. sourceCode,
  204. node.right,
  205. )
  206. ) {
  207. rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
  208. } else {
  209. const tokenAfterOperator =
  210. sourceCode.getTokenAfter(operatorToken, {
  211. includeComments: true,
  212. });
  213. let rightTextPrefix = "";
  214. if (
  215. operatorToken.range[1] ===
  216. tokenAfterOperator.range[0] &&
  217. !astUtils.canTokensBeAdjacent(
  218. {
  219. type: "Punctuator",
  220. value: newOperator,
  221. },
  222. tokenAfterOperator,
  223. )
  224. ) {
  225. rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
  226. }
  227. rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
  228. }
  229. return fixer.replaceText(
  230. node,
  231. `${leftText}= ${leftText}${newOperator}${rightText}`,
  232. );
  233. }
  234. return null;
  235. },
  236. });
  237. }
  238. }
  239. return {
  240. AssignmentExpression: !never ? verify : prohibit,
  241. };
  242. },
  243. };