Skip to content

Commit 0541eaf

Browse files
not-an-aardvarkilyavolodin
authored andcommitted
Fix: no-implicit-coercion invalid autofix with consecutive identifiers (#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.
1 parent 41b9786 commit 0541eaf

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

lib/rules/no-implicit-coercion.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"use strict";
77

88
const astUtils = require("../ast-utils");
9+
const esUtils = require("esutils");
910

1011
//------------------------------------------------------------------------------
1112
// Helpers
@@ -197,19 +198,31 @@ module.exports = {
197198
*/
198199
function report(node, recommendation, shouldFix) {
199200
shouldFix = typeof shouldFix === "undefined" ? true : shouldFix;
200-
const reportObj = {
201+
202+
context.report({
201203
node,
202204
message: "use `{{recommendation}}` instead.",
203205
data: {
204206
recommendation
207+
},
208+
fix(fixer) {
209+
if (!shouldFix) {
210+
return null;
211+
}
212+
213+
const tokenBefore = sourceCode.getTokenBefore(node);
214+
215+
if (
216+
tokenBefore &&
217+
tokenBefore.range[1] === node.range[0] &&
218+
esUtils.code.isIdentifierPartES6(tokenBefore.value.slice(-1).charCodeAt(0)) &&
219+
esUtils.code.isIdentifierPartES6(recommendation.charCodeAt(0))
220+
) {
221+
return fixer.replaceText(node, ` ${recommendation}`);
222+
}
223+
return fixer.replaceText(node, recommendation);
205224
}
206-
};
207-
208-
if (shouldFix) {
209-
reportObj.fix = fixer => fixer.replaceText(node, recommendation);
210-
}
211-
212-
context.report(reportObj);
225+
});
213226
}
214227

215228
return {

tests/lib/rules/no-implicit-coercion.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,16 @@ ruleTester.run("no-implicit-coercion", rule, {
221221
parserOptions: { ecmaVersion: 6 },
222222
errors: [{ message: "use `String(foo)` instead.", type: "BinaryExpression" }],
223223
output: "var a = String(foo)"
224+
},
225+
{
226+
code: "typeof+foo",
227+
output: "typeof Number(foo)",
228+
errors: [{ message: "use `Number(foo)` instead.", type: "UnaryExpression" }]
229+
},
230+
{
231+
code: "typeof +foo",
232+
output: "typeof Number(foo)",
233+
errors: [{ message: "use `Number(foo)` instead.", type: "UnaryExpression" }]
224234
}
225235
]
226236
});

0 commit comments

Comments
 (0)