no-mixed-operators.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /**
  2. * @fileoverview Rule to disallow mixed binary operators.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils.js");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"];
  14. const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"];
  15. const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="];
  16. const LOGICAL_OPERATORS = ["&&", "||"];
  17. const RELATIONAL_OPERATORS = ["in", "instanceof"];
  18. const TERNARY_OPERATOR = ["?:"];
  19. const COALESCE_OPERATOR = ["??"];
  20. const ALL_OPERATORS = [].concat(
  21. ARITHMETIC_OPERATORS,
  22. BITWISE_OPERATORS,
  23. COMPARISON_OPERATORS,
  24. LOGICAL_OPERATORS,
  25. RELATIONAL_OPERATORS,
  26. TERNARY_OPERATOR,
  27. COALESCE_OPERATOR
  28. );
  29. const DEFAULT_GROUPS = [
  30. ARITHMETIC_OPERATORS,
  31. BITWISE_OPERATORS,
  32. COMPARISON_OPERATORS,
  33. LOGICAL_OPERATORS,
  34. RELATIONAL_OPERATORS
  35. ];
  36. const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u;
  37. /**
  38. * Normalizes options.
  39. * @param {Object|undefined} options A options object to normalize.
  40. * @returns {Object} Normalized option object.
  41. */
  42. function normalizeOptions(options = {}) {
  43. const hasGroups = options.groups && options.groups.length > 0;
  44. const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
  45. const allowSamePrecedence = options.allowSamePrecedence !== false;
  46. return {
  47. groups,
  48. allowSamePrecedence
  49. };
  50. }
  51. /**
  52. * Checks whether any group which includes both given operator exists or not.
  53. * @param {Array.<string[]>} groups A list of groups to check.
  54. * @param {string} left An operator.
  55. * @param {string} right Another operator.
  56. * @returns {boolean} `true` if such group existed.
  57. */
  58. function includesBothInAGroup(groups, left, right) {
  59. return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
  60. }
  61. /**
  62. * Checks whether the given node is a conditional expression and returns the test node else the left node.
  63. * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node.
  64. * This parent node can be BinaryExpression, LogicalExpression
  65. * , or a ConditionalExpression node
  66. * @returns {ASTNode} node the appropriate node(left or test).
  67. */
  68. function getChildNode(node) {
  69. return node.type === "ConditionalExpression" ? node.test : node.left;
  70. }
  71. //------------------------------------------------------------------------------
  72. // Rule Definition
  73. //------------------------------------------------------------------------------
  74. module.exports = {
  75. meta: {
  76. type: "suggestion",
  77. docs: {
  78. description: "disallow mixed binary operators",
  79. category: "Stylistic Issues",
  80. recommended: false,
  81. url: "https://eslint.org/docs/rules/no-mixed-operators"
  82. },
  83. schema: [
  84. {
  85. type: "object",
  86. properties: {
  87. groups: {
  88. type: "array",
  89. items: {
  90. type: "array",
  91. items: { enum: ALL_OPERATORS },
  92. minItems: 2,
  93. uniqueItems: true
  94. },
  95. uniqueItems: true
  96. },
  97. allowSamePrecedence: {
  98. type: "boolean",
  99. default: true
  100. }
  101. },
  102. additionalProperties: false
  103. }
  104. ],
  105. messages: {
  106. unexpectedMixedOperator: "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'."
  107. }
  108. },
  109. create(context) {
  110. const sourceCode = context.getSourceCode();
  111. const options = normalizeOptions(context.options[0]);
  112. /**
  113. * Checks whether a given node should be ignored by options or not.
  114. * @param {ASTNode} node A node to check. This is a BinaryExpression
  115. * node or a LogicalExpression node. This parent node is one of
  116. * them, too.
  117. * @returns {boolean} `true` if the node should be ignored.
  118. */
  119. function shouldIgnore(node) {
  120. const a = node;
  121. const b = node.parent;
  122. return (
  123. !includesBothInAGroup(options.groups, a.operator, b.type === "ConditionalExpression" ? "?:" : b.operator) ||
  124. (
  125. options.allowSamePrecedence &&
  126. astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
  127. )
  128. );
  129. }
  130. /**
  131. * Checks whether the operator of a given node is mixed with parent
  132. * node's operator or not.
  133. * @param {ASTNode} node A node to check. This is a BinaryExpression
  134. * node or a LogicalExpression node. This parent node is one of
  135. * them, too.
  136. * @returns {boolean} `true` if the node was mixed.
  137. */
  138. function isMixedWithParent(node) {
  139. return (
  140. node.operator !== node.parent.operator &&
  141. !astUtils.isParenthesised(sourceCode, node)
  142. );
  143. }
  144. /**
  145. * Gets the operator token of a given node.
  146. * @param {ASTNode} node A node to check. This is a BinaryExpression
  147. * node or a LogicalExpression node.
  148. * @returns {Token} The operator token of the node.
  149. */
  150. function getOperatorToken(node) {
  151. return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken);
  152. }
  153. /**
  154. * Reports both the operator of a given node and the operator of the
  155. * parent node.
  156. * @param {ASTNode} node A node to check. This is a BinaryExpression
  157. * node or a LogicalExpression node. This parent node is one of
  158. * them, too.
  159. * @returns {void}
  160. */
  161. function reportBothOperators(node) {
  162. const parent = node.parent;
  163. const left = (getChildNode(parent) === node) ? node : parent;
  164. const right = (getChildNode(parent) !== node) ? node : parent;
  165. const data = {
  166. leftOperator: left.operator || "?:",
  167. rightOperator: right.operator || "?:"
  168. };
  169. context.report({
  170. node: left,
  171. loc: getOperatorToken(left).loc,
  172. messageId: "unexpectedMixedOperator",
  173. data
  174. });
  175. context.report({
  176. node: right,
  177. loc: getOperatorToken(right).loc,
  178. messageId: "unexpectedMixedOperator",
  179. data
  180. });
  181. }
  182. /**
  183. * Checks between the operator of this node and the operator of the
  184. * parent node.
  185. * @param {ASTNode} node A node to check.
  186. * @returns {void}
  187. */
  188. function check(node) {
  189. if (
  190. TARGET_NODE_TYPE.test(node.parent.type) &&
  191. isMixedWithParent(node) &&
  192. !shouldIgnore(node)
  193. ) {
  194. reportBothOperators(node);
  195. }
  196. }
  197. return {
  198. BinaryExpression: check,
  199. LogicalExpression: check
  200. };
  201. }
  202. };