1 | /**
|
2 | * @fileoverview Rule to disallow negating the left operand of relational operators
|
3 | * @author Toru Nagashima
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | const astUtils = require("../ast-utils");
|
13 |
|
14 | //------------------------------------------------------------------------------
|
15 | // Helpers
|
16 | //------------------------------------------------------------------------------
|
17 |
|
18 | /**
|
19 | * Checks whether the given operator is a relational operator or not.
|
20 | *
|
21 | * @param {string} op - The operator type to check.
|
22 | * @returns {boolean} `true` if the operator is a relational operator.
|
23 | */
|
24 | function isRelationalOperator(op) {
|
25 | return op === "in" || op === "instanceof";
|
26 | }
|
27 |
|
28 | /**
|
29 | * Checks whether the given node is a logical negation expression or not.
|
30 | *
|
31 | * @param {ASTNode} node - The node to check.
|
32 | * @returns {boolean} `true` if the node is a logical negation expression.
|
33 | */
|
34 | function isNegation(node) {
|
35 | return node.type === "UnaryExpression" && node.operator === "!";
|
36 | }
|
37 |
|
38 | //------------------------------------------------------------------------------
|
39 | // Rule Definition
|
40 | //------------------------------------------------------------------------------
|
41 |
|
42 | module.exports = {
|
43 | meta: {
|
44 | docs: {
|
45 | description: "disallow negating the left operand of relational operators",
|
46 | category: "Possible Errors",
|
47 | recommended: true,
|
48 | url: "https://eslint.org/docs/rules/no-unsafe-negation"
|
49 | },
|
50 | schema: [],
|
51 | fixable: "code"
|
52 | },
|
53 |
|
54 | create(context) {
|
55 | const sourceCode = context.getSourceCode();
|
56 |
|
57 | return {
|
58 | BinaryExpression(node) {
|
59 | if (isRelationalOperator(node.operator) &&
|
60 | isNegation(node.left) &&
|
61 | !astUtils.isParenthesised(sourceCode, node.left)
|
62 | ) {
|
63 | context.report({
|
64 | node,
|
65 | loc: node.left.loc,
|
66 | message: "Unexpected negating the left operand of '{{operator}}' operator.",
|
67 | data: node,
|
68 |
|
69 | fix(fixer) {
|
70 | const negationToken = sourceCode.getFirstToken(node.left);
|
71 | const fixRange = [negationToken.range[1], node.range[1]];
|
72 | const text = sourceCode.text.slice(fixRange[0], fixRange[1]);
|
73 |
|
74 | return fixer.replaceTextRange(fixRange, `(${text})`);
|
75 | }
|
76 | });
|
77 | }
|
78 | }
|
79 | };
|
80 | }
|
81 | };
|