Skip to content
Permalink
Browse files

Fix: operator-assignment invalid autofix with adjacent tokens (#12483)

  • Loading branch information
mdjermanovic authored and platinumazure committed Oct 25, 2019
1 parent 0f6d0dc commit 52ca11a66ab6c2fb5a71d8b9869482f14f98cb9d
Showing with 36 additions and 1 deletion.
  1. +11 −1 lib/rules/operator-assignment.js
  2. +25 −0 tests/lib/rules/operator-assignment.js
@@ -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}`);
@@ -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.
You can’t perform that action at this time.