Skip to content

Commit 1695efa

Browse files
xiongjianxusafishamsi
authored andcommitted
feat(go): resolve member calls through the receiver's declared type
`g.Greet()` where `Greeter` is declared in another file produced no edge. The shared cross-file pass skips member calls, and the Go extractor read the receiver's identifier only to discard it for anything that was not an imported package — so the one shape Go dependency injection actually takes (a struct field used from a method) contributed nothing to the call graph. `extract_go` now exports a per-file `go_type_table` built from the four places a Go receiver's type is written down: a struct field, a parameter (which covers the method receiver `func (s *Server)`), `var x T`, and `x := T{}` / `x := &T{}`. `_resolve_go_member_calls` looks the receiver up there, takes the single declaration of that type and emits the `calls` edge to its method. Also stamps `_callable` / `_callable_class` on Go declarations (#2438). Go is the one extractor outside the tree-sitter engine, so its nodes carried neither, which left them invisible to every consumer that reads the markers off the node. Design notes: - The receiver travels as `member_receiver`, not `receiver`: in this extractor `receiver` means "imported package", and the Swift/Python/Ruby member-call resolvers select on `is_member_call` plus `receiver` without checking the language, so a Go name there binds to their types in a mixed corpus. - `s.logger.Log()` is read as a call on the `logger` field only when `s` is the enclosing method's own receiver. The table is flat and file-scoped, so any other head could be a package or a variable whose type it cannot confirm. - Names are matched case-sensitively, unlike the sibling resolvers. Go exports by capitalisation, so `Run` and `run` on one type are two different methods. - Go does not defer: a member call reaches `raw_calls` only once the bare callee name misses in the caller's file, so in-file behaviour is byte-identical. - Two packages declaring the same name stay two type nodes and the single-definition guard bails — without import evidence neither is the answer. (cherry picked from commit deca9fa)
1 parent 15d2312 commit 1695efa

3 files changed

Lines changed: 354 additions & 7 deletions

File tree

‎graphify/extract.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6796,6 +6796,92 @@ def _resolve_rust_self_member_calls(
67966796
})
67976797

67986798

