fix(go): resolve member calls on receivers typed from another package (#3368)

1695efae resolves a Go member call through the receiver's declared type,
but only when that type is declared in the caller's own package:
_go_single_type_name drops a qualified_type (`pkg.T`) because no bare
local name can stand for it. A dependency held as a field is almost always
typed from another package (`*plugincontext.Provider`, `plugins.Client`),
so the common case of #3368 still produced no calls edge, including when
the struct is declared in a sibling file (fdd25f7b).

The file's import of `pkg` is exact evidence of which `T` is meant. The
type table now keeps `pkg.T` as written, and _resolve_go_member_calls binds
it only to a `T` whose node carries the import path the caller imports
`pkg` from. Each Go type node records that path (`_go_package_path`, from
go.mod), and the incremental resolution context forwards it, so an
unchanged declaring file still answers on an update.

A sibling file's struct field (`_go_fields`) is stored as
`<import path>.T`, settled by the declaring file's imports: the method
file reading it, like Grafana's datasources.go reading
`HTTPServer.pluginClient plugins.Client`, need not import `pkg` itself.

Stdlib and out-of-corpus types stay unresolved and are not parked. The
qualifier also settles two packages declaring the same `T`, which the
bare-name path must leave alone.

Bumps _AST_CACHE_SCHEMA to 34 so cached Go extractions re-run.

(cherry picked from commit 048685ada1)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-11-03 19:45:14 +00:00
1 parent 8ed0f30698
commit d90f9f5342
5 files changed
+232 -8

No files matched your search

+1
View File
@@ -4489,6 +4489,7 @@ def dispatch_command(cmd: str) -> None:
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture", "_py_return_type", "_go_fields",
"_go_package_path",
):
if _node.get(_marker):
_ctx_node[_marker] = _node[_marker]
+34 -1
View File
@@ -7686,6 +7686,10 @@ def _resolve_go_member_calls(
A receiver typed to a type this corpus declares nowhere is parked on the caller for
a merged graph to finish (#3152).
A package-qualified type (`plugins.Client`, `*svc.Greeter`), the usual shape of a
dependency injected from another package, resolves through the caller's import of
that package: only a declaration whose file sits at the imported path qualifies.
"""
raw = [
rc
@@ -7697,10 +7701,12 @@ def _resolve_go_member_calls(
if not raw:
return
package_vars_by_file: dict[str, dict[str, str | None]] = {}
imports_by_file: dict[str, dict[str, str]] = {}
for result in per_file:
tt = result.get("go_type_table")
if tt and tt.get("path"):
package_vars_by_file[tt["path"]] = tt.get("package_vars", {})
imports_by_file[tt["path"]] = result.get("go_imports") or {}
def _key(label: object) -> str:
return str(label or "").strip().removeprefix(".").removesuffix("()")
@@ -7715,10 +7721,16 @@ def _resolve_go_member_calls(
# Owner fields may be declared in a sibling file. Duplicate owner declarations
# provide no unique field type.
fields_by_type: dict[str, list[dict[str, str]]] = {}
# A Go type node id folds in only the package directory's name, which says nothing
# about the import path (`api/v1` and `web/v1` even share one); the files that declare
# the node do, so a node keeps every path it is declared at.
package_paths_by_nid: dict[str, set[str]] = {}
for n in all_nodes:
node_by_id[n.get("id")] = n
if n.get("_callable_class") and _lang_family(n.get("source_file")) == "go":
type_def_nids.setdefault(_key(n.get("label", "")), []).append(n["id"])
if n.get("_go_package_path"):
package_paths_by_nid.setdefault(n["id"], set()).add(n["_go_package_path"])
for struct_nid, fields in (n.get("_go_fields") or {}).items():
fields_by_type.setdefault(struct_nid, []).append(fields)
@@ -7735,18 +7747,39 @@ def _resolve_go_member_calls(
# One edge survives per pair, so direct calls must take priority over method values.
for rc in sorted(raw, key=lambda call: bool(call.get("indirect"))):
receiver, callee, caller = rc["member_receiver"], rc["callee"], rc["caller_nid"]
# The enclosing method's own receiver is typed by its declaration (the
# scoped `receiver_type`), which already covers params and locals. A field
# receiver is typed from its owning struct's declaration instead.
type_name = rc.get("receiver_type")
from_sibling = False
if rc.get("field_owner"):
type_name = None
owner_defs = type_def_nids.get(_key(rc["field_owner"]), [])
declared = fields_by_type.get(owner_defs[0], []) if len(owner_defs) == 1 else []
if len(declared) == 1:
type_name = declared[0].get(receiver)
from_sibling = True
elif not type_name and not rc.get("receiver_bound"):
type_name = package_vars_by_file.get(rc.get("source_file", ""), {}).get(receiver)
if not type_name or type_name in _LANGUAGE_BUILTIN_GLOBALS:
continue
type_defs = type_def_nids.get(_key(type_name), [])
if "." in type_name:
# `pkg.T`: bind only to the `T` declared at the path this file imports `pkg`
# from. That is exact import evidence, so it also settles two packages that
# both declare `T`. No match means stdlib or a module outside this corpus,
# which stays unresolved as before rather than being parked. A sibling file's
# field already carries the import path in place of `pkg`.
if from_sibling:
import_path, _, bare = type_name.rpartition(".")
else:
alias, _, bare = type_name.partition(".")
import_path = imports_by_file.get(rc.get("source_file", ""), {}).get(alias)
type_defs = [nid for nid in type_def_nids.get(_key(bare), [])
if import_path and import_path in package_paths_by_nid.get(nid, ())]
if not type_defs:
continue
else:
type_defs = type_def_nids.get(_key(type_name), [])
if not type_defs:
# Declared nowhere here — usually "in a repo this build does not contain",
# so park it for the merge (#3152). The extractor's language tag already
+32 -7
View File
@@ -12,6 +12,7 @@ from graphify.extractors.base import (
_read_source_bytes,
_read_text,
)
from graphify.extractors.resolution import _go_import_path_for_file
_GO_PREDECLARED_TYPES = frozenset({
@@ -175,13 +176,22 @@ def _go_strip_generic_args(type_text: str) -> str:
def _go_single_type_name(node, source: bytes) -> str | None:
"""The one declared type a Go type expression names, or None.
Generic arguments do not change the receiver's base type. A slice, map or channel
element is not the receiver, and a qualified type cannot bind by bare local name.
`Greeter`, `*Greeter`, `pkg.Greeter` and `*pkg.Greeter` qualify, and generic
arguments do not change the receiver's base type. A slice, map or channel
element is not the receiver of `x.M()`. A qualified type keeps its package
qualifier as written (`pkg.Greeter`): no bare local name can stand for it, so
the resolver binds it only through the file's import of `pkg`.
"""
while node is not None and node.type in ("pointer_type", "parenthesized_type", "generic_type"):
node = node.child_by_field_name("type") or next(
(c for c in node.children if c.is_named), None,
)
if node is not None and node.type == "qualified_type":
package = node.child_by_field_name("package")
name_node = node.child_by_field_name("name")
if package is None or name_node is None:
return None
return f"{_read_text(package, source)}.{_read_text(name_node, source)}"
if node is None or node.type != "type_identifier":
return None
name = _read_text(node, source)
@@ -792,21 +802,36 @@ def extract_go(path: Path) -> dict:
walk(root)
# A type carries both markers, as in the tree-sitter engine: `_callable_class` is
# the narrowing, not a separate kind.
# the narrowing, not a separate kind. A type also carries its import path from go.mod:
# a `pkg.T` receiver binds only to a `T` declared at the path the caller imports `pkg`
# from, and on an incremental rebuild an unchanged declaring file reaches the resolver
# only as its nodes.
package_path = _go_import_path_for_file(path.absolute(), path.absolute().parent)
for n in nodes:
if n["id"] in callable_nids or n["id"] in callable_class_nids:
n["_callable"] = True
if n["id"] in callable_class_nids:
n["_callable_class"] = True
if package_path:
n["_go_package_path"] = package_path
# 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
# struct node: every file holding a method of the struct emits that id too, so an
# incremental rebuild of a method file would shadow the declaring file's copy.
struct_fields = {
type_symbol_nid(name): dict(sorted(fields.items()))
for name, fields in _go_struct_field_types(root, source).items()
}
# A `pkg.T` field is stored as `<import path>.T`: the method file reading it may not
# import `pkg` at all, so the qualifier is settled by this file's imports.
struct_fields: dict[str, dict[str, str]] = {}
for name, fields in _go_struct_field_types(root, source).items():
typed: dict[str, str] = {}
for field, type_name in fields.items():
alias, dot, bare = type_name.partition(".")
if not dot:
typed[field] = type_name
elif alias in go_imported_pkgs:
typed[field] = f"{go_imported_pkgs[alias]}.{bare}"
if typed:
struct_fields[type_symbol_nid(name)] = dict(sorted(typed.items()))
if struct_fields:
file_node = next(n for n in nodes if n["id"] == file_nid)
file_node["_go_fields"] = dict(sorted(struct_fields.items()))
+1
View File
@@ -2562,6 +2562,7 @@ def _rebuild_code(
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture", "_py_return_type", "_go_fields",
"_go_package_path",
):
if node.get(marker):
ctx_node[marker] = node[marker]
+164
View File
@@ -265,3 +265,167 @@ def test_a_sibling_files_field_of_another_struct_does_not_type_the_receiver(tmp_
"type Other struct {\n\tgreeter *Greeter\n}\n",
})
assert _greet_edge(calls) is None, calls
# Package-qualified receiver types. Dependency injection in Go almost always crosses a
# package: a field typed `*svc.Greeter` or `plugins.Client` held by a type in another
# package. These resolve through the caller's import of the package, matched against the
# import path each declaring file gets from go.mod.
GO_MOD = "module example.com/app\n\ngo 1.22\n"
SVC_IMPORT = "import \"example.com/app/svc\"\n\n"
def _greet_targets(result) -> dict[str, set[str]]:
source_of = {n["id"]: str(n.get("source_file") or "") for n in result["nodes"]}
label_of = {n["id"]: n["label"] for n in result["nodes"]}
targets: dict[str, set[str]] = {}
for e in result["edges"]:
if e["relation"] == "calls" and label_of.get(e["target"]) == ".Greet()":
targets.setdefault(label_of.get(e["source"]), set()).add(
source_of[e["target"]].replace("\\", "/"))
return targets
def test_a_qualified_struct_field_types_the_receiver(tmp_path):
calls, _ = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": GREETER,
"api/app.go": "package api\n\n" + SVC_IMPORT
+ "type App struct {\n\tgreeter *svc.Greeter\n}\n\n"
"func (a *App) Run() { a.greeter.Greet() }\n",
})
edge = _greet_edge(calls)
assert edge is not None, calls
assert edge["confidence"] == "INFERRED"
def test_a_qualified_parameter_types_the_receiver(tmp_path):
calls, _ = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": GREETER,
"api/app.go": "package api\n\n" + SVC_IMPORT + "func Run(g *svc.Greeter) { g.Greet() }\n",
})
assert _greet_edge(calls) is not None, calls
@pytest.mark.parametrize("binding", ["var g svc.Greeter", "g := &svc.Greeter{}"])
def test_a_qualified_local_binding_types_the_receiver(tmp_path, binding):
calls, _ = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": GREETER,
"api/app.go": "package api\n\n" + SVC_IMPORT
+ f"func Run() {{\n\t{binding}\n\tg.Greet()\n}}\n",
})
assert _greet_edge(calls) is not None, calls
def test_an_aliased_import_types_the_receiver(tmp_path):
calls, _ = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": GREETER,
"api/app.go": "package api\n\nimport greet \"example.com/app/svc\"\n\n"
"func Run(g *greet.Greeter) { g.Greet() }\n",
})
assert _greet_edge(calls) is not None, calls
def test_a_qualified_interface_field_reaches_the_interface_method(tmp_path):
calls, _ = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": "package svc\n\ntype Greeter interface {\n\tGreet()\n}\n",
"api/app.go": "package api\n\n" + SVC_IMPORT
+ "type App struct {\n\tgreeter svc.Greeter\n}\n\n"
"func (a *App) Run() { a.greeter.Greet() }\n",
})
assert _greet_edge(calls) is not None, calls
def test_the_import_picks_one_of_two_packages_declaring_the_type(tmp_path):
# Bare `Greeter` with two declarations stays unresolved (the single-definition guard);
# `b.Greeter` names one of them through the import, so it is exact.
_, result = _calls(tmp_path, {
"go.mod": GO_MOD,
"a/greeter.go": GREETER.replace("package svc", "package a"),
"b/greeter.go": GREETER.replace("package svc", "package b"),
"api/app.go": "package api\n\nimport \"example.com/app/b\"\n\n"
"func Run(g *b.Greeter) { g.Greet() }\n",
})
targets = _greet_targets(result)
assert targets.get("Run()") and all(t.endswith("b/greeter.go") for t in targets["Run()"]), targets
def test_a_qualifier_never_binds_a_same_named_type_at_another_path(tmp_path):
# `other.Greeter` is imported from a module this corpus does not contain; the local
# `svc.Greeter` shares the name but not the path, so nothing binds and nothing is parked.
calls, result = _calls(tmp_path, {
"go.mod": GO_MOD,
"svc/greeter.go": GREETER,
"api/app.go": "package api\n\nimport \"example.org/other\"\n\n"
"func Run(g *other.Greeter) { g.Greet() }\n",
})
assert _greet_edge(calls) is None, calls
assert not [n for n in result["nodes"] if n["label"] == "Run()"
and (n.get("metadata") or {}).get("unresolved_calls")], result["nodes"]
# The Grafana shape of #3368: `HTTPServer` is declared in http_server.go with a field typed
# `plugins.Client`, and the handler calling `hs.pluginClient.CheckHealth()` lives in a
# sibling file that does not import `plugins` itself.
XPKG_SIBLING_FILES = {
"go.mod": GO_MOD,
"svc/greeter.go": "package svc\n\ntype Greeter interface {\n\tGreet()\n}\n",
"api/server.go": "package api\n\n" + SVC_IMPORT
+ "type App struct {\n\tgreeter svc.Greeter\n}\n",
"api/run.go": "package api\n\nfunc (a *App) Run() { a.greeter.Greet() }\n",
}
def test_a_qualified_field_declared_in_a_sibling_file_types_the_receiver(tmp_path):
calls, result = _calls(tmp_path, XPKG_SIBLING_FILES)
edge = _greet_edge(calls)
assert edge is not None, calls
assert edge["confidence"] == "INFERRED"
targets = _greet_targets(result)
assert targets.get(".Run()") and all(t.endswith("svc/greeter.go") for t in targets[".Run()"]), targets
def test_a_sibling_files_qualifier_is_read_from_the_declaring_files_imports(tmp_path):
# run.go imports a different package under the same name `svc`; the field's `svc` is
# the one server.go imports, so the caller's own import must not decide.
calls, _ = _calls(tmp_path, {
**XPKG_SIBLING_FILES,
"api/run.go": "package api\n\nimport svc \"example.org/other\"\n\nvar _ svc.X\n\n"
"func (a *App) Run() { a.greeter.Greet() }\n",
})
assert _greet_edge(calls) is not None, calls
def test_a_sibling_files_qualified_field_from_outside_the_corpus_resolves_to_nothing(tmp_path):
calls, _ = _calls(tmp_path, {
**XPKG_SIBLING_FILES,
"api/server.go": "package api\n\nimport svc \"example.org/other\"\n\n"
"type App struct {\n\tgreeter svc.Greeter\n}\n",
})
assert _greet_edge(calls) is None, calls
def test_a_sibling_files_qualified_field_survives_a_rebuild_of_the_method_file_only(tmp_path):
import json
from graphify.watch import _rebuild_code
for name, body in XPKG_SIBLING_FILES.items():
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
assert _rebuild_code(tmp_path, no_cluster=True, acquire_lock=False, force=True)
run = tmp_path / "api" / "run.go"
run.write_text(run.read_text(encoding="utf-8") + "// touched\n", encoding="utf-8")
assert _rebuild_code(tmp_path, changed_paths=[run], no_cluster=True, acquire_lock=False)
g = json.loads((tmp_path / "graphify-out" / "graph.json").read_text(encoding="utf-8"))
label = {n["id"]: n["label"] for n in g["nodes"]}
calls = {(label.get(e["source"]), label.get(e["target"]))
for e in g.get("links", g.get("edges", [])) if e["relation"] == "calls"}
assert (".Run()", ".Greet()") in calls, calls