UNPKG

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