fix(linter/no-unused-vars): do not delete function expressions when fixing (#4848)

`VariableDeclarator` fixer will no longer delete declarations that are initialized to function expressions.

```ts
// none of these get deleted
const unusedArrow = () => {}
const unusedAnon = function() {}
const unusedNamed = function foo() {}

// matches fixer behavior for function declarations
function unusedDecl() {}
```
This commit is contained in:
DonIsaac 2024-08-13 02:31:34 +00:00
parent c53c210efc
commit a81ce3a3c7
2 changed files with 31 additions and 1 deletions

View file

@ -1,4 +1,7 @@
use oxc_ast::{ast::VariableDeclarator, AstKind};
use oxc_ast::{
ast::{Expression, VariableDeclarator},
AstKind,
};
use oxc_semantic::{AstNode, AstNodeId};
use oxc_span::CompactStr;
use regex::Regex;
@ -20,6 +23,10 @@ impl NoUnusedVars {
decl: &VariableDeclarator<'a>,
decl_id: AstNodeId,
) -> RuleFix<'a> {
if decl.init.as_ref().is_some_and(Expression::is_function) {
return fixer.noop();
}
let Some(AstKind::VariableDeclaration(declaration)) =
symbol.nodes().parent_node(decl_id).map(AstNode::kind)
else {

View file

@ -89,6 +89,20 @@ fn test_vars_simple() {
None,
FixKind::DangerousSuggestion,
),
// function expressions do not get changed
(r"const foo = () => {}", r"const foo = () => {}", None, FixKind::DangerousSuggestion),
(
r"const foo = function() {}",
r"const foo = function() {}",
None,
FixKind::DangerousSuggestion,
),
(
r"const foo = function foo() {}",
r"const foo = function foo() {}",
None,
FixKind::DangerousSuggestion,
),
// vars with references get renamed
("let x = 1; x = 2;", "let _x = 1; _x = 2;", None, FixKind::DangerousFix),
(
@ -279,8 +293,10 @@ fn test_vars_destructure() {
];
let fix = vec![
// single destructure
("const { a } = obj;", "", None, FixKind::DangerousSuggestion),
("const [a] = arr;", "", None, FixKind::DangerousSuggestion),
// multi destructure
(
"const { a, b } = obj; f(b)",
"const { b } = obj; f(b)",
@ -313,6 +329,13 @@ fn test_vars_destructure() {
None,
FixKind::DangerousSuggestion,
),
// multi destructure with rename
(
"const { a: foo, b: bar } = obj; f(bar)",
"const { b: bar } = obj; f(bar)",
None,
FixKind::DangerousSuggestion,
),
// renaming
// (
// "let a = 1; a = 2;",