no-mixed-operators.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. * Checks whether the operator of a given node is mixed with a
  146. * conditional expression.
  147. * @param {ASTNode} node A node to check. This is a conditional
  148. * expression node
  149. * @returns {boolean} `true` if the node was mixed.
  150. */
  151. function isMixedWithConditionalParent(node) {
  152. return !astUtils.isParenthesised(sourceCode, node) && !astUtils.isParenthesised(sourceCode, node.test);
  153. }
  154. /**
  155. * Gets the operator token of a given node.
  156. * @param {ASTNode} node A node to check. This is a BinaryExpression
  157. * node or a LogicalExpression node.
  158. * @returns {Token} The operator token of the node.
  159. */
  160. function getOperatorToken(node) {
  161. return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken);
  162. }
  163. /**
  164. * Reports both the operator of a given node and the operator of the
  165. * parent node.
  166. * @param {ASTNode} node A node to check. This is a BinaryExpression
  167. * node or a LogicalExpression node. This parent node is one of
  168. * them, too.
  169. * @returns {void}
  170. */
  171. function reportBothOperators(node) {
  172. const parent = node.parent;
  173. const left = (getChildNode(parent) === node) ? node : parent;
  174. const right = (getChildNode(parent) !== node) ? node : parent;
  175. const data = {
  176. leftOperator: left.operator || "?:",
  177. rightOperator: right.operator || "?:"
  178. };
  179. context.report({
  180. node: left,
  181. loc: getOperatorToken(left).loc,
  182. messageId: "unexpectedMixedOperator",
  183. data
  184. });
  185. context.report({
  186. node: right,
  187. loc: getOperatorToken(right).loc,
  188. messageId: "unexpectedMixedOperator",
  189. data
  190. });
  191. }
  192. /**
  193. * Checks between the operator of this node and the operator of the
  194. * parent node.
  195. * @param {ASTNode} node A node to check.
  196. * @returns {void}
  197. */
  198. function check(node) {
  199. if (TARGET_NODE_TYPE.test(node.parent.type)) {
  200. if (node.parent.type === "ConditionalExpression" && !shouldIgnore(node) && isMixedWithConditionalParent(node.parent)) {
  201. reportBothOperators(node);
  202. } else {
  203. if (TARGET_NODE_TYPE.test(node.parent.type) &&
  204. isMixedWithParent(node) &&
  205. !shouldIgnore(node)
  206. ) {
  207. reportBothOperators(node);
  208. }
  209. }
  210. }
  211. }
  212. return {
  213. BinaryExpression: check,
  214. LogicalExpression: check
  215. };
  216. }
  217. };