fix(go): type a receiver's field when its struct is declared in a sibling file (#3368)

1695efae types `s.field.M()` through the caller file's own go_type_table.
When the struct is declared in another file of the package, the usual Go
layout, that file has no binding for `field` and the call is dropped, even
for a same-package field type.

Each Go file node now carries the field types of the structs it declares
(`_go_fields`, keyed by struct id), and a self-rooted raw call names the
struct that owns the field (`field_owner`). When the caller's table has no
binding, the resolver reads the owner struct's fields, only when the owner
is a single type declared by a single file. The fields ride on the file
node, not the struct node: every method file emits the struct's id too,
and on an incremental rebuild that fresh copy shadows the declaring
file's. `_go_fields` is carried through the incremental resolution
context, and the AST cache schema goes to 30.

(cherry picked from commit f3b1e7d87a)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-10-30 23:26:30 +00:00
1 parent 61e864a7b1
commit fdd25f7b31
5 files changed
+117 -2

No files matched your search

+1 -1
View File
@@ -4412,7 +4412,7 @@ def dispatch_command(cmd: str) -> None:
"_rust_impl_key", "_rust_declaration_count",
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture", "_py_return_type",
"_py_fixture", "_py_return_type", "_go_fields",
):
if _node.get(_marker):
_ctx_node[_marker] = _node[_marker]
+12
View File
@@ -7408,10 +7408,17 @@ def _resolve_go_member_calls(
# class would both answer a Go receiver and hide that nothing local declares it.
type_def_nids: dict[str, list[str]] = {}
node_by_id: dict[str, dict] = {}
# A struct's fields, by struct id, from the file node that declares it: a method in
# one file of the package and the struct in another is the common Go layout, and the
# caller's flat table holds only what its own file declares. An id two files declare
# has no single answer.
fields_by_type: dict[str, list[dict[str, 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"])
for struct_nid, fields in (n.get("_go_fields") or {}).items():
fields_by_type.setdefault(struct_nid, []).append(fields)
method_index: dict[tuple[str, str], list[str]] = {}
for e in all_edges:
@@ -7429,6 +7436,11 @@ def _resolve_go_member_calls(
# flat table: two types in one file may both name their receiver `s`.
type_name = rc.get("receiver_type") or type_table_by_file.get(
rc.get("source_file", ""), {}).get(receiver)
if not type_name and rc.get("field_owner"):
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)
if not type_name or type_name in _LANGUAGE_BUILTIN_GLOBALS:
continue
type_defs = type_def_nids.get(_key(type_name), [])
+53
View File
@@ -242,6 +242,41 @@ def _go_receiver_type_table(root, source: bytes) -> dict[str, str]:
return table
def _go_struct_field_types(root, source: bytes) -> dict[str, dict[str, str]]:
"""``struct name -> {field name -> TypeName}`` for every struct this file declares.
Only a named field whose type `_go_single_type_name` accepts is kept, the same rule
the flat receiver table applies. Unlike that table it stays keyed by the struct, so a
method in another file of the package can read the fields of its own receiver.
"""
fields_by_struct: dict[str, dict[str, str]] = {}
stack = [root]
while stack:
n = stack.pop()
if n.type in ("function_declaration", "method_declaration"):
continue
if n.type == "type_spec":
name_node = n.child_by_field_name("name")
body = n.child_by_field_name("type")
if name_node is not None and body is not None and body.type == "struct_type":
fields: dict[str, str] = {}
for fdl in body.children:
if fdl.type != "field_declaration_list":
continue
for field in fdl.children:
if field.type != "field_declaration":
continue
type_name = _go_single_type_name(field.child_by_field_name("type"), source)
for c in field.children if type_name else ():
if c.type == "field_identifier":
fields.setdefault(_read_text(c, source), type_name)
if fields:
fields_by_struct[_read_text(name_node, source)] = fields
continue
stack.extend(n.children)
return fields_by_struct
def extract_go(path: Path) -> dict:
"""Extract functions, methods, type declarations, and imports from a .go file."""
try:
@@ -720,6 +755,18 @@ def extract_go(path: Path) -> dict:
if n["id"] in callable_class_nids:
n["_callable_class"] = True
# 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()
}
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()))
type_table = _go_receiver_type_table(root, source)
label_to_nid: dict[str, str] = {}
@@ -743,6 +790,7 @@ def extract_go(path: Path) -> dict:
package_receiver: str | None = None
member_receiver: str | None = None
member_receiver_type: str | None = None
field_owner: str | None = None
import_path: str | None = None
if func_node:
if func_node.type == "identifier":
@@ -773,6 +821,7 @@ def extract_go(path: Path) -> dict:
and _read_text(inner, source) == self_name):
member_receiver = _read_text(
operand.child_by_field_name("field"), source)
field_owner = self_type
if field:
callee_name = _read_text(field, source)
if is_bare_identifier and callee_name in _GO_PREDECLARED_FUNCS:
@@ -815,6 +864,10 @@ def extract_go(path: Path) -> dict:
# declarations are in scope here; the flat table is the fallback for
# a struct field, and must not answer a name this scope rebinds.
"receiver_type": member_receiver_type,
# The struct whose field `member_receiver` is, for `s.field.M()`:
# the struct may be declared in another file of the package, where
# this file's flat table cannot see its fields.
"field_owner": field_owner,
"import_path": import_path,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
+1 -1
View File
@@ -2355,7 +2355,7 @@ def _rebuild_code(
"_rust_impl_key", "_rust_declaration_count",
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture", "_py_return_type",
"_py_fixture", "_py_return_type", "_go_fields",
):
if node.get(marker):
ctx_node[marker] = node[marker]
+50
View File
@@ -217,3 +217,53 @@ def test_a_parameter_binds_only_inside_its_own_function(tmp_path):
targets.setdefault(label_of.get(e["source"]), set()).add(source_of[e["target"]])
assert len(targets["Run()"]) == 1 and targets["Run()"].pop().endswith("greeter.go"), targets
assert len(targets["Also()"]) == 1 and targets["Also()"].pop().endswith("other.go"), targets
# The struct in one file of the package and its methods in another is the usual Go
# layout (`HTTPServer` declared in http_server.go, its handlers in datasources.go).
SIBLING_FILES = {
"svc/greeter.go": GREETER,
"svc/types.go": "package svc\n\ntype App struct {\n\tgreeter *Greeter\n}\n",
"svc/run.go": "package svc\n\nfunc (a *App) Run() { a.greeter.Greet() }\n",
}
def test_a_struct_field_declared_in_a_sibling_file_types_the_receiver(tmp_path):
# run.go declares no `greeter`, so its own table cannot answer; the struct's can.
calls, _ = _calls(tmp_path, SIBLING_FILES)
edge = _greet_edge(calls)
assert edge is not None, calls
assert edge["confidence"] == "INFERRED"
def test_a_sibling_files_struct_field_survives_a_rebuild_of_the_method_file_only(tmp_path):
# An update re-extracts only the changed file, and the struct's unchanged file reaches
# the resolver only as its graph.json nodes, so the field types must persist there.
import json
from graphify.watch import _rebuild_code
for name, body in 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 / "svc" / "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
def test_a_sibling_files_field_of_another_struct_does_not_type_the_receiver(tmp_path):
# `greeter` is a field of `Other`, not of `App`: the owner decides, not the name.
calls, _ = _calls(tmp_path, {
**SIBLING_FILES,
"svc/types.go": "package svc\n\ntype App struct{}\n\n"
"type Other struct {\n\tgreeter *Greeter\n}\n",
})
assert _greet_edge(calls) is None, calls