Skip to content

Commit

Permalink
Fix: no-implicit-coercion invalid autofix with consecutive identifiers (
Browse files Browse the repository at this point in the history
#8340)

Previously, the no-implicit-coercion rule would convert code like `typeof+foo` to `typeofNumber(foo)`, combining the `typeof` keyword with the following identifier and changing the semantics. This commit updates the no-implicit-coercion autofixer to prevent that from happening.
  • Loading branch information
not-an-aardvark authored and ilyavolodin committed Mar 28, 2017
1 parent 41b9786 commit 0541eaf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
29 changes: 21 additions & 8 deletions lib/rules/no-implicit-coercion.js
Expand Up @@ -6,6 +6,7 @@
"use strict";

const astUtils = require("../ast-utils");
const esUtils = require("esutils");

//------------------------------------------------------------------------------
// Helpers
Expand Down Expand Up @@ -197,19 +198,31 @@ module.exports = {
*/
function report(node, recommendation, shouldFix) {
shouldFix = typeof shouldFix === "undefined" ? true : shouldFix;
const reportObj = {

context.report({
node,
message: "use `{{recommendation}}` instead.",
data: {
recommendation
},
fix(fixer) {
if (!shouldFix) {
return null;
}

const tokenBefore = sourceCode.getTokenBefore(node);

if (
tokenBefore &&
tokenBefore.range[1] === node.range[0] &&
esUtils.code.isIdentifierPartES6(tokenBefore.value.slice(-1).charCodeAt(0)) &&
esUtils.code.isIdentifierPartES6(recommendation.charCodeAt(0))
) {
return fixer.replaceText(node, ` ${recommendation}`);
}
return fixer.replaceText(node, recommendation);
}
};

if (shouldFix) {
reportObj.fix = fixer => fixer.replaceText(node, recommendation);
}

context.report(reportObj);
});
}

return {
Expand Down
10 changes: 10 additions & 0 deletions tests/lib/rules/no-implicit-coercion.js
Expand Up @@ -221,6 +221,16 @@ ruleTester.run("no-implicit-coercion", rule, {
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "use `String(foo)` instead.", type: "BinaryExpression" }],
output: "var a = String(foo)"
},
{
code: "typeof+foo",
output: "typeof Number(foo)",
errors: [{ message: "use `Number(foo)` instead.", type: "UnaryExpression" }]
},
{
code: "typeof +foo",
output: "typeof Number(foo)",
errors: [{ message: "use `Number(foo)` instead.", type: "UnaryExpression" }]
}
]
});

0 comments on commit 0541eaf

Please sign in to comment.