Skip to content

Commit

Permalink
fix(linter/unicorn): consistent-function-scoping false positive on as…
Browse files Browse the repository at this point in the history
…signment expression (#5312)

fixes #5159 and any other named function assigned to a property like:
```js
const foo = {};
foo.bar = function fooBar() {}
```

---------

Co-authored-by: Don Isaac <[email protected]>
Co-authored-by: Cameron Clark <[email protected]>
  • Loading branch information
3 people authored Aug 31, 2024
1 parent f81e8a1 commit 11b93af
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
16 changes: 14 additions & 2 deletions crates/oxc_linter/src/rules/unicorn/consistent_function_scoping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ impl Rule for ConsistentFunctionScoping {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let (function_declaration_symbol_id, function_body, reporter_span) = match node.kind() {
AstKind::Function(function) => {
if let Some(AstKind::AssignmentExpression(_)) = ctx.nodes().parent_kind(node.id()) {
return;
}

if function.is_typescript_syntax() {
return;
}
Expand All @@ -172,8 +176,12 @@ impl Rule for ConsistentFunctionScoping {
(
binding_ident.symbol_id.get().unwrap(),
function_body,
// 8 for "function"
Span::sized(function.span.start, 8),
function
.id
.as_ref()
.map_or(Span::sized(function.span.start, 8), |func_binding_ident| {
func_binding_ident.span
}),
)
} else if let Some(function_id) = &function.id {
(function_id.symbol_id.get().unwrap(), function_body, function_id.span())
Expand Down Expand Up @@ -573,6 +581,9 @@ fn test() {
("t.throws(() => receiveString(function a() {}), {})", None),
("function test () { t.throws(() => receiveString(function a() {}), {}) }", None),
("function foo() { let x = new Bar(function b() {}) }", None),
("module.exports = function foo() {};", None),
("module.exports.foo = function foo() {};", None),
("foo.bar.func = function foo() {};", None),
];

let fail = vec![
Expand Down Expand Up @@ -804,6 +815,7 @@ fn test() {
// ("const doFoo = () => bar => bar;", None),
("function foo() { const bar = async () => {} }", None),
("function doFoo() { const doBar = function(bar) { return bar; }; }", None),
("function outer() { const inner = function inner() {}; }", None),
];

Tester::new(ConsistentFunctionScoping::NAME, pass, fail).test_and_snapshot();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,10 @@ source: crates/oxc_linter/src/tester.rs
· ────────
╰────
help: Move this function to the outer scope.

⚠ eslint-plugin-unicorn(consistent-function-scoping): Function does not capture any variables from the outer scope.
╭─[consistent_function_scoping.tsx:1:43]
1 │ function outer() { const inner = function inner() {}; }
· ─────
╰────
help: Move this function to the outer scope.

0 comments on commit 11b93af

Please sign in to comment.