fix(go): link a method value passed as an argument as an indirect_call (#1566)

A Go handler or callback is registered by passing a method value:
`routing.Wrap(s.Health)`, `r.Get("/p", s.Health)`. The call walk looked
only at what a call expression invokes, so the method got no edge from
its registration and a handler reached only through its route had no
caller.

walk_calls now records each `x.M` argument (on a plain identifier, not an
imported package) as an `indirect` raw member call, typed the way a direct
`x.M()` is. _resolve_go_member_calls resolves it through the same receiver
type, single-declaration and single-method guards and emits an INFERRED
`indirect_call`, as Python and JS do. It is never parked for a merge: a
value argument is as often a field as a method. The AST cache schema goes
to 30.

(cherry picked from commit e724c0c44f)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-10-30 23:26:18 +00:00
1 parent 1c4c3f2c63
commit 61e864a7b1
3 files changed
+137 -4

No files matched your search

+9 -4
View File
@@ -7435,8 +7435,10 @@ def _resolve_go_member_calls(
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
# says who is asking, so no suffix sniff is needed.
_park_unresolved_member_call(node_by_id.get(caller), callee, type_name, "go", rc)
# says who is asking, so no suffix sniff is needed. A method value is not
# parked: `f(x.y)` may just as well pass a field, which is no call at all.
if not rc.get("indirect"):
_park_unresolved_member_call(node_by_id.get(caller), callee, type_name, "go", rc)
continue
if len(type_defs) != 1: # ambiguous -> bail (god-node guard)
continue
@@ -7447,11 +7449,14 @@ def _resolve_go_member_calls(
if target == caller or (caller, target) in existing_pairs:
continue
existing_pairs.add((caller, target))
indirect = bool(rc.get("indirect"))
all_edges.append({
"source": caller,
"target": target,
"relation": "calls",
"context": "call",
# A method value (`routing.Wrap(s.Handle)`) hands the method over to be
# called later, as an `indirect_call` does in the other languages (#1566).
"relation": "indirect_call" if indirect else "calls",
"context": rc.get("context", "argument") if indirect else "call",
"confidence": "INFERRED",
# The rubric's discrete INFERRED scale (references/extraction-spec.md):
# a single-definition type-table hit is the high-confidence rung.
+31
View File
@@ -819,6 +819,37 @@ def extract_go(path: Path) -> dict:
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
# A method value passed as an argument (`routing.Wrap(s.Handle)`,
# `r.Get("/p", s.Handle)`) is how Go registers a handler or callback. It is
# not a call here, so it never reached the branch above and the method had
# no caller. Record it for the member-call resolver as an indirect call
# through the receiver's declared type (#1566).
args = node.child_by_field_name("arguments")
for arg in args.children if args is not None else ():
if arg.type != "selector_expression":
continue
operand = arg.child_by_field_name("operand")
field = arg.child_by_field_name("field")
if operand is None or field is None or operand.type != "identifier":
continue
name = _read_text(operand, source)
if name in go_imported_pkgs:
continue
raw_calls.append({
"caller_nid": caller_nid,
"callee": _read_text(field, source),
"is_member_call": True,
"indirect": True,
"context": "argument",
"language": "go",
"receiver": None,
"member_receiver": name,
"receiver_type": self_type if self_name and name == self_name
else scope_types.get(name),
"import_path": None,
"source_file": str_path,
"source_location": f"L{arg.start_point[0] + 1}",
})
for child in node.children:
walk_calls(child, caller_nid, self_name, self_type, scope_types)
@@ -0,0 +1,97 @@
"""A Go method value passed as an argument links the caller to the method.
`routing.Wrap(s.Handle)` and `r.Get("/p", s.Handle)` are how Go registers a handler or a
callback. The method is not called at that site, so the call walk never saw it and a
handler reached only through its registration had no caller at all. It is recorded as
an INFERRED `indirect_call`, like a callback passed by name in Python and JS (#1566),
typed through the receiver's declared type the way the member-call resolver types a
direct call.
"""
from __future__ import annotations
import importlib
import pytest
from graphify.extract import extract
pytestmark = pytest.mark.skipif(
importlib.util.find_spec("tree_sitter_go") is None,
reason="tree_sitter_go not installed",
)
ROUTING = (
"package routing\n\ntype Handler func(string) string\n\n"
"func Wrap(h Handler) Handler { return h }\n"
)
SERVER = (
"package api\n\ntype Server struct{}\n\n"
"func (s *Server) Health(name string) string { return name }\n"
)
def _edges(tmp_path, files: dict[str, str]) -> dict[tuple[str, str, str], dict]:
for name, body in files.items():
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
result = extract([tmp_path / n for n in files if n.endswith(".go")],
cache_root=tmp_path / "graphify-out", parallel=False)
label = {n["id"]: n["label"] for n in result["nodes"]}
return {(label.get(e["source"]), e["relation"], label.get(e["target"])): e
for e in result["edges"] if e["relation"] in ("calls", "indirect_call")}
def _files(register: str) -> dict[str, str]:
return {
"go.mod": "module example.com/m\n\ngo 1.22\n",
"routing/routing.go": ROUTING,
"api/server.go": SERVER,
"api/routes.go": "package api\n\nimport \"example.com/m/routing\"\n\n" + register,
}
def test_a_method_value_on_the_methods_own_receiver_is_an_indirect_call(tmp_path):
edges = _edges(tmp_path, _files(
"func (s *Server) Register() routing.Handler {\n"
"\treturn routing.Wrap(s.Health)\n}\n"))
edge = edges.get((".Register()", "indirect_call", ".Health()"))
assert edge is not None, edges
assert edge["confidence"] == "INFERRED"
assert (".Register()", "calls", ".Health()") not in edges, edges
# The registration call itself is unchanged.
assert (".Register()", "calls", "Wrap()") in edges, edges
def test_a_method_value_on_a_typed_parameter_is_an_indirect_call(tmp_path):
edges = _edges(tmp_path, _files(
"func Register(s *Server) routing.Handler {\n"
"\treturn routing.Wrap(s.Health)\n}\n"))
assert ("Register()", "indirect_call", ".Health()") in edges, edges
def test_a_field_passed_as_an_argument_links_nothing_and_parks_nothing(tmp_path):
# `s.name` is a field, not a method; and `Unknown` is declared nowhere, which for a
# direct call would park it for a merge. A value argument is neither.
files = _files(
"type Holder struct {\n\tname string\n}\n\n"
"func (h *Holder) Use(u *Unknown) {\n\tprintln(h.name)\n\tkeep(u.Health)\n}\n\n"
"func keep(v any) {}\n")
for name, body in files.items():
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
result = extract([tmp_path / n for n in files if n.endswith(".go")],
cache_root=tmp_path / "graphify-out", parallel=False)
label = {n["id"]: n["label"] for n in result["nodes"]}
assert not [e for e in result["edges"] if e["relation"] == "indirect_call"], result["edges"]
use = next(n for n in result["nodes"] if label[n["id"]] == ".Use()")
assert not (use.get("metadata") or {}).get("unresolved_calls"), use
def test_a_package_function_value_is_not_read_as_a_method_value(tmp_path):
# `routing.Wrap` names a function of an imported package, not a method of a value.
edges = _edges(tmp_path, _files(
"func Register(s *Server) any {\n\treturn keep(routing.Wrap)\n}\n\n"
"func keep(v any) any { return v }\n"))
assert not [k for k in edges if k[1] == "indirect_call"], edges