feat(go): dispatch interface method calls to implicit implementers

A call through an interface-typed field lands on the interface's method
node, and nothing joins it to the concrete method, because Go types
satisfy interfaces implicitly and the shared interface_dispatch pass
only reads `implements` edges. So the concrete method loses every caller
that goes through the interface.

The Go extractor now stamps interface type nodes with
metadata {"language": "go", "kind": "interface"}, and a new
graphify.go_dispatch pass infers implementers from method sets (every
method name the interface requires, own and embedded) and feeds those
pairs to resolve_interface_dispatch. Empty interfaces, type-set
constraints, interfaces embedding an interface outside the corpus, and
interfaces with more than ten structural implementers are skipped; an
unexported requirement only matches types in the same package. The AST
cache schema is bumped so cached Go extractions pick up the stamp.

(cherry picked from commit 97ccefff72)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-11-03 19:46:14 +00:00
1 parent d90f9f5342
commit 6be19949d6
4 files changed
+367

No files matched your search

+9
View File
@@ -27,6 +27,7 @@ from .resolver_registry import (
)
from .ruby_resolution import resolve_ruby_member_calls
from .csharp_dispatch import resolve_csharp_interface_dispatch
from .go_dispatch import resolve_go_interface_dispatch
from .swift_dispatch import resolve_swift_protocol_dispatch
from .pascal_resolution import resolve_pascal_inherited_calls
from .markdown_resolution import MARKDOWN_MENTION_SUFFIXES, resolve_markdown_mentions
@@ -8284,6 +8285,14 @@ register_language_resolver(
"swift_protocol_dispatch", frozenset({".swift"}), resolve_swift_protocol_dispatch
)
)
# Go member-level interface dispatch: the same edge, but Go types satisfy an
# interface implicitly, so graphify.go_dispatch infers the implementers from
# method sets before handing them to graphify.interface_dispatch.
register_language_resolver(
LanguageResolver(
"go_interface_dispatch", frozenset({".go"}), resolve_go_interface_dispatch
)
)
# Markdown code-span mentions (`Widget`, `mod.py::Widget::render`) become
# heading --references--> symbol edges once every file is extracted and ids are
# final. Lives in graphify.markdown_resolution; the shared call pass above skips
+7
View File
@@ -337,6 +337,10 @@ def extract_go(path: Path) -> dict:
# guard and the cross-repo member-call pass both read them off the node.
callable_nids: set[str] = set()
callable_class_nids: set[str] = set()
# Go interfaces are satisfied implicitly, so nothing else in the output tells an
# interface's method requirements from a struct's methods; `graphify.go_dispatch`
# reads this stamp to know which owners are interfaces.
interface_nids: set[str] = set()
# local package name (including aliases) -> written Go import path
go_imported_pkgs: dict[str, str] = {}
@@ -700,6 +704,7 @@ def extract_go(path: Path) -> dict:
add_edge(type_nid, tgt, "references",
field.start_point[0] + 1, context=ctx)
elif type_body.type == "interface_type":
interface_nids.add(type_nid)
for elem in type_body.children:
if elem.type == "method_elem":
# A method requirement declared in the interface body
@@ -814,6 +819,8 @@ def extract_go(path: Path) -> dict:
n["_callable_class"] = True
if package_path:
n["_go_package_path"] = package_path
if n["id"] in interface_nids:
n["metadata"] = {"language": "go", "kind": "interface"}
# The field types of the structs this file declares ride on the file node, keyed by
# struct id, so a method in a sibling file can type `s.field` (#3368). Not on the
+129
View File
@@ -0,0 +1,129 @@
"""Member-level interface dispatch for Go.
`d.provider.GetWithDataSource()` where `provider` is a `pluginContextProvider`
resolves to the interface's own `.GetWithDataSource()` requirement, because that
is what the call site names. The concrete `Provider.GetWithDataSource()` is a
separate node, and nothing joins the two, so a directed walk stops at the
interface — the Go twin of the C# gap #3003 closed.
C# and Swift feed `graphify.interface_dispatch` with the `implements` edges
their extractors read off a declaration. Go has no such declaration: a type
implements an interface by having its methods. So this pass infers the pairs
from method sets and hands them to the shared mechanism, which does the rest
(per-method `dispatches_to` at INFERRED, 0.85 / 0.75 / 0.65 by implementer
count, the single-owner guard). The inferred `implements` pairs only feed the
mechanism; they are not added to the graph.
A named type T implements interface I here when T's methods (value and
pointer receivers alike: the extractor hangs both off T's node) include every
method name I requires. Names only: method nodes carry no signature, and Go has
no overloads to tell apart. The guards:
- Both ends are declared in a `.go` file, as in the C# and Swift passes.
- An interface with no methods (`interface{}`, `any`) or only a type set is
skipped: every type satisfies the first, and the second is a generics
constraint, not something a call goes through.
- An interface that embeds another is used only when every embedded interface
is declared in the corpus, with its methods counted in. `io.Reader` and
other external interfaces have unknown methods, so such an interface is
skipped rather than matched on part of its method set.
- An unexported method name (`run()`) can only be implemented in the
interface's own package, so only types in the same directory count.
- An interface matched by more than `_MAX_IMPLICIT_IMPLEMENTERS` types is
skipped. Name-only matching makes a lone common name (`Close`, `String`)
match unrelated types, and past this many the edges say little. The builtin
`error` and `fmt.Stringer` are not in the corpus, so they never match; a
local redeclaration of either is matched like any other interface.
Struct embedding is not followed: a type whose method comes from an embedded
field does not own that method node, so it is not matched.
"""
from __future__ import annotations
from pathlib import PurePath
from graphify.interface_dispatch import (
declared_in,
method_label,
resolve_interface_dispatch,
)
_GO_SUFFIXES = (".go",)
# Past this many structural implementers an interface is skipped, not truncated:
# which ten to keep would be arbitrary.
_MAX_IMPLICIT_IMPLEMENTERS = 10
def _is_go_interface(node: dict | None) -> bool:
meta = (node or {}).get("metadata")
return isinstance(meta, dict) and meta.get("language") == "go" and meta.get("kind") == "interface"
def resolve_go_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each Go interface method to the methods of every type that satisfies the interface."""
interfaces = {n.get("id"): n for n in all_nodes if _is_go_interface(n) and declared_in(n, _GO_SUFFIXES)}
if not interfaces:
return
node_by_id = {n.get("id"): n for n in all_nodes}
method_names: dict[str, set[str]] = {}
embeds: dict[str, set[str]] = {}
type_set_constrained: set[str] = set()
for e in all_edges:
rel, source = e.get("relation"), e.get("source")
if rel == "method":
mnode = node_by_id.get(e.get("target"))
if mnode is not None and declared_in(mnode, _GO_SUFFIXES) and method_label(mnode):
method_names.setdefault(source, set()).add(method_label(mnode))
elif source in interfaces and rel == "embeds":
embeds.setdefault(source, set()).add(e.get("target"))
elif source in interfaces and rel == "references" and e.get("context") == "type_constraint":
type_set_constrained.add(source)
def required(iface: str, visiting: frozenset[str] = frozenset()) -> set[str] | None:
# None: the method set is not fully known (an embedded interface outside
# the corpus, or an embedding cycle, which Go rejects anyway).
names = set(method_names.get(iface, ()))
for embedded in embeds.get(iface, ()):
if embedded not in interfaces or embedded in visiting:
return None
inner = required(embedded, visiting | {iface})
if inner is None:
return None
names |= inner
return names
candidates = {
owner: names for owner, names in method_names.items()
if owner not in interfaces and declared_in(node_by_id.get(owner), _GO_SUFFIXES)
}
inferred: list[dict] = []
for iface, iface_node in interfaces.items():
if iface in type_set_constrained or not method_names.get(iface):
continue
needed = required(iface)
if not needed:
continue
package = PurePath(str(iface_node.get("source_file"))).parent
same_package_only = any(not name[:1].isupper() for name in needed)
impls = [
owner for owner, names in candidates.items()
if needed <= names
and (not same_package_only
or PurePath(str(node_by_id[owner].get("source_file"))).parent == package)
]
if 0 < len(impls) <= _MAX_IMPLICIT_IMPLEMENTERS:
inferred.extend({"source": impl, "target": iface, "relation": "implements"} for impl in impls)
if not inferred:
return
# The shared resolver reads `implements` from the edge list it is given and
# appends its `dispatches_to` edges to that list; keep only the latter.
edges = all_edges + inferred
resolve_interface_dispatch(per_file, all_nodes, edges, suffixes=_GO_SUFFIXES)
all_edges.extend(edges[len(all_edges) + len(inferred):])
+222
View File
@@ -0,0 +1,222 @@
"""Go member-level interface dispatch.
`d.provider.GetWithDataSource()` on a field typed with a local interface
resolves to the interface's own `.GetWithDataSource()` requirement, which is
what the call site names. Go types satisfy an interface implicitly, so there
is no `implements` edge for the shared dispatch mechanism to read, and the
concrete method used to sit unreachable from every call through the interface.
`resolve_go_interface_dispatch` infers the implementers from method sets (every
method name the interface requires) and links each requirement to the matching
method. Confidence falls as the implementer count grows (0.85 / 0.75 / 0.65).
"""
from __future__ import annotations
from pathlib import Path
from graphify.extract import extract
_GO_MOD = "module example.com/app\n\ngo 1.22\n"
_PROVIDER = (
"package plugincontext\n\n"
"type Provider struct{}\n\n"
"func (p *Provider) GetWithDataSource(uid string) error { return p.lookup(uid) }\n\n"
"func (p *Provider) lookup(uid string) error { return nil }\n"
)
_NODES = (
"package expr\n\n"
"type pluginContextProvider interface {\n"
"\tGetWithDataSource(uid string) error\n"
"}\n\n"
"type DSNode struct {\n"
"\tprovider pluginContextProvider\n"
"}\n\n"
"func (d *DSNode) Execute() error {\n"
"\treturn d.provider.GetWithDataSource(\"x\")\n"
"}\n"
)
def _extract(tmp_path: Path, files: dict[str, str]):
(tmp_path / "go.mod").write_text(_GO_MOD)
for name, body in files.items():
p = tmp_path / name
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(body)
r = extract(
sorted(tmp_path / n for n in files),
cache_root=tmp_path / "cache",
root=tmp_path,
parallel=False,
)
dispatch = {(e["source"], e["target"]) for e in r["edges"]
if e["relation"] == "dispatches_to"}
return dispatch, r
def _find(r, label, id_contains):
return next(n["id"] for n in r["nodes"]
if n["label"] == label and id_contains in n["id"])
def _reachable(r, start: str) -> set[str]:
adjacency: dict[str, list[str]] = {}
for e in r["edges"]:
adjacency.setdefault(e["source"], []).append(e["target"])
seen = {start}
queue = [start]
while queue:
for nxt in adjacency.get(queue.pop(0), []):
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return seen
def test_local_interface_dispatches_to_an_implementer_in_another_package(tmp_path):
dispatch, r = _extract(tmp_path, {
"plugincontext/provider.go": _PROVIDER,
"expr/nodes.go": _NODES,
})
requirement = _find(r, ".GetWithDataSource()", "plugincontextprovider")
concrete = _find(r, ".GetWithDataSource()", "plugincontext_provider")
assert dispatch == {(requirement, concrete)}
edge = next(e for e in r["edges"] if e["relation"] == "dispatches_to")
assert edge["confidence"] == "INFERRED"
assert edge["confidence_score"] == 0.85
assert edge["context"] == "call"
assert edge["source_file"].endswith("provider.go")
# Additive: the call to the interface method stays, and the chain now
# continues into the concrete method's own callees.
calls = {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
assert (_find(r, ".Execute()", "dsnode"), requirement) in calls
assert _find(r, ".lookup()", "provider") in _reachable(r, _find(r, ".Execute()", "dsnode"))
# The inferred pairs feed the dispatch pass; they are not graph edges.
assert not any(e["relation"] == "implements" for e in r["edges"])
def test_value_and_pointer_receivers_both_count(tmp_path):
dispatch, r = _extract(tmp_path, {"shape/shape.go": (
"package shape\n\n"
"type Shape interface {\n\tArea() float64\n\tName() string\n}\n\n"
"type Square struct{ side float64 }\n\n"
"func (s Square) Area() float64 { return s.side * s.side }\n\n"
"func (s *Square) Name() string { return \"square\" }\n"
)})
assert dispatch == {
(_find(r, ".Area()", "shape_shape"), _find(r, ".Area()", "square")),
(_find(r, ".Name()", "shape_shape"), _find(r, ".Name()", "square")),
}
def test_a_type_missing_one_method_does_not_implement(tmp_path):
dispatch, _ = _extract(tmp_path, {"shape/shape.go": (
"package shape\n\n"
"type Shape interface {\n\tArea() float64\n\tName() string\n}\n\n"
"type Square struct{}\n\n"
"func (s Square) Area() float64 { return 1 }\n"
)})
assert not dispatch
def test_two_implementers_both_get_an_edge_at_lower_confidence(tmp_path):
dispatch, r = _extract(tmp_path, {"shape/shape.go": (
"package shape\n\n"
"type Shape interface {\n\tArea() float64\n}\n\n"
"type Square struct{}\n\n"
"func (s Square) Area() float64 { return 1 }\n\n"
"type Circle struct{}\n\n"
"func (c *Circle) Area() float64 { return 2 }\n"
)})
requirement = _find(r, ".Area()", "shape_shape")
assert dispatch == {
(requirement, _find(r, ".Area()", "square")),
(requirement, _find(r, ".Area()", "circle")),
}
assert {e["confidence_score"] for e in r["edges"]
if e["relation"] == "dispatches_to"} == {0.75}
def test_empty_interface_is_ignored(tmp_path):
dispatch, _ = _extract(tmp_path, {"box/box.go": (
"package box\n\n"
"type Anything interface{}\n\n"
"type Box struct{ v Anything }\n\n"
"func (b Box) Get() Anything { return b.v }\n"
)})
assert not dispatch
def test_embedded_interface_methods_are_required(tmp_path):
# ReadCloser requires Read (via Reader) and Close; File has both, Pipe only Close.
dispatch, r = _extract(tmp_path, {"io2/io.go": (
"package io2\n\n"
"type Reader interface {\n\tRead() int\n}\n\n"
"type ReadCloser interface {\n\tReader\n\tClose() error\n}\n\n"
"type File struct{}\n\n"
"func (f *File) Read() int { return 0 }\n\n"
"func (f *File) Close() error { return nil }\n\n"
"type Pipe struct{}\n\n"
"func (p *Pipe) Close() error { return nil }\n"
)})
assert (_find(r, ".Close()", "readcloser"), _find(r, ".Close()", "file")) in dispatch
assert (_find(r, ".Read()", "reader"), _find(r, ".Read()", "file")) in dispatch
assert not any("pipe" in target for _, target in dispatch)
def test_interface_embedding_an_external_interface_is_skipped(tmp_path):
# io.Reader's methods are not in the corpus, so the method set is unknown.
dispatch, _ = _extract(tmp_path, {"rc/rc.go": (
"package rc\n\n"
"import \"io\"\n\n"
"type ReadCloser interface {\n\tio.Reader\n\tClose() error\n}\n\n"
"type Pipe struct{}\n\n"
"func (p *Pipe) Close() error { return nil }\n"
)})
assert not dispatch
def test_unexported_method_is_only_implemented_in_the_same_package(tmp_path):
dispatch, r = _extract(tmp_path, {
"a/a.go": (
"package a\n\n"
"type runner interface {\n\trun()\n}\n\n"
"type local struct{}\n\n"
"func (l local) run() {}\n"
),
"b/b.go": "package b\n\ntype remote struct{}\n\nfunc (r remote) run() {}\n",
})
assert dispatch == {(_find(r, ".run()", "a_runner"), _find(r, ".run()", "a_local"))}
def test_interface_with_too_many_implementers_is_skipped(tmp_path):
from graphify.go_dispatch import _MAX_IMPLICIT_IMPLEMENTERS
types = "".join(
f"type T{i} struct{{}}\n\nfunc (t T{i}) Close() error {{ return nil }}\n\n"
for i in range(_MAX_IMPLICIT_IMPLEMENTERS + 1)
)
dispatch, _ = _extract(tmp_path, {"c/c.go": (
"package c\n\ntype closer interface {\n\tClose() error\n}\n\n" + types
)})
assert not dispatch
def test_a_non_go_interface_is_untouched(tmp_path):
from graphify.go_dispatch import resolve_go_interface_dispatch
nodes = [
{"id": "iface", "label": "IR", "source_file": "a.cs",
"metadata": {"language": "go", "kind": "interface"}},
{"id": "impl", "label": "A", "source_file": "a.go"},
{"id": "iface_m", "label": ".M()", "source_file": "a.cs"},
{"id": "impl_m", "label": ".M()", "source_file": "a.go"},
]
edges = [
{"source": "iface", "target": "iface_m", "relation": "method"},
{"source": "impl", "target": "impl_m", "relation": "method"},
]
resolve_go_interface_dispatch([], nodes, edges)
assert not any(e["relation"] == "dispatches_to" for e in edges)