Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-use-hook-at-top-level-forward-ref.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@biomejs/biome": patch
---

Fixed [#9195](https://github.com/biomejs/biome/issues/9195): `useHookAtTopLevel` no longer reports false positives for component render functions passed to `forwardRef` or `React.forwardRef`.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::react::hooks::{is_react_hook_call, is_react_hook_name};
use crate::react::{ReactLibrary, is_react_call_api};
use crate::services::semantic::{SemanticModelBuilderVisitor, SemanticServices};
use biome_analyze::{
AddVisitor, FromServices, Phase, Phases, QueryMatch, Queryable, Rule, RuleDiagnostic, RuleKey,
Expand All @@ -9,12 +10,13 @@ use biome_analyze::{RuleDomain, RuleSource};
use biome_console::markup;
use biome_js_semantic::{CallsExtensions, SemanticModel};
use biome_js_syntax::{
AnyFunctionLike, AnyJsBinding, AnyJsClassMemberName, AnyJsExpression, AnyJsFunction,
AnyJsObjectMemberName, JsArrayAssignmentPatternElement, JsArrayBindingPatternElement,
JsCallExpression, JsConditionalExpression, JsGetterClassMember, JsGetterObjectMember,
JsIfStatement, JsLanguage, JsLogicalExpression, JsMethodClassMember, JsMethodObjectMember,
JsObjectBindingPatternShorthandProperty, JsReturnStatement, JsSetterClassMember,
JsSetterObjectMember, JsSyntaxKind, JsSyntaxNode, JsTryFinallyStatement, TextRange,
AnyFunctionLike, AnyJsBinding, AnyJsCallArgument, AnyJsClassMemberName, AnyJsExpression,
AnyJsFunction, AnyJsObjectMemberName, JsArrayAssignmentPatternElement,
JsArrayBindingPatternElement, JsCallExpression, JsConditionalExpression, JsGetterClassMember,
JsGetterObjectMember, JsIfStatement, JsLanguage, JsLogicalExpression, JsMethodClassMember,
JsMethodObjectMember, JsObjectBindingPatternShorthandProperty, JsReturnStatement,
JsSetterClassMember, JsSetterObjectMember, JsSyntaxKind, JsSyntaxNode, JsTryFinallyStatement,
TextRange,
};
use biome_rowan::{AstNode, Language, SyntaxNode, Text, WalkEvent, declare_node_union};
use rustc_hash::FxHashMap;
Expand Down Expand Up @@ -89,10 +91,13 @@ declare_node_union! {
}

impl AnyJsFunctionOrMethod {
fn is_react_component_or_hook(&self) -> bool {
fn is_react_component_or_hook(&self, model: &SemanticModel) -> bool {
if ReactComponentInfo::from_function(self.syntax()).is_some() {
return true;
}
if self.is_forward_ref_render_function(model) {
return true;
}
if let Some(name) = self.name() {
return is_react_hook_name(&name);
}
Expand Down Expand Up @@ -128,6 +133,61 @@ impl AnyJsFunctionOrMethod {
.map(AnyJsObjectMemberName::to_trimmed_text),
}
}

fn is_forward_ref_render_function(&self, model: &SemanticModel) -> bool {
let Self::AnyJsFunction(function) = self else {
return false;
};
let Ok(binding) = function.binding() else {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

function.binding() returns Option, not Result.

The pipeline failure confirms this: use let Some(binding) = ... instead of let Ok(binding) = ....

🔧 Proposed fix
-        let Ok(binding) = function.binding() else {
+        let Some(binding) = function.binding() else {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let Ok(binding) = function.binding() else {
let Some(binding) = function.binding() else {
🧰 Tools
🪛 GitHub Actions: autofix.ci

[error] 141-141: Rust compile error E0308: mismatched types. function.binding() has type Option<AnyJsBinding>, but code pattern expects Result via let Ok(binding) = ... else. Expected Option<AnyJsBinding>, found Result<_, _>.

🪛 GitHub Actions: Lint rule docs

[error] 141-141: Rust compile error E0308 (mismatched types): function.binding() has type Option<AnyJsBinding> but code uses let Ok(binding) = ... else expecting a Result. Expected Option<AnyJsBinding>, found Result<_, _>.

🪛 GitHub Actions: Pull request Node.js

[error] 141-141: Rust compiler error E0308: mismatched types in use_hook_at_top_level.rs. let Ok(binding) = function.binding() else { ... } expects Option<AnyJsBinding> but found Result<_, _>.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs` at
line 141, The code is using a Result pattern for function.binding() but that
method returns an Option; change the pattern from `let Ok(binding) =
function.binding()` to `let Some(binding) = function.binding()` and adjust the
corresponding else branch handling if needed in the function (the match around
the `function.binding()` call in use_hook_at_top_level.rs); ensure any
error/unreachable logic remains correct for the None case rather than treating
it like a Result::Err.

return false;
};
let Some(binding) = binding.as_js_identifier_binding() else {
return false;
};

model.as_binding(binding).all_references().any(|reference| {
let Some(expression) = reference
.syntax()
.ancestors()
.find_map(AnyJsExpression::cast)
.map(AnyJsExpression::omit_parentheses)
else {
return false;
};

if !matches!(expression, AnyJsExpression::JsIdentifierExpression(_)) {
return false;
}

let Some(argument) = expression.syntax().parent::<AnyJsCallArgument>() else {
return false;
};
let Some(argument_expression) = argument.as_any_js_expression() else {
return false;
};
if argument_expression.omit_parentheses().syntax() != expression.syntax() {
return false;
}

let Some(call_expression) = argument
.syntax()
.ancestors()
.find_map(JsCallExpression::cast)
else {
return false;
Comment on lines +162 to +177
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Several API misuses causing compilation failures.

The parent() method on SyntaxNode doesn't accept generic arguments. You need to call parent() and then cast separately.

Additionally, once you fix the parent call, argument will be AnyJsCallArgument, which doesn't have as_any_js_expression(). You likely want to extract the inner expression via pattern matching or a dedicated method.

🔧 Proposed fix
-            let Some(argument) = expression.syntax().parent::<AnyJsCallArgument>() else {
-                return false;
-            };
-            let Some(argument_expression) = argument.as_any_js_expression() else {
-                return false;
-            };
-            if argument_expression.omit_parentheses().syntax() != expression.syntax() {
-                return false;
-            }
-
-            let Some(call_expression) = argument
-                .syntax()
-                .ancestors()
-                .find_map(JsCallExpression::cast)
+            let Some(argument) = expression
+                .syntax()
+                .parent()
+                .and_then(AnyJsCallArgument::cast)
             else {
                 return false;
             };
+            let AnyJsCallArgument::AnyJsExpression(argument_expression) = &argument else {
+                return false;
+            };
+            if argument_expression.omit_parentheses().syntax() != expression.syntax() {
+                return false;
+            }
+
+            let Some(call_expression) = argument.syntax().ancestors().find_map(JsCallExpression::cast) else {
+                return false;
+            };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let Some(argument) = expression.syntax().parent::<AnyJsCallArgument>() else {
return false;
};
let Some(argument_expression) = argument.as_any_js_expression() else {
return false;
};
if argument_expression.omit_parentheses().syntax() != expression.syntax() {
return false;
}
let Some(call_expression) = argument
.syntax()
.ancestors()
.find_map(JsCallExpression::cast)
else {
return false;
let Some(argument) = expression
.syntax()
.parent()
.and_then(AnyJsCallArgument::cast)
else {
return false;
};
let AnyJsCallArgument::AnyJsExpression(argument_expression) = &argument else {
return false;
};
if argument_expression.omit_parentheses().syntax() != expression.syntax() {
return false;
}
let Some(call_expression) = argument.syntax().ancestors().find_map(JsCallExpression::cast) else {
return false;
};
🧰 Tools
🪛 GitHub Actions: autofix.ci

[error] 162-162: Rust compile error E0107: method takes 0 generic arguments but 1 was supplied. Call expression.syntax().parent::<AnyJsCallArgument>(); parent() is defined as pub fn parent(&self) -> Option<Self> (no generics).


[error] 165-165: Rust compile error E0599: no method named as_any_js_expression found for SyntaxNode<JsLanguage> at argument.as_any_js_expression().


[error] 168-168: Rust compile error E0282: type annotations needed. Cannot infer type at argument_expression.omit_parentheses().syntax() != expression.syntax().


[error] 173-173: Rust compile error E0599: no method named syntax found for SyntaxNode<JsLanguage> at .syntax() on argument.

🪛 GitHub Actions: Lint rule docs

[error] 162-162: Rust compile error E0107: expression.syntax().parent::<AnyJsCallArgument>() supplies 1 generic argument, but method parent takes 0 generic arguments.


[error] 165-165: Rust compile error E0599: no method named as_any_js_expression found for SyntaxNode<JsLanguage>.


[error] 168-168: Rust compile error E0282: type annotations needed at argument_expression.omit_parentheses().syntax() != expression.syntax() (cannot infer type).


[error] 172-173: Rust compile error E0599: no method named syntax found for SyntaxNode<JsLanguage> at .syntax() call in let Some(call_expression) = argument .syntax() ...

🪛 GitHub Actions: Pull request Node.js

[error] 162-162: Rust compiler error E0107: method takes 0 generic arguments but 1 was supplied. expression.syntax().parent::<AnyJsCallArgument>() should be called without generics; parent() is pub fn parent(&self) -> Option<Self>.


[error] 165-165: Rust compiler error E0599: no method named as_any_js_expression found for SyntaxNode<JsLanguage> in the current scope at .as_any_js_expression().


[error] 168-168: Rust compiler error E0282: type annotations needed. Cannot infer type for argument_expression usage at if argument_expression.omit_parentheses().syntax() != expression.syntax() { ... }.


[error] 172-173: Rust compiler error E0599: no method named syntax found for struct SyntaxNode<JsLanguage> at .syntax() on call_expression.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs` around
lines 162 - 177, The current code misuses SyntaxNode::parent generics and
AnyJsCallArgument APIs: replace the generic parent::<AnyJsCallArgument>() call
with a plain parent() followed by casting the returned SyntaxNode to
AnyJsCallArgument (e.g., via AnyJsCallArgument::cast or pattern match) to get an
argument value, and instead of calling as_any_js_expression() (which doesn't
exist on AnyJsCallArgument) extract the inner expression by pattern-matching the
AnyJsCallArgument variants or using the provided accessor (e.g., match on
AnyJsCallArgument::Expr or call a method like AnyJsCallArgument::expression())
so you obtain argument_expression whose omit_parentheses().syntax() can be
compared to expression.syntax(); keep the existing ancestor search using
JsCallExpression::cast unchanged.

};
let Ok(callee): Result<AnyJsExpression, _> = call_expression.callee() else {
return false;
};

is_react_call_api(
&callee.omit_parentheses(),
model,
ReactLibrary::React,
"forwardRef",
)
})
}
}

pub struct Suggestion {
Expand Down Expand Up @@ -254,8 +314,11 @@ fn is_conditional_expression(parent_node: &JsSyntaxNode, node: &JsSyntaxNode) ->
)
}

fn is_nested_function_inside_component_or_hook(function: &AnyJsFunctionOrMethod) -> bool {
if function.is_react_component_or_hook() {
fn is_nested_function_inside_component_or_hook(
function: &AnyJsFunctionOrMethod,
model: &SemanticModel,
) -> bool {
if function.is_react_component_or_hook(model) {
return false;
}

Expand All @@ -265,7 +328,7 @@ fn is_nested_function_inside_component_or_hook(function: &AnyJsFunctionOrMethod)

parent.ancestors().any(|node| {
AnyJsFunctionOrMethod::cast(node)
.is_some_and(|enclosing_function| enclosing_function.is_react_component_or_hook())
.is_some_and(|enclosing_function| enclosing_function.is_react_component_or_hook(model))
})
}

Expand Down Expand Up @@ -541,7 +604,7 @@ impl Rule for UseHookAtTopLevel {
path.push(range);

if let Some(enclosing_function) = enclosing_function_if_call_is_at_top_level(&call) {
if is_nested_function_inside_component_or_hook(&enclosing_function) {
if is_nested_function_inside_component_or_hook(&enclosing_function, model) {
// We cannot allow nested functions inside hooks and
// components, since it would break the requirement for
// hooks to be called from the top-level.
Expand All @@ -561,7 +624,7 @@ impl Rule for UseHookAtTopLevel {
}

let enclosed = is_enclosed_in_component_or_hook
|| enclosing_function.is_react_component_or_hook();
|| enclosing_function.is_react_component_or_hook(model);

if let AnyJsFunctionOrMethod::AnyJsFunction(function) = enclosing_function
&& let Some(calls_iter) = function.all_calls(model)
Expand Down Expand Up @@ -590,7 +653,7 @@ impl Rule for UseHookAtTopLevel {
}

if enclosing_function_if_call_is_at_top_level(call).is_some_and(|function| {
!function.is_react_component_or_hook() && !function.is_function_expression()
!function.is_react_component_or_hook(model) && !function.is_function_expression()
}) {
return Some(Suggestion {
hook_name_range: get_hook_name_range()?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ function Component7() {
useEffect();
};

function ForwardRefComponent(props, ref) {
const forwardedRef = useRef();
return <div ref={forwardedRef} />;
}

const WrappedForwardRefComponent = forwardRef(ForwardRefComponent);

function ReactForwardRefComponent(props, ref) {
const forwardedRef = useRef();
return <div ref={forwardedRef} />;
}

const WrappedReactForwardRefComponent = React.forwardRef(ReactForwardRefComponent);

test('a', () => {
function TestComponent() {
useState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,20 @@ function Component7() {
useEffect();
};

function ForwardRefComponent(props, ref) {
const forwardedRef = useRef();
return <div ref={forwardedRef} />;
}

const WrappedForwardRefComponent = forwardRef(ForwardRefComponent);

function ReactForwardRefComponent(props, ref) {
const forwardedRef = useRef();
return <div ref={forwardedRef} />;
}

const WrappedReactForwardRefComponent = React.forwardRef(ReactForwardRefComponent);

test('a', () => {
function TestComponent() {
useState();
Expand Down
Loading