UNPKG

3.09 kBJavaScriptView Raw
1"use strict";
2/*
3 * eslint-plugin-sonarjs
4 * Copyright (C) 2018-2021 SonarSource SA
5 * mailto:info AT sonarsource DOT com
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 */
21// https://sonarsource.github.io/rspec/#/rspec/S2757
22const docs_url_1 = require("../utils/docs-url");
23const rule = {
24 meta: {
25 type: 'problem',
26 docs: {
27 description: 'Non-existent operators "=+", "=-" and "=!" should not be used',
28 category: 'Possible Errors',
29 recommended: 'error',
30 url: docs_url_1.default(__filename),
31 },
32 },
33 create(context) {
34 return {
35 AssignmentExpression(node) {
36 const assignmentExpression = node;
37 if (assignmentExpression.operator === '=') {
38 checkOperator(context, assignmentExpression.right);
39 }
40 },
41 VariableDeclarator(node) {
42 const variableDeclarator = node;
43 checkOperator(context, variableDeclarator.init);
44 },
45 };
46 },
47};
48function checkOperator(context, unaryNode) {
49 if (unaryNode &&
50 unaryNode.type === 'UnaryExpression' &&
51 isUnaryOperatorOfInterest(unaryNode.operator)) {
52 const sourceCode = context.getSourceCode();
53 const assignmentOperatorToken = sourceCode.getTokenBefore(unaryNode, token => token.value === '=');
54 const unaryOperatorToken = sourceCode.getFirstToken(unaryNode);
55 const expressionFirstToken = sourceCode.getFirstToken(unaryNode.argument);
56 if (assignmentOperatorToken != null &&
57 unaryOperatorToken != null &&
58 expressionFirstToken != null &&
59 areAdjacent(assignmentOperatorToken, unaryOperatorToken) &&
60 !areAdjacent(unaryOperatorToken, expressionFirstToken)) {
61 context.report({
62 message: `Was "${unaryNode.operator}=" meant instead?`,
63 loc: { start: assignmentOperatorToken.loc.start, end: unaryOperatorToken.loc.end },
64 });
65 }
66 }
67}
68function isUnaryOperatorOfInterest(operator) {
69 return operator === '-' || operator === '+' || operator === '!';
70}
71function areAdjacent(first, second) {
72 return (first.loc.end.column === second.loc.start.column && first.loc.end.line === second.loc.start.line);
73}
74module.exports = rule;
75//# sourceMappingURL=non-existent-operator.js.map
\No newline at end of file