6799+
def _resolve_go_member_calls(
6800+
per_file: list[dict],
6801+
all_nodes: list[dict],
6802+
all_edges: list[dict],
6803+
) -> None:
6804+
"""Resolve Go member calls (``g.Greet()``) through the receiver's declared type.
6805+
6806+
The shared cross-file pass skips member calls, so a method call on a receiver whose
6807+
type is declared in another file resolved to nothing. The per-file ``go_type_table``
6808+
names the declared type of every struct field, parameter (the method receiver
6809+
included), ``var x T`` and ``x := T{}`` binding; this pass looks the receiver up
6810+
there, takes the single declaration of that type, and emits the ``calls`` edge to its
6811+
method. Always INFERRED: the type comes from the table, never from the call site.
6812+
6813+
Names are matched case-sensitively, unlike the sibling resolvers. Go exports by
6814+
capitalisation, so `Run` and `run` on one type are two different methods with two
6815+
different visibilities, and folding them would pick whichever came last.
6816+
"""
6817+
raw = [
6818+
rc
6819+
for result in per_file
6820+
for rc in result.get("raw_calls", [])
6821+
if rc.get("language") == "go" and rc.get("is_member_call")
6822+
and rc.get("member_receiver") and rc.get("callee") and rc.get("caller_nid")
6823+
]
6824+
if not raw:
6825+
return
6826+
type_table_by_file: dict[str, dict[str, str]] = {}
6827+
for result in per_file:
6828+
tt = result.get("go_type_table")
6829+
if tt and tt.get("path"):
6830+
type_table_by_file[tt["path"]] = tt.get("table", {})
6831+
6832+
def _key(label: object) -> str:
6833+
return str(label or "").strip().removeprefix(".").removesuffix("()")
6834+
6835+
# A Go type node id folds in the package directory, so two packages declaring the
6836+
# same name stay two entries and the single-definition guard below bails: without
6837+
# import evidence neither one is the answer.
6838+
type_def_nids: dict[str, list[str]] = {}
6839+
node_by_id: dict[str, dict] = {}
6840+
for n in all_nodes:
6841+
node_by_id[n.get("id")] = n
6842+
if n.get("_callable_class") and n.get("source_file"):
6843+
type_def_nids.setdefault(_key(n.get("label", "")), []).append(n["id"])
6844+
6845+
method_index: dict[tuple[str, str], list[str]] = {}
6846+
for e in all_edges:
6847+
if e.get("relation") != "method":
6848+
continue
6849+
tnode = node_by_id.get(e.get("target"))
6850+
if tnode is not None:
6851+
method_index.setdefault(
6852+
(e.get("source"), _key(tnode.get("label", ""))), []).append(e["target"])
6853+
6854+
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
6855+
for rc in raw:
6856+
receiver, callee, caller = rc["member_receiver"], rc["callee"], rc["caller_nid"]
6857+
type_name = type_table_by_file.get(rc.get("source_file", ""), {}).get(receiver)
6858+
if not type_name or type_name in _LANGUAGE_BUILTIN_GLOBALS:
6859+
continue
6860+
type_defs = type_def_nids.get(_key(type_name), [])
6861+
if len(type_defs) != 1: # ambiguous or absent -> bail (god-node guard)
6862+
continue
6863+
targets = method_index.get((type_defs[0], _key(callee)), [])
6864+
if len(targets) != 1:
6865+
continue
6866+
target = targets[0]
6867+
if target == caller or (caller, target) in existing_pairs:
6868+
continue
6869+
existing_pairs.add((caller, target))
6870+
all_edges.append({
6871+
"source": caller,
6872+
"target": target,
6873+
"relation": "calls",
6874+
"context": "call",
6875+
"confidence": "INFERRED",
6876+
# The rubric's discrete INFERRED scale (references/extraction-spec.md):
6877+
# a single-definition type-table hit is the high-confidence rung.
6878+
"confidence_score": 0.85,
6879+
"source_file": rc.get("source_file", ""),
6880+
"source_location": rc.get("source_location"),
6881+
"weight": 1.0,
6882+
})
6883+
6884+
67996885
def _resolve_elixir_import_targets(
68006886
per_file: list[dict],
68016887
all_nodes: list[dict],
@@ -7145,6 +7231,12 @@ def _resolve_kotlin_member_calls(
71457231
"kotlin_member_calls", frozenset({".kt", ".kts"}), _resolve_kotlin_member_calls
71467232
)
71477233
)
7234+
# Go receiver-typed member-call resolution: `g.Greet()` where the method is declared in
7235+
# another file. The shared pass skips member calls, so these had no edge unless the bare
7236+
# method name happened to match a symbol in the caller's own file.
7237+
register_language_resolver(
7238+
LanguageResolver("go_member_calls", frozenset({".go"}), _resolve_go_member_calls)
7239+
)
71487240
# C# qualified construction (#2997): `new A.B.Cache()` arrives as the bare name,
71497241
# so a colliding `Cache` elsewhere makes it ambiguous. Runs in the tail registry
71507242
# beside csharp_member_calls and matches the prefix against declared namespaces.

‎graphify/extractors/go.py‎

