Skip to content

Commit

Permalink
dont provide suggestions if removing console.log() will lead to ASI b…
Browse files Browse the repository at this point in the history
…reaking
  • Loading branch information
Rec0iL99 committed Nov 7, 2023
1 parent a74dc87 commit f112803
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
36 changes: 35 additions & 1 deletion lib/rules/no-console.js
Expand Up @@ -97,6 +97,39 @@ module.exports = {
);
}

/**
* Checks if removing the MemberExpression node will cause ASI to
* break.
* eg.
* foo()
* console.log();
* [1, 2, 3].forEach(a => doSomething(a))
*
* Removing the console.log(); statement should leave two statements, but
* here the two statements will become one because [ causes continuation after
* foo().
* @param {ASTNode} node The MemberExpression node to check.
* @returns {boolean} `true` if ASI will break after removing the MemberExpression
* node
*/
function maybeAsiHazard(node) {
const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-`
const CONTINUATION_PATTERN = /^[:;{]/u; // One of :;{
const tokenBefore = sourceCode.getTokenBefore(node.parent.parent);
const tokenAfter = sourceCode.getTokenAfter(node.parent.parent);

return (
Boolean(tokenAfter) &&
OPT_OUT_PATTERN.test(tokenAfter.value) &&
tokenAfter.value !== "++" &&
tokenAfter.value !== "--" &&
Boolean(tokenBefore) &&
!CONTINUATION_PATTERN.test(tokenBefore.value) &&
tokenBefore.value !== "++" &&
tokenBefore.value !== "--"
);
}

/**
* Checks if the MemberExpression node's parent.parent.parent is a
* Program, BlockStatement, StaticBlock, or SwitchCase node. This check
Expand All @@ -118,7 +151,8 @@ module.exports = {
node.parent.type === "CallExpression" &&
node.parent.callee === node &&
node.parent.parent.type === "ExpressionStatement" &&
astUtils.STATEMENT_LIST_PARENTS.has(node.parent.parent.parent.type)
astUtils.STATEMENT_LIST_PARENTS.has(node.parent.parent.parent.type) &&
!maybeAsiHazard(node)
);
}

Expand Down
22 changes: 22 additions & 0 deletions tests/lib/rules/no-console.js
Expand Up @@ -153,6 +153,28 @@ ruleTester.run("no-console", rule, {
}]
}]
},
{
code: "a()\nconsole.log(foo);\n[1, 2, 3].forEach(a => doSomething(a))",
parserOptions: { ecmaVersion: "latest" },
errors: [{
messageId: "unexpected",
type: "MemberExpression",
suggestions: null
}]
},
{
code: "a();\nconsole.log(foo);\n[1, 2, 3].forEach(a => doSomething(a));",
parserOptions: { ecmaVersion: "latest" },
errors: [{
messageId: "unexpected",
type: "MemberExpression",
suggestions: [{
messageId: "removeConsole",
data: { propertyName: "log" },
output: "a();\n\n[1, 2, 3].forEach(a => doSomething(a));"
}]
}]
},

// one option
{
Expand Down

0 comments on commit f112803

Please sign in to comment.