From 34292647994001a3bc3c30331ea37cdf0e208502 Mon Sep 17 00:00:00 2001 From: safishamsi Date: Fri, 14 Aug 2026 15:02:15 +0100 Subject: [PATCH] feat(js): extend nested-function extraction to arrow components/callbacks (#2653) #2705 fixed `function` nested in a `function`, but the React idiom that motivated the issue -- a function declared inside an arrow-defined component (`const Panel = () => { function handleClick(){} }`) or an arrow callback (`useEffect(() => { function h(){} })`) -- was still missed: the main walk never recurses into arrow bodies and the scan bailed at the arrow boundary. Refactors the inline scan into a module-level _scan_js_nested_function_ declarations that also descends through arrow / function-expression bodies (attributing nested declarations to the nearest enclosing named scope), and invokes it from the const-arrow branch of _js_extra_walk. Nested bodies join function_bodies, so the central _tracked_body_ids guard prevents double-walk. Adds tests for both arrow idioms. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 1 + graphify/extractors/engine.py | 131 ++++++++++++++++++++++++---------- tests/test_extract.py | 61 ++++++++++++++++ 3 files changed, 156 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a8d6bb9..7ddce4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu - Fix: a wiki article link now targets the article's filename verbatim instead of a percent-encoded twin, so a label with `( ) & #` or non-ASCII characters no longer produces a link that names no file on disk; the link and the on-disk filename share one canonicalization (#2597, thanks @abhay-codes07). - Fix: export filenames are now budgeted against the full destination path rather than only the per-component `NAME_MAX`, so a long output directory on Windows no longer pushes an Obsidian/wiki note path past `MAX_PATH` and aborts the export mid-write (#2655, thanks @abhay-codes07). The collision-suffix reserve was widened so a four-digit dedup suffix can't overrun the budget. - Fix: the Bash extractor resolves two more `source` path forms — `source "$(dirname "$VAR")/lib/x.sh"` and a `..` suffix on a tracked-variable base (`source "$VAR/../lib/x.sh"`) — so those cross-file source edges are no longer silently dropped (#2596, thanks @hudsonwa). A `..` on a *guessed* base is still rejected, and a tracked-base `..` cannot walk past the base's parent to an arbitrary host path, so a hostile corpus can't make the extractor stat or record an out-of-tree file. +- Fix: a named `function` declaration nested inside another function now gets its own node, a `contains` edge from the enclosing function, and its own call scope, so calls made from inside it are no longer dropped as dangling (#2653, thanks @himanshupatro-334). Coverage was extended to the arrow idioms too: a function declared inside an arrow-defined component (`const Panel = () => { function handleClick(){} }`) or inside an arrow callback (`useEffect(() => { function h(){} })`) is captured and attributed to the nearest enclosing named scope. - Feature: OCaml `.ml`/`.mli` extraction via tree-sitter-ocaml (optional `[ocaml]` extra). Extracts modules, top-level and module-level values/functions, types and their variant constructors, `open` imports, and function calls; qualified calls (`Geo.area`) resolve to the value, and cross-file `open`/call targets collapse onto the unique real definition via the corpus stub rewire. - Fix: a JS/TS `for...of` / `for...in` loop binding is now shadowed, so passing it as a call argument no longer fabricates an `indirect_call` edge to an unrelated same-named callable (#2685, thanks @ousamabenyounes); completes the loop/closure/catch shadow family (#2568/#2569/#2517). - Fix: graph provenance (`built_at_commit`) is stamped from the analysed repository rather than the shell's working directory, so `graphify extract` run from elsewhere records the target's commit, not the caller's (#2534 family; #2699, thanks @C0KERNEL). diff --git a/graphify/extractors/engine.py b/graphify/extractors/engine.py index d09eb27..b91463c 100644 --- a/graphify/extractors/engine.py +++ b/graphify/extractors/engine.py @@ -1875,6 +1875,78 @@ def _require_imports_js(node, source: bytes, file_nid: str, stem: str, edges: li _JS_FUNCTION_VALUE_TYPES = frozenset({"arrow_function", "function_expression", "function", "generator_function"}) + +def _scan_js_nested_function_declarations( + container_node, parent_nid: str, *, source: bytes, config, + add_node, add_edge, callable_def_nids: set | None, + local_bound_names: dict | None, function_bodies: list, +) -> None: + """Emit a node + `contains` edge for every named `function`/generator + declaration lexically nested inside *container_node*, scoped under + *parent_nid*, and track its body so calls made from inside it resolve + instead of dangling (#2653). + + Recurses through non-function children AND through the bodies of nested + arrow / function expressions, so a `function` declared inside an arrow + callback (`useEffect(() => { function h(){} })`) or inside an arrow-defined + component (`const Panel = () => { function handleClick(){} }`, the React + idiom that motivated #2653) is captured too. Anonymous closures themselves + are not noded — they are attributed to the nearest enclosing named scope, + which is *parent_nid*. + """ + if container_node is None: + return + for child in container_node.children: + if child.type in ("function_declaration", "generator_function_declaration"): + name_node = child.child_by_field_name(config.name_field) + if name_node is None: + for c in child.children: + if c.type in config.name_fallback_child_types: + name_node = c + break + func_name = _read_text(name_node, source) if name_node else None + # A name that normalizes to nothing (e.g. minified `$`) would collapse + # the nested id onto parent_nid and leak the scan path (#1899); skip it. + if func_name and normalize_id(func_name): + line = child.start_point[0] + 1 + nested_nid = _make_id(parent_nid, func_name) + add_node(nested_nid, f"{func_name}()", line) + add_edge(parent_nid, nested_nid, "contains", line) + if callable_def_nids is not None: + callable_def_nids.add(nested_nid) + if local_bound_names is not None: + local_bound_names[nested_nid] = _js_local_bound_names(child, source) + nested_body = _find_body(child, config) + if nested_body: + function_bodies.append((nested_nid, nested_body)) + _scan_js_nested_function_declarations( + nested_body, nested_nid, source=source, config=config, + add_node=add_node, add_edge=add_edge, + callable_def_nids=callable_def_nids, + local_bound_names=local_bound_names, + function_bodies=function_bodies, + ) + elif child.type in _JS_FUNCTION_VALUE_TYPES: + # An anonymous arrow/function expression is not itself a node, but a + # `function` declared inside its body still belongs to the enclosing + # named scope — descend into the body keeping the SAME parent_nid. + _scan_js_nested_function_declarations( + _find_body(child, config), parent_nid, source=source, config=config, + add_node=add_node, add_edge=add_edge, + callable_def_nids=callable_def_nids, + local_bound_names=local_bound_names, + function_bodies=function_bodies, + ) + else: + _scan_js_nested_function_declarations( + child, parent_nid, source=source, config=config, + add_node=add_node, add_edge=add_edge, + callable_def_nids=callable_def_nids, + local_bound_names=local_bound_names, + function_bodies=function_bodies, + ) + + def _js_topmost_closures(node, out: list) -> None: """Collect the TOPMOST closure nodes (arrow / function expressions) under ``node``, without descending into a found closure — its nested closures @@ -1935,7 +2007,8 @@ def _js_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str, parent_class_nid: str | None, add_node_fn, add_edge_fn, callable_def_nids: set | None = None, local_bound_names: dict | None = None, - closure_locals_by_body: dict | None = None) -> bool: + closure_locals_by_body: dict | None = None, + config=None) -> bool: """Handle lexical_declaration (arrow functions, CJS requires, module-level const literals) for JS/TS. Returns True if handled.""" # CommonJS / prototype member assignments whose value is a function: # exports.X = () => {} → file-contained function X() @@ -2053,6 +2126,18 @@ def _js_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str, body = value.child_by_field_name("body") if body: function_bodies.append((func_nid, body)) + # #2653: a `function` declared inside an arrow-defined + # component (`const Panel = () => { function h(){} }`) + # is otherwise never seen — the main walk does not + # recurse into arrow bodies. Scan it here so the + # nested declaration is noded and its calls resolve. + _scan_js_nested_function_declarations( + body, func_nid, source=source, config=config, + add_node=add_node_fn, add_edge=add_edge_fn, + callable_def_nids=callable_def_nids, + local_bound_names=local_bound_names, + function_bodies=function_bodies, + ) arrow_found = True elif value and ( is_exported_scalar_binding @@ -4114,41 +4199,13 @@ def _extract_generic( if config.ts_module in ( "tree_sitter_javascript", "tree_sitter_typescript" ): - def _scan_js_nested_functions(parent_nid: str, container_node) -> None: - if container_node is None: - return - for child in container_node.children: - if child.type in ( - "function_declaration", - "generator_function_declaration", - ): - name_node = child.child_by_field_name(config.name_field) - if name_node is None: - for c in child.children: - if c.type in config.name_fallback_child_types: - name_node = c - break - func_name = _read_text(name_node, source) if name_node else None - if func_name and normalize_id(func_name): - line = child.start_point[0] + 1 - nested_nid = _make_id(parent_nid, func_name) - add_node(nested_nid, f"{func_name}()", line) - add_edge(parent_nid, nested_nid, "contains", line) - callable_def_nids.add(nested_nid) - if local_bound_names is not None: - local_bound_names[nested_nid] = _js_local_bound_names( - child, source - ) - nested_body = _find_body(child, config) - if nested_body: - function_bodies.append((nested_nid, nested_body)) - _scan_js_nested_functions(nested_nid, nested_body) - elif child.type in _JS_FUNCTION_VALUE_TYPES: - continue - else: - _scan_js_nested_functions(parent_nid, child) - - _scan_js_nested_functions(func_nid, body) + _scan_js_nested_function_declarations( + body, func_nid, source=source, config=config, + add_node=add_node, add_edge=add_edge, + callable_def_nids=callable_def_nids, + local_bound_names=local_bound_names, + function_bodies=function_bodies, + ) if config.ts_module == "tree_sitter_kotlin": # #2347: Kotlin anonymous objects (`object : Foo { … }`, # node type `object_literal`). The function branch never @@ -4241,7 +4298,7 @@ def _extract_generic( nodes, edges, seen_ids, function_bodies, parent_class_nid, add_node, add_edge, callable_def_nids, local_bound_names, - closure_locals_by_body): + closure_locals_by_body, config=config): return # TS namespace / module containers (internal_module, module) diff --git a/tests/test_extract.py b/tests/test_extract.py index 04c8d84..2dbda9f 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -950,6 +950,67 @@ def test_extract_js_deeply_nested_function_declarations(tmp_path): assert (outer_id, dothing_id, "calls") not in edges +def test_extract_js_function_nested_in_arrow_component(tmp_path): + """#2653 (the motivating React idiom): a named function declared inside an + ARROW-defined component `const Panel = () => { function handleRegen(){…} }` + is noded, contained by the component, and its calls resolve — the main walk + never recurses into arrow bodies, so this must be scanned explicitly.""" + from graphify.extract import extract + f = tmp_path / "Panel.jsx" + f.write_text( + "function doThing() {}\n" + "const Panel = () => {\n" + " function handleRegen() {\n" + " doThing()\n" + " }\n" + " return handleRegen\n" + "}\n" + ) + result = extract([f], root=tmp_path) + by_label = {n["label"]: n for n in result["nodes"]} + + assert "handleRegen()" in by_label + edges = [(e["source"], e["target"], e["relation"]) for e in result["edges"]] + panel_id = by_label["Panel()"]["id"] + handle_id = by_label["handleRegen()"]["id"] + dothing_id = by_label["doThing()"]["id"] + + assert (panel_id, handle_id, "contains") in edges + assert (handle_id, dothing_id, "calls") in edges + assert (panel_id, dothing_id, "calls") not in edges + + +def test_extract_js_function_nested_in_arrow_callback(tmp_path): + """#2653: a named function declared inside an arrow CALLBACK nested in a + function (`function Panel(){ useEffect(() => { function h(){…} }) }`) is + attributed to the nearest enclosing named scope (the anonymous arrow is not + a node), and its calls resolve instead of dangling.""" + from graphify.extract import extract + f = tmp_path / "Effect.jsx" + f.write_text( + "function doThing() {}\n" + "function Panel() {\n" + " useEffect(() => {\n" + " function h() {\n" + " doThing()\n" + " }\n" + " })\n" + "}\n" + ) + result = extract([f], root=tmp_path) + by_label = {n["label"]: n for n in result["nodes"]} + + assert "h()" in by_label + edges = [(e["source"], e["target"], e["relation"]) for e in result["edges"]] + panel_id = by_label["Panel()"]["id"] + h_id = by_label["h()"]["id"] + dothing_id = by_label["doThing()"]["id"] + + # the anonymous arrow is not noded, so h is contained directly by Panel + assert (panel_id, h_id, "contains") in edges + assert (h_id, dothing_id, "calls") in edges + + def test_extract_js_nested_function_local_variable_preservation(tmp_path): """#2653 / #1077: extracting nested named functions must preserve local variable suppression.""" from graphify.extract import extract_js