fix(extract): resolve module.func values in Python dispatch tables (#1566)

A dict/list/set/tuple literal of bare function names already yields
`indirect_call` edges, but the same table written with the module
prefix, the usual shape of a plugin registry:

    from payments import card, cash
    PROVIDERS = {"card": card.card_charge, "cash": cash.cash_charge}

got no edge at all, because only bare identifiers counted as values.

Such a value now becomes an `indirect` member raw call, and the Python
member-call resolver binds it through its module arm only: the receiver
must be a module imported into the caller's own file, holding exactly
one callable of that name. It is emitted as the INFERRED
`indirect_call` (0.85, context `collection`) the bare-name path uses,
never to a class used as a value, and never when a parameter or local
shadows the module name. A module-level table resolves from the file
node. The AST cache schema goes to 26 so cached Python extractions
re-run.

(cherry picked from commit 28934b6316)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-10-30 23:27:41 +00:00
1 parent fdd25f7b31
commit 948938a647
3 files changed
+257 -3

No files matched your search

+43 -3
View File
@@ -5021,6 +5021,13 @@ def _resolve_python_member_calls(
return _key(stem or n.get("label", ""))
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
# A dispatch-table value is only pre-empted by an edge that already says the
# caller reaches the target. An `imports` edge from the file to the same symbol
# is expected and must not hide it (the generic resolver's call_like_pairs).
call_like_pairs = {
(e.get("source"), e.get("target")) for e in all_edges
if e.get("relation") in ("calls", "indirect_call")
}
# A method hangs off its class (`method` edge), not its file (`contains`), so
# the typed-receiver arm finds a method caller's file through its class.
method_class: dict[str, str] = {}
@@ -5091,6 +5098,28 @@ def _resolve_python_member_calls(
# Swift node labelled `Swift.Array`. Stubs and external modules
# carry no file.
return
if rc.get("indirect"):
# `module.func` listed in a dispatch table: referenced as a value, not
# invoked, so the same INFERRED `indirect_call` the bare-name path emits,
# and only to a real callable, never a class used as a value (#2137).
if (caller, target_nid) in call_like_pairs:
return
if not node_by_id.get(target_nid, {}).get("_callable") or node_by_id.get(target_nid, {}).get("_callable_class"):
return
call_like_pairs.add((caller, target_nid))
existing_pairs.add((caller, target_nid))
all_edges.append({
"source": caller,
"target": target_nid,
"relation": "indirect_call",
"context": rc.get("context", "collection"),
"confidence": "INFERRED",
"confidence_score": 0.85,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
return
if rc.get("_python_attr_read"):
# An attribute read only runs a property getter, and only the one it
# spells: _key() folds `_items` into `items`, so compare the name.
@@ -5106,6 +5135,8 @@ def _resolve_python_member_calls(
if (caller, target_nid) in existing_pairs:
return
existing_pairs.add((caller, target_nid))
if not rc.get("_python_attr_read"):
call_like_pairs.add((caller, target_nid))
# EXTRACTED: a qualified call (`ClassName.method()` or `module.func()`) is
# an explicit, unambiguous static reference resolved to exactly one
# definition (each arm applies a single-definition god-node guard).
@@ -5179,7 +5210,10 @@ def _resolve_python_member_calls(
return None
factory_receivers: list[dict] = []
for rc in all_raw_calls:
# Dispatch-table values (`indirect`) go last, so a direct call to the same target
# claims the pair as `calls` whichever comes first in the body. Both halves keep
# their source order.
for rc in [r for r in all_raw_calls if not r.get("indirect")] + [r for r in all_raw_calls if r.get("indirect")]:
if rc.get("_ambiguous_python_import"):
continue
if not rc.get("is_member_call"):
@@ -5192,14 +5226,18 @@ def _resolve_python_member_calls(
receiver = rc.get("receiver")
callee = rc.get("callee")
caller = rc.get("caller_nid")
if receiver in ("self", "cls", "super") and callee and caller and not rc.get("_python_super_args"):
# A dispatch-table `module.func` value takes the module arm only: its
# receiver is a bare name the extractor already checked is not a local.
if rc.get("indirect") and not (receiver and callee and caller and not receiver[:1].isupper()):
continue
if not rc.get("indirect") and receiver in ("self", "cls", "super") and callee and caller and not rc.get("_python_super_args"):
target = _inherited_method(caller, callee, skip_own=receiver == "super")
if target:
# Same rule as the in-file base walk (_self_call_target), across files.
_emit_call(caller, target, rc)
continue
attr_type = rc.get("_python_self_attr_type")
if attr_type and callee and caller:
if attr_type and callee and caller and not rc.get("indirect"):
# `self.X.m()` with X bound to one class (#2860): only a unique class
# the caller's own file defines or imports, and only if it owns `m`.
class_nids = class_def_nids.get(_key(attr_type), [])
@@ -5281,6 +5319,8 @@ def _resolve_python_member_calls(
# (#2082), so an aliased import resolves the same as the bare name.
rkey = _key(receiver)
caller_file = _file_node(caller)
if caller_file is None and rc.get("indirect") and caller in imported_by_filenode and caller not in file_of_node:
caller_file = str(caller) # a module-level dispatch table: the caller IS the file
file_aliases = import_alias_by_filenode.get(caller_file, {})
mods = [t for t in imported_by_filenode.get(caller_file, ())
if t in contains_children
+40
View File
@@ -9070,6 +9070,42 @@ def _extract_generic(
if el.type == "identifier":
yield el
def _python_dispatch_value_attrs(coll_node):
"""Yield the ``module.func`` value-nodes of a dict/list/set/tuple literal: the
same value positions as ``_python_dispatch_value_idents``, written with a module
prefix (``{"card": card.card_charge}``). Only a bare-name receiver qualifies; a
longer chain (``a.b.c``) or a call result has no single receiver to resolve."""
if coll_node.type == "dictionary":
values = (p.child_by_field_name("value") for p in coll_node.children if p.type == "pair")
else: # list / set / tuple
values = iter(coll_node.children)
for val in values:
if val is None or val.type != "attribute":
continue
obj = val.child_by_field_name("object")
if obj is not None and obj.type == "identifier" and val.child_by_field_name("attribute") is not None:
yield val
def _emit_indirect_member_ref(attr_node, scope_nid: str, enclosing_locals, context: str) -> None:
"""``module.func`` listed in a dispatch table: defer it to the Python member-call
resolver as an ``indirect`` member raw_call. That resolver binds it only when the
receiver is a module imported into this file holding exactly one callable of that
name, and emits an INFERRED ``indirect_call`` like the bare-name path. A receiver
bound as a param/local (or ``self``/``cls``) names a value, not a module."""
receiver = _read_text(attr_node.child_by_field_name("object"), source)
if receiver in enclosing_locals or receiver in ("self", "cls"):
return
raw_calls.append({
"caller_nid": scope_nid,
"callee": _read_text(attr_node.child_by_field_name("attribute"), source),
"is_member_call": True,
"receiver": receiver,
"indirect": True,
"context": context,
"source_file": str_path,
"source_location": f"L{attr_node.start_point[0] + 1}",
})
def _python_ref_value_idents(value_node):
"""Identifiers on the VALUE side of an assignment RHS or a return: a bare name
(`cb = handler`, `return handler`) or the elements of a bare unpack
@@ -10325,6 +10361,8 @@ def _extract_generic(
enclosing_locals = local_bound_names.get(caller_nid, frozenset()) | extra_locals
for ident in _python_dispatch_value_idents(node):
_emit_indirect_ref(ident, caller_nid, enclosing_locals, "collection")
for attr in _python_dispatch_value_attrs(node):
_emit_indirect_member_ref(attr, caller_nid, enclosing_locals, "collection")
elif config.ts_module in ("tree_sitter_javascript", "tree_sitter_typescript") \
and node.type in ("object", "array"):
enclosing_locals = local_bound_names.get(caller_nid, frozenset()) | extra_locals
@@ -10524,6 +10562,8 @@ def _extract_generic(
if n.type in ("dictionary", "list", "set", "tuple"):
for ident in _python_dispatch_value_idents(n):
_emit_indirect_ref(ident, file_nid, module_bound, "collection")
for attr in _python_dispatch_value_attrs(n):
_emit_indirect_member_ref(attr, file_nid, module_bound, "collection")
elif n.type == "assignment":
# Module-level alias / re-export: CALLBACK = handler
for ident in _python_ref_value_idents(n.child_by_field_name("right")):
+174
View File
@@ -0,0 +1,174 @@
"""Dispatch tables whose values are written `module.func` (#1566).
A dict/list/set/tuple of bare function names already yields `indirect_call`
edges. The same table written with the module prefix, the common shape of a
plugin registry (`{"card": card.card_charge, "cash": cash.cash_charge}`), got
no edge at all, because only bare identifiers counted as values.
Such a value is now resolved the way a direct `card.card_charge()` call is:
only when `card` is a module imported into the caller's own file and that
module holds exactly one callable of that name. Anything else (a class used
as a value, a parameter that shadows the module, a module the file never
imports) still yields no edge.
"""
from __future__ import annotations
from pathlib import Path
from graphify.extract import extract
PAYMENTS = {
"payments/__init__.py": "",
"payments/card.py": "def card_charge(amount):\n return amount\n\n\nclass CardGateway:\n pass\n",
"payments/cash.py": "def cash_charge(amount):\n return amount\n",
}
def _extract(tmp_path, files: dict[str, str]):
base = tmp_path / "shop"
for name, body in files.items():
path = base / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
return extract([base / name for name in files], root=base,
cache_root=base / "graphify-out", parallel=False)
def _id(r, label: str, source_suffix: str = "") -> str:
matches = [
n["id"] for n in r["nodes"]
if n["label"].rstrip("()") == label and str(n.get("source_file", "")).replace("\\", "/").endswith(source_suffix)
]
assert len(matches) == 1, (label, source_suffix, matches)
return matches[0]
def _edges(r, relation: str) -> list[dict]:
return [e for e in r["edges"] if e["relation"] == relation]
def _pairs(r, relation: str) -> set[tuple[str, str]]:
return {(e["source"], e["target"]) for e in _edges(r, relation)}
def test_function_table_of_module_attributes_links_each_function(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n"
"import payments.cash as cash\n\n\n"
"def pay(provider, amount):\n"
' table = {"card": card.card_charge, "cash": cash.cash_charge}\n'
" return table[provider](amount)\n"
)})
pay = _id(r, "pay")
card_charge, cash_charge = _id(r, "card_charge"), _id(r, "cash_charge")
assert {(pay, card_charge), (pay, cash_charge)} <= _pairs(r, "indirect_call")
assert not {(pay, card_charge), (pay, cash_charge)} & _pairs(r, "calls")
for e in _edges(r, "indirect_call"):
if e["source"] == pay:
assert (e["confidence"], e["confidence_score"], e["context"]) == ("INFERRED", 0.85, "collection")
def test_module_level_registry_links_from_the_file(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "registry.py": (
"from payments import card, cash\n\n"
"PROVIDERS = [card.card_charge, cash.cash_charge]\n"
)})
registry = next(n["id"] for n in r["nodes"] if n["label"] == "registry.py")
assert {(registry, _id(r, "card_charge")), (registry, _id(r, "cash_charge"))} <= _pairs(r, "indirect_call")
def test_class_used_as_a_value_is_not_an_indirect_call(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n\n\n"
"def gateways():\n"
" return {\"card\": card.CardGateway}\n"
)})
assert (_id(r, "gateways"), _id(r, "CardGateway")) not in _pairs(r, "indirect_call")
def test_parameter_shadowing_the_module_emits_nothing(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n\n\n"
"def charge_with(card):\n"
" return {\"x\": card.card_charge}\n"
)})
assert not [e for e in _edges(r, "indirect_call") if e["source"] == _id(r, "charge_with")]
def test_module_the_file_never_imports_emits_nothing(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"def pay():\n"
" return {\"card\": card.card_charge}\n"
)})
assert not [e for e in _edges(r, "indirect_call") if e["source"] == _id(r, "pay")]
def test_same_function_name_in_two_modules_links_the_imported_one(tmp_path):
r = _extract(tmp_path, {**PAYMENTS,
"legacy/__init__.py": "",
"legacy/card.py": "def card_charge(amount):\n return -amount\n",
"checkout.py": (
"from payments import card\n\n\n"
"def pay():\n"
" return {\"card\": card.card_charge}\n"
),
})
pay = _id(r, "pay")
targets = {e["target"] for e in _edges(r, "indirect_call") if e["source"] == pay}
assert targets == {_id(r, "card_charge", "payments/card.py")}
def test_a_direct_call_is_not_duplicated_as_an_indirect_one(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n\n\n"
"def pay(amount):\n"
" card.card_charge(amount)\n"
" return {\"card\": card.card_charge}\n"
)})
pay, card_charge = _id(r, "pay"), _id(r, "card_charge")
assert (pay, card_charge) in _pairs(r, "calls")
assert (pay, card_charge) not in _pairs(r, "indirect_call")
def test_a_table_listed_before_the_direct_call_does_not_hide_it(tmp_path):
"""The precise `calls` edge wins regardless of which appears first in the body."""
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n\n\n"
"def pay(amount):\n"
" table = {\"card\": card.card_charge}\n"
" card.card_charge(amount)\n"
" return table\n"
)})
pay, card_charge = _id(r, "pay"), _id(r, "card_charge")
assert (pay, card_charge) in _pairs(r, "calls")
assert (pay, card_charge) not in _pairs(r, "indirect_call")
def test_both_spellings_in_one_table_give_one_edge(tmp_path):
r = _extract(tmp_path, {**PAYMENTS, "checkout.py": (
"from payments import card\n"
"from payments.card import card_charge\n\n\n"
"def pay():\n"
" return [card_charge, card.card_charge]\n"
)})
pay, card_charge = _id(r, "pay"), _id(r, "card_charge")
assert [(e["source"], e["target"]) for e in _edges(r, "indirect_call")].count((pay, card_charge)) == 1
def test_a_file_level_import_of_the_same_function_does_not_hide_the_edge(tmp_path):
"""`from payments.card import card_charge` adds an `imports` edge from the file
to the function. That is not a call and must not pre-empt the registry's edge."""
r = _extract(tmp_path, {**PAYMENTS, "registry.py": (
"from payments import card\n"
"from payments.card import card_charge\n\n"
"PROVIDERS = [card.card_charge]\n"
)})
registry = next(n["id"] for n in r["nodes"] if n["label"] == "registry.py")
assert (registry, _id(r, "card_charge")) in _pairs(r, "indirect_call")