From 8288829613cab2364b29d7ea89db53ef35d430c3 Mon Sep 17 00:00:00 2001 From: safishamsi Date: Tue, 30 Jun 2026 22:17:53 +0100 Subject: [PATCH] feat(extract): capture dispatch tables as indirect_call edges (#1566) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice 1 of #1566. A function referenced as a VALUE in a dict/list/set/ tuple literal — the registry/route-table idiom (`ROUTES = {"create": create_user}`, `HOOKS = [on_start, on_stop]`) — is an indirect dependency that blast-radius must see, but the call-argument capture (#1565) didn't cover it. Emit an indirect_call edge for each callable value: - module-level tables attribute to the file node; function-scoped tables attribute to the enclosing function. Same-file and cross-file (an imported handler in a table routes through the cross-file resolver). - dict KEYS are excluded (only values are references); non-callable values (a number, a string) never resolve; a name shadowed by a param/local or rebound at module scope is the local value, not the function. Refactors the resolve-and-emit logic shared by the argument and table paths into one guarded helper (_emit_python_indirect_ref) and threads the edge `context` ("argument" | "collection") through the cross-file pass. Adds _python_module_bound_names for the module-scope shadow set. 7 new tests (module dict/list, function-scoped, dict-keys-excluded, non-callable-value, module-reassign shadow, cross-file table). Full suite 2717 passed. Python only; assignment/return refs + other languages remain on #1566. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 1 + graphify/extract.py | 183 +++++++++++++++++++++++--------- tests/test_indirect_dispatch.py | 93 ++++++++++++++++ 3 files changed, 226 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1590b61..ba8a17f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu ## Unreleased +- Feat: extend `indirect_call` to dispatch tables (#1566). A function listed as a VALUE in a dict/list/set/tuple literal — a route/handler registry like `ROUTES = {"create": create_user, "delete": delete_user}` or `HOOKS = [on_start, on_stop]` — now emits an `indirect_call` edge so `affected` reaches those handlers too. Works at module level (attributed to the file) and inside a function (attributed to the function), same-file and cross-file. Same guards as the call-argument case: callable-target-only, not shadowed by a param/local/module-level reassignment, dict KEYS excluded (only values are references). Python only for now; assignment/return references and other languages tracked on #1566. - Feat: capture indirect dispatch as `indirect_call` edges so `graphify affected` (blast radius) catches callers that pass a function by name as a call argument — `executor.submit(fn)`, `Thread(target=fn)`, `map(fn, xs)`, callbacks (#1565, thanks @sheik-hiiobd). Kept as a distinct INFERRED relation separate from `calls` (strict call-graph queries stay precise) and added to the affected relation set. Hardened against false edges: the argument name must resolve to a callable definition and must NOT be shadowed by a parameter or local binding in the enclosing function — so the idiomatic `def via(pool, handler): pool.submit(handler)` (handler is the param) and a data variable sharing a function's name produce no edge. Now also resolves cross-file: a callback imported from another module (`from .handlers import on_event; pool.submit(on_event)`) routes through the same cross-file resolver as direct calls — single-definition god-node guard, callable-target-only, staying INFERRED — closing the gap where #1565 saw only same-file callbacks (the common real-world shape is cross-module). Python only for now. ## 0.9.3 (2026-06-30) diff --git a/graphify/extract.py b/graphify/extract.py index ead0661..732b8ce 100644 --- a/graphify/extract.py +++ b/graphify/extract.py @@ -1548,6 +1548,39 @@ def _python_local_bound_names(func_def_node, source: bytes) -> set[str]: return bound +def _python_module_bound_names(root, source: bytes) -> set[str]: + """Names rebound by assignment at MODULE scope (top-level `x = ...`, `for`, walrus). + + The module-scope analogue of the per-function shadow set: a dispatch-table value + whose name is reassigned to data at module level (`handler = build()`) names that + value, not a same-named function, so it must not manufacture an indirect edge. + Function and class bodies are not descended into — their bindings are local. + """ + bound: set[str] = set() + + def walk(n) -> None: + for child in n.children: + t = child.type + if t in ("function_definition", "class_definition", "lambda"): + continue # inner scope — not a module-level binding + if t == "assignment": + _python_collect_assignment_targets( + child.child_by_field_name("left"), source, bound + ) + elif t in ("for_statement", "for_in_clause"): + _python_collect_assignment_targets( + child.child_by_field_name("left"), source, bound + ) + elif t == "named_expression": # walrus := + _python_collect_assignment_targets( + child.child_by_field_name("name"), source, bound + ) + walk(child) + + walk(root) + return bound + + def _resolve_name(node, source: bytes, config: LanguageConfig) -> str | None: """Get the name from a node using config.name_field, falling back to child types.""" if config.resolve_function_name_fn is not None: @@ -4169,6 +4202,69 @@ def _extract_generic( # receiver_type so the cross-file pass resolves `var.method` by type (#ruby). ruby_var_types: dict[str, dict[str, str | None]] = {} + def _emit_python_indirect_ref(ident, scope_nid: str, enclosing_locals, context: str) -> None: + """A function referenced BY NAME — passed as a call argument, or listed as a + value in a dispatch table — is an indirect dependency of ``scope_nid``. Emit + it as a distinct INFERRED ``indirect_call`` (kept out of the precise ``calls`` + relation) only when the name resolves to a real callable and is NOT shadowed + by a parameter / local binding. A callback defined in another file is deferred + to the cross-file resolver via an ``indirect`` raw_call carrying its context. + Shared by the call-argument and dispatch-table (#1565, #1566) capture paths. + """ + if ident is None or ident.type != "identifier": + return + ident_name = _read_text(ident, source) + # shadowing: a param / local binding names a local value, not the module fn + if ident_name in enclosing_locals or ident_name in ("self", "cls"): + return + ref_nid = label_to_nid.get(ident_name) + if ref_nid is None: + # Defined in another file (`from .h import fn`): defer to the cross-file + # resolver, which applies the same single-definition god-node guard plus + # the callable-target check before emitting an INFERRED indirect_call. + raw_calls.append({ + "caller_nid": scope_nid, + "callee": ident_name, + "is_member_call": False, + "indirect": True, + "context": context, + "source_file": str_path, + "source_location": f"L{ident.start_point[0] + 1}", + }) + return + if ref_nid == scope_nid or ref_nid not in callable_def_nids: + return # self-ref, or a same-named non-callable data node — never an edge + if (scope_nid, ref_nid) in seen_call_pairs: + return # already a direct call to this target + if (scope_nid, ref_nid) in seen_indirect_pairs: + return + seen_indirect_pairs.add((scope_nid, ref_nid)) + edges.append({ + "source": scope_nid, + "target": ref_nid, + "relation": "indirect_call", + "context": context, + "confidence": "INFERRED", + "source_file": str_path, + "source_location": f"L{ident.start_point[0] + 1}", + "weight": 1.0, + }) + + def _python_dispatch_value_idents(coll_node): + """Yield the identifier value-nodes of a dict/list/set/tuple literal that are + function-reference candidates: dict VALUES (never keys), and the elements of a + list/set/tuple. Nested collections are reached by the caller's own recursion.""" + if coll_node.type == "dictionary": + for pair in coll_node.children: + if pair.type == "pair": + val = pair.child_by_field_name("value") + if val is not None and val.type == "identifier": + yield val + else: # list / set / tuple + for el in coll_node.children: + if el.type == "identifier": + yield el + def _php_class_const_scope(n) -> str | None: scope = n.child_by_field_name("scope") if scope is None: @@ -4442,57 +4538,11 @@ def _extract_generic( enclosing_locals = local_bound_names.get(caller_nid, frozenset()) for arg in args_node.children: if arg.type == "identifier": - ident = arg + _emit_python_indirect_ref(arg, caller_nid, enclosing_locals, "argument") elif arg.type == "keyword_argument": - ident = arg.child_by_field_name("value") - else: - continue - if ident is None or ident.type != "identifier": - continue - ident_name = _read_text(ident, source) - # 1. shadowing: a param / local binding is not the module fn - if ident_name in enclosing_locals: - continue - if ident_name in ("self", "cls"): - continue # never a module-level callable reference - ref_nid = label_to_nid.get(ident_name) - if ref_nid is None: - # Callback defined in ANOTHER file (e.g. `from .h import fn; - # pool.submit(fn)`). The in-file label map can't see it, so - # defer to the cross-file resolvers, which apply the same - # single-definition god-node guard plus a callable-target - # check before emitting an INFERRED `indirect_call`. The - # shadowing guard above has already run, so a parameter / - # local binding never reaches here. - raw_calls.append({ - "caller_nid": caller_nid, - "callee": ident_name, - "is_member_call": False, - "indirect": True, - "source_file": str_path, - "source_location": f"L{ident.start_point[0] + 1}", - }) - continue - if ref_nid == caller_nid: - continue - # 2. callable target only: never an arbitrary data/same-named node - if ref_nid not in callable_def_nids: - continue - if (caller_nid, ref_nid) in seen_call_pairs: - continue # already a direct call to this target - if (caller_nid, ref_nid) in seen_indirect_pairs: - continue - seen_indirect_pairs.add((caller_nid, ref_nid)) - edges.append({ - "source": caller_nid, - "target": ref_nid, - "relation": "indirect_call", - "context": "argument", - "confidence": "INFERRED", - "source_file": str_path, - "source_location": f"L{ident.start_point[0] + 1}", - "weight": 1.0, - }) + _emit_python_indirect_ref( + arg.child_by_field_name("value"), + caller_nid, enclosing_locals, "argument") # Helper function calls: config('foo.bar') → uses_config edge to "foo" if (callee_name and callee_name in config.helper_fn_names): @@ -4618,6 +4668,17 @@ def _extract_generic( "weight": 1.0, }) + # Dispatch tables (#1566): a function listed as a value in a dict/list/set/ + # tuple literal inside this body is an indirect dependency of the enclosing + # function. Reuses the shared resolve-and-emit guard (callable-target-only, + # not shadowed by a param/local, cross-file deferral). + if config.ts_module == "tree_sitter_python" and node.type in ( + "dictionary", "list", "set", "tuple" + ): + enclosing_locals = local_bound_names.get(caller_nid, frozenset()) + for ident in _python_dispatch_value_idents(node): + _emit_python_indirect_ref(ident, caller_nid, enclosing_locals, "collection") + for child in node.children: walk_calls(child, caller_nid) @@ -4664,6 +4725,26 @@ def _extract_generic( "weight": 1.0, }) + # ── Module-level dispatch tables (#1566) ────────────────────────────────── + # A function listed as a value in a TOP-LEVEL dict/list/set/tuple literal (a + # route / handler registry) is an indirect dependency of the file. Attributed + # to the file node. Function and class bodies are walked above, so this scan + # stops at their boundaries — it must not re-attribute a method's local table + # to the file, and class-attribute tables are a later refinement. + if config.ts_module == "tree_sitter_python": + module_bound = _python_module_bound_names(root, source) + + def _scan_module_dispatch(n) -> None: + if n.type in ("function_definition", "class_definition"): + return + if n.type in ("dictionary", "list", "set", "tuple"): + for ident in _python_dispatch_value_idents(n): + _emit_python_indirect_ref(ident, file_nid, module_bound, "collection") + for c in n.children: + _scan_module_dispatch(c) + + _scan_module_dispatch(root) + # ── Clean edges ─────────────────────────────────────────────────────────── valid_ids = seen_ids clean_edges = [] @@ -15116,7 +15197,7 @@ def extract( "source": caller, "target": tgt, "relation": "indirect_call", - "context": "argument", + "context": rc.get("context", "argument"), "confidence": "INFERRED", "confidence_score": 0.8, "source_file": rc.get("source_file", ""), diff --git a/tests/test_indirect_dispatch.py b/tests/test_indirect_dispatch.py index 5f495b1..144bf3c 100644 --- a/tests/test_indirect_dispatch.py +++ b/tests/test_indirect_dispatch.py @@ -254,3 +254,96 @@ def test_cross_file_param_shadow_emits_no_indirect_call(tmp_path): }) indirect = _rels(r, "indirect_call") assert (nid["schedule"], nid["on_event"]) not in indirect + + +# ── Dispatch tables (#1566 slice 1): functions referenced as collection values ─ +# A function listed as a VALUE in a dict/list/set/tuple literal (a route/handler +# registry) is an indirect dependency. Same INFERRED relation, same guards: +# callable-target-only, not shadowed, dict keys excluded. + +def test_module_level_dict_registry_emits_indirect_call(tmp_path): + r, nid = _extract(tmp_path, ( + "def create(x):\n return x\n\n\n" + "def delete(x):\n return x\n\n\n" + 'ROUTES = {"create": create, "delete": delete}\n' + )) + indirect = _rels(r, "indirect_call") + file_nid = next(n["id"] for n in r["nodes"] if n["label"] == "m.py") + # the module references both handlers through the table + assert (file_nid, nid["create"]) in indirect + assert (file_nid, nid["delete"]) in indirect + # not leaked into precise `calls` + assert (file_nid, nid["create"]) not in _rels(r, "calls") + + +def test_module_level_list_registry_emits_indirect_call(tmp_path): + r, nid = _extract(tmp_path, ( + "def on_start():\n pass\n\n\n" + "def on_stop():\n pass\n\n\n" + "HOOKS = [on_start, on_stop]\n" + )) + indirect = _rels(r, "indirect_call") + file_nid = next(n["id"] for n in r["nodes"] if n["label"] == "m.py") + assert (file_nid, nid["on_start"]) in indirect + assert (file_nid, nid["on_stop"]) in indirect + + +def test_function_scoped_dispatch_table_attributes_to_function(tmp_path): + r, nid = _extract(tmp_path, ( + "def cb(x):\n return x\n\n\n" + "def build():\n return {\"k\": cb}\n" + )) + assert (nid["build"], nid["cb"]) in _rels(r, "indirect_call") + + +def test_dict_keys_are_not_dispatch_targets(tmp_path): + """Only VALUES are references; a function used as a dict KEY is not invoked + through the table and must not produce an edge.""" + r, nid = _extract(tmp_path, ( + "def keyfn():\n pass\n\n\n" + "def valfn():\n pass\n\n\n" + "T = {keyfn: valfn}\n" + )) + indirect = _rels(r, "indirect_call") + assert all(t != nid["keyfn"] for _s, t in indirect) + file_nid = next(n["id"] for n in r["nodes"] if n["label"] == "m.py") + assert (file_nid, nid["valfn"]) in indirect # the value still resolves + + +def test_non_callable_collection_value_emits_no_indirect_call(tmp_path): + """A data value in the table (a number, a string) is not a callable and must + never become a dispatch target.""" + r, nid = _extract(tmp_path, ( + "def use():\n pass\n\n\n" + 'CONF = {"timeout": 30, "name": use}\n' + )) + indirect = _rels(r, "indirect_call") + file_nid = next(n["id"] for n in r["nodes"] if n["label"] == "m.py") + # only the genuine callable resolves; the int value contributes nothing + assert (file_nid, nid["use"]) in indirect + assert len(indirect) == 1 + + +def test_module_level_reassigned_name_shadows_dispatch_value(tmp_path): + """If the name is rebound to data at module scope, the table value is that + data, not the same-named function — no edge.""" + r, nid = _extract(tmp_path, ( + "def handler():\n pass\n\n\n" + "handler = object()\n" + 'T = {"h": handler}\n' + )) + indirect = _rels(r, "indirect_call") + assert all(t != nid["handler"] for _s, t in indirect) + + +def test_cross_file_dict_registry_emits_indirect_call(tmp_path): + r, nid = _extract_dir(tmp_path, { + "handlers.py": "def on_event(x):\n return x\n", + "registry.py": ( + "from handlers import on_event\n\n\n" + 'ROUTES = {"event": on_event}\n' + ), + }) + indirect = _rels(r, "indirect_call") + reg_file = next(n["id"] for n in r["nodes"] if n["label"] == "registry.py") + assert (reg_file, nid["on_event"]) in indirect