Skip to content

Commit

Permalink
Fix: operator-assignment invalid autofix with adjacent tokens (#12483)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic authored and platinumazure committed Oct 25, 2019
1 parent 0f6d0dc commit 52ca11a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/rules/operator-assignment.js
Expand Up @@ -194,7 +194,17 @@ module.exports = {
) {
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
} else {
rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
const firstRightToken = sourceCode.getFirstToken(node.right);
let rightTextPrefix = "";

if (
operatorToken.range[1] === firstRightToken.range[0] &&
!astUtils.canTokensBeAdjacent(newOperator, firstRightToken)
) {
rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
}

rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
}

return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
Expand Down
25 changes: 25 additions & 0 deletions tests/lib/rules/operator-assignment.js
Expand Up @@ -230,6 +230,31 @@ ruleTester.run("operator-assignment", rule, {
output: "foo = foo * (bar + 1)",
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=-bar",
output: "foo= foo+-bar", // tokens can be adjacent
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=+bar",
output: "foo= foo+ +bar", // tokens cannot be adjacent, insert a space between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+= +bar",
output: "foo= foo+ +bar", // tokens cannot be adjacent, but there is already a space between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=/**/+bar",
output: "foo= foo+/**/+bar", // tokens cannot be adjacent, but there is a comment between
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}, {
code: "foo+=+bar===baz",
output: "foo= foo+(+bar===baz)", // tokens cannot be adjacent, but the right side will be parenthesised
options: ["never"],
errors: UNEXPECTED_OPERATOR_ASSIGNMENT
}]

});

0 comments on commit 52ca11a

Please sign in to comment.