Lines changed: 101 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,58 @@ def _go_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[st
133133
if c.is_named:
134134
_go_collect_type_refs(c, source, generic, out, skip)
135135

136+
def _go_single_type_name(node, source: bytes) -> str | None:
137+
"""The one declared type a Go type expression names, or None.
138+
139+
Only `Greeter` and `*Greeter` qualify. A slice, map or channel element is not the
140+
receiver of `x.M()`, and a `qualified_type` (`pkg.Greeter`) names a type no bare
141+
local name can stand for.
142+
"""
143+
if node is not None and node.type == "pointer_type":
144+
node = next((c for c in node.children if c.is_named), None)
145+
if node is None or node.type != "type_identifier":
146+
return None
147+
name = _read_text(node, source)
148+
return name if name and name not in _GO_PREDECLARED_TYPES else None
149+
150+
151+
def _go_receiver_type_table(root, source: bytes) -> dict[str, str]:
152+
"""Collect ``name -> TypeName`` for every Go receiver whose type is written down.
153+
154+
Four sources: a struct field, a parameter (which covers the method receiver
155+
`func (s *Server)`), `var x T`, and `x := T{}` / `x := &T{}`. File-scoped and flat,
156+
first binding wins — a parameter shadowing a field in another function must not
157+
retype the field's own calls. Children are pushed reversed so the walk yields
158+
document order and "first" means first in the file.
159+
"""
160+
table: dict[str, str] = {}
161+
stack = [root]
162+
while stack:
163+
n = stack.pop()
164+
t = n.type
165+
if t in ("field_declaration", "parameter_declaration", "var_spec"):
166+
type_name = _go_single_type_name(n.child_by_field_name("type"), source)
167+
for c in n.children if type_name else ():
168+
if c.type in ("field_identifier", "identifier"):
169+
table.setdefault(_read_text(c, source), type_name)
170+
elif t == "short_var_declaration":
171+
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
172+
if left is not None and right is not None:
173+
names = [c for c in left.children if c.type == "identifier"]
174+
values = [c for c in right.children if c.is_named]
175+
for name_node, value in zip(names, values):
176+
if value.type == "unary_expression":
177+
value = value.child_by_field_name("operand") or value
178+
if value.type != "composite_literal":
179+
continue
180+
type_name = _go_single_type_name(
181+
value.child_by_field_name("type"), source)
182+
if type_name:
183+
table.setdefault(_read_text(name_node, source), type_name)
184+
stack.extend(reversed(n.children))
185+
return table
186+
187+
136188
def extract_go(path: Path) -> dict:
137189
"""Extract functions, methods, type declarations, and imports from a .go file."""
138190
try:
@@ -158,7 +210,13 @@ def extract_go(path: Path) -> dict:
158210
nodes: list[dict] = []
159211
edges: list[dict] = []
160212
seen_ids: set[str] = set()
161-
function_bodies: list[tuple[str, object]] = []
213+
# `(caller nid, body, receiver variable name)` — the receiver name is what makes
214+
# `s.logger.Log()` readable as a call on the `logger` field rather than on `s`.
215+
function_bodies: list[tuple[str, object, str | None]] = []
216+
# Fed to the `_callable` / `_callable_class` stamp below (#2438): the indirect-call
217+
# guard and the cross-repo member-call pass both read them off the node.
218+
callable_nids: set[str] = set()
219+
callable_class_nids: set[str] = set()
162220
# local package name (including aliases) -> written Go import path
163221
go_imported_pkgs: dict[str, str] = {}
164222

@@ -351,22 +409,27 @@ def walk(node) -> None:
351409
line = node.start_point[0] + 1
352410
func_nid = symbol_nid(_make_id(stem, func_name), func_name)
353411
add_node(func_nid, f"{func_name}()", line)
412+
callable_nids.add(func_nid)
354413
add_edge(file_nid, func_nid, "contains", line)
355414
emit_go_method_refs(node, func_nid, line)
356415
body = node.child_by_field_name("body")
357416
if body:
358-
function_bodies.append((func_nid, body))
417+
function_bodies.append((func_nid, body, None))
359418
return
360419

361420
if t == "method_declaration":
362421
receiver = node.child_by_field_name("receiver")
363422
receiver_type: str | None = None
423+
receiver_name: str | None = None
364424
if receiver:
365425
for param in receiver.children:
366426
if param.type == "parameter_declaration":
367427
type_node = param.child_by_field_name("type")
368428
if type_node:
369429
receiver_type = _read_text(type_node, source).lstrip("*").strip()
430+
name_node = param.child_by_field_name("name")
431+
if name_node:
432+
receiver_name = _read_text(name_node, source)
370433
break
371434
name_node = node.child_by_field_name("name")
372435
if not name_node:
@@ -377,18 +440,20 @@ def walk(node) -> None:
377440
if receiver_type:
378441
parent_nid = _make_id(pkg_scope, receiver_type)
379442
add_node(parent_nid, receiver_type, line)
443+
callable_class_nids.add(parent_nid)
380444
method_nid = symbol_nid(_make_id(parent_nid, method_name), method_name)
381445
add_node(method_nid, f".{method_name}()", line)
382446
add_edge(parent_nid, method_nid, "method", line)
383447
else:
384448
method_nid = symbol_nid(_make_id(stem, method_name), method_name)
385449
add_node(method_nid, f"{method_name}()", line)
386450
add_edge(file_nid, method_nid, "contains", line)
451+
callable_nids.add(method_nid)
387452

388453
emit_go_method_refs(node, method_nid, line)
389454
body = node.child_by_field_name("body")
390455
if body:
391-
function_bodies.append((method_nid, body))
456+
function_bodies.append((method_nid, body, receiver_name))
392457
return
393458

394459
if t == "type_declaration":
@@ -402,6 +467,7 @@ def walk(node) -> None:
402467
line = child.start_point[0] + 1
403468
type_nid = _make_id(pkg_scope, type_name)
404469
add_node(type_nid, type_name, line)
470+
callable_class_nids.add(type_nid)
405471
add_edge(file_nid, type_nid, "contains", line)
406472
# A generic type's own parameters (`type Box[T any]`) are local
407473
# bindings; a field or method using `T` must not mint a stub.
@@ -533,6 +599,16 @@ def walk(node) -> None:
533599
_scan_declarations(root)
534600
walk(root)
535601

602+
# A type carries both markers, as in the tree-sitter engine: `_callable_class` is
603+
# the narrowing, not a separate kind.
604+
for n in nodes:
605+
if n["id"] in callable_nids or n["id"] in callable_class_nids:
606+
n["_callable"] = True
607+
if n["id"] in callable_class_nids:
608+
n["_callable_class"] = True
609+
610+
type_table = _go_receiver_type_table(root, source)
611+
536612
label_to_nid: dict[str, str] = {}
537613
for n in nodes:
538614
raw = n["label"]
@@ -542,7 +618,7 @@ def walk(node) -> None:
542618
seen_call_pairs: set[tuple[str, str]] = set()
543619
raw_calls: list[dict] = []
544620

545-
def walk_calls(node, caller_nid: str) -> None:
621+
def walk_calls(node, caller_nid: str, self_name: str | None) -> None:
546622
if node.type in ("function_declaration", "method_declaration"):
547623
return
548624
if node.type == "call_expression":
@@ -551,6 +627,7 @@ def walk_calls(node, caller_nid: str) -> None:
551627
is_member_call: bool = False
552628
is_bare_identifier: bool = False
553629
package_receiver: str | None = None
630+
member_receiver: str | None = None
554631
import_path: str | None = None
555632
if func_node:
556633
if func_node.type == "identifier":
@@ -566,6 +643,17 @@ def walk_calls(node, caller_nid: str) -> None:
566643
if not is_member_call:
567644
package_receiver = receiver_name
568645
import_path = go_imported_pkgs[receiver_name]
646+
elif operand is not None and operand.type == "identifier":
647+
member_receiver = receiver_name
648+
elif operand is not None and operand.type == "selector_expression":
649+
# `s.logger.Log()` names the receiver by the field only when `s` is
650+
# this method's own receiver; any other head could be a package or
651+
# a variable whose type the flat table does not know.
652+
inner = operand.child_by_field_name("operand")
653+
if (self_name and inner is not None and inner.type == "identifier"
654+
and _read_text(inner, source) == self_name):
655+
member_receiver = _read_text(
656+
operand.child_by_field_name("field"), source)
569657
if field:
570658
callee_name = _read_text(field, source)
571659
if is_bare_identifier and callee_name in _GO_PREDECLARED_FUNCS:
@@ -599,15 +687,20 @@ def walk_calls(node, caller_nid: str) -> None:
599687
"is_member_call": is_member_call,
600688
"language": "go",
601689
"receiver": package_receiver,
690+
# A key of its own: `receiver` means "imported package" here, and
691+
# the Swift/Python/Ruby member-call resolvers select on
692+
# `is_member_call` plus `receiver` without checking the language,
693+
# so a Go name placed there binds to their types in a mixed corpus.
694+
"member_receiver": member_receiver,
602695
"import_path": import_path,
603696
"source_file": str_path,
604697
"source_location": f"L{node.start_point[0] + 1}",
605698
})
606699
for child in node.children:
607-
walk_calls(child, caller_nid)
700+
walk_calls(child, caller_nid, self_name)
608701

609-
for caller_nid, body_node in function_bodies:
610-
walk_calls(body_node, caller_nid)
702+
for caller_nid, body_node, self_name in function_bodies:
703+
walk_calls(body_node, caller_nid, self_name)
611704

612705
valid_ids = seen_ids
613706
clean_edges = []
@@ -621,4 +714,5 @@ def walk_calls(node, caller_nid: str) -> None:
621714
"edges": clean_edges,
622715
"raw_calls": raw_calls,
623716
"go_imports": dict(go_imported_pkgs),
717+
"go_type_table": {"path": str_path, "table": type_table},
624718
}

0 commit comments

Comments
 (0)