no-mixed-operators.js 8.1 KB

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