项目原始demo,不改动
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
このリポジトリはアーカイブされています。 ファイルの閲覧とクローンは可能ですが、プッシュや、課題・プルリクエストのオープンはできません。
 
 
 
 

208 行
7.6 KiB

  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("../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. default:
  63. return false;
  64. }
  65. }
  66. /**
  67. * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
  68. * toString calls regardless of whether assignment shorthand is used)
  69. * @param {ASTNode} node The node on the left side of the expression
  70. * @returns {boolean} `true` if the node can be fixed
  71. */
  72. function canBeFixed(node) {
  73. return node.type === "Identifier" ||
  74. node.type === "MemberExpression" && node.object.type === "Identifier" && (!node.computed || node.property.type === "Literal");
  75. }
  76. module.exports = {
  77. meta: {
  78. docs: {
  79. description: "require or disallow assignment operator shorthand where possible",
  80. category: "Stylistic Issues",
  81. recommended: false,
  82. url: "https://eslint.org/docs/rules/operator-assignment"
  83. },
  84. schema: [
  85. {
  86. enum: ["always", "never"]
  87. }
  88. ],
  89. fixable: "code"
  90. },
  91. create(context) {
  92. const sourceCode = context.getSourceCode();
  93. /**
  94. * Returns the operator token of an AssignmentExpression or BinaryExpression
  95. * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
  96. * @returns {Token} The operator token in the node
  97. */
  98. function getOperatorToken(node) {
  99. return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  100. }
  101. /**
  102. * Ensures that an assignment uses the shorthand form where possible.
  103. * @param {ASTNode} node An AssignmentExpression node.
  104. * @returns {void}
  105. */
  106. function verify(node) {
  107. if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
  108. return;
  109. }
  110. const left = node.left;
  111. const expr = node.right;
  112. const operator = expr.operator;
  113. if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
  114. if (same(left, expr.left)) {
  115. context.report({
  116. node,
  117. message: "Assignment can be replaced with operator assignment.",
  118. fix(fixer) {
  119. if (canBeFixed(left)) {
  120. const equalsToken = getOperatorToken(node);
  121. const operatorToken = getOperatorToken(expr);
  122. const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
  123. const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
  124. return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
  125. }
  126. return null;
  127. }
  128. });
  129. } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
  130. /*
  131. * This case can't be fixed safely.
  132. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
  133. * change the execution order of the valueOf() functions.
  134. */
  135. context.report({
  136. node,
  137. message: "Assignment can be replaced with operator assignment."
  138. });
  139. }
  140. }
  141. }
  142. /**
  143. * Warns if an assignment expression uses operator assignment shorthand.
  144. * @param {ASTNode} node An AssignmentExpression node.
  145. * @returns {void}
  146. */
  147. function prohibit(node) {
  148. if (node.operator !== "=") {
  149. context.report({
  150. node,
  151. message: "Unexpected operator assignment shorthand.",
  152. fix(fixer) {
  153. if (canBeFixed(node.left)) {
  154. const operatorToken = getOperatorToken(node);
  155. const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
  156. const newOperator = node.operator.slice(0, -1);
  157. let rightText;
  158. // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
  159. if (
  160. astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
  161. !astUtils.isParenthesised(sourceCode, node.right)
  162. ) {
  163. rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
  164. } else {
  165. rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
  166. }
  167. return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
  168. }
  169. return null;
  170. }
  171. });
  172. }
  173. }
  174. return {
  175. AssignmentExpression: context.options[0] !== "never" ? verify : prohibit
  176. };
  177. }
  178. };