Skip to content
Closed
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
16 changes: 11 additions & 5 deletions codeflash/languages/javascript/treesitter_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@

from tree_sitter import Node, Tree

_FUNC_LIKE_TYPES: frozenset[str] = frozenset(
("function_declaration", "function_expression", "arrow_function", "method_definition")
)

_FUNCTION_BODY_TYPES = frozenset(
{
"function_declaration",
Expand Down Expand Up @@ -1242,30 +1246,32 @@ def has_return_statement(self, function_node: FunctionNode, source: str) -> bool

def _node_has_return(self, node: Node) -> bool:
"""Recursively check if a node contains a return statement."""
# Use an explicit stack to avoid recursion overhead while preserving traversal order.
func_types = ("function_declaration", "function_expression", "arrow_function", "method_definition")
stack = [node]
# Localize extend for minor speedup and avoid repeated attribute lookups on the list object
stack_extend = stack.extend
while stack:
current = stack.pop()
# Direct return statement check
if current.type == "return_statement":
return True

# If this node is a function-like node, only traverse its body children
if current.type in func_types:
if current.type in _FUNC_LIKE_TYPES:
body_node = current.child_by_field_name("body")
if body_node:
# Push children in reverse so they are processed in original order
children = body_node.children
if children:
stack.extend(reversed(children))
# reversed() returns an iterator; extend consumes it without creating an intermediate list
stack_extend(reversed(children))
# Do not traverse other parts of the function node
# Do not traverse other parts of the function node
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: This comment is duplicated on the line above. Remove the duplicate.

Suggested change
# Do not traverse other parts of the function node

continue

# General case: traverse all children
children = current.children
if children:
stack.extend(reversed(children))
stack_extend(reversed(children))

return False

Expand Down
Loading