fix(linter/no-unused-vars): function expression in implicit arrow function return (#5155)

Fixes cases such as:
```ts
export const foo = () => function bar() {}
```
This commit is contained in:
DonIsaac 2024-08-24 15:49:56 +00:00
parent 147b37176b
commit d29042e7fc
3 changed files with 24 additions and 1 deletions

View file

@ -52,7 +52,15 @@ impl<'s, 'a> Symbol<'s, 'a> {
AstKind::AssignmentExpression(assignment) if assignment.right.span().contains_inclusive(self.span()) => {
return self != &assignment.left;
}
AstKind::ExpressionStatement(_) => {
// implicit return in arrow function expression
let Some(AstKind::FunctionBody(body)) = self.nodes().parent_kind(parent.id()) else {
return false;
};
return body.span.contains_inclusive(self.span()) && body.statements.len() == 1 && !self.get_snippet(body.span).starts_with('{')
}
_ => {
parent.kind().debug_name();
return false;
}
}

View file

@ -459,9 +459,15 @@ fn test_functions() {
};
});
",
"const foo = () => function bar() { }\nfoo()",
"module.exports.foo = () => function bar() { }"
];
let fail = vec!["function foo() {}", "function foo() { foo() }"];
let fail = vec![
"function foo() {}",
"function foo() { foo() }",
"const foo = () => { function bar() { } }\nfoo()",
];
let fix = vec![
// function declarations are never removed

View file

@ -16,3 +16,12 @@ source: crates/oxc_linter/src/tester.rs
· ╰── 'foo' is declared here
╰────
help: Consider removing this declaration.
⚠ eslint(no-unused-vars): Variable 'bar' is declared but never used.
╭─[no_unused_vars.tsx:1:30]
1 │ const foo = () => { function bar() { } }
· ─┬─
· ╰── 'bar' is declared here
2 │ foo()
╰────
help: Consider removing this declaration.