Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(go): bind calls through interface-typed variables to interface method specs (#3850)
Aman0d6df6e335d1
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.pyindex 212896979..c4bc7756f 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py@@ -358,6 +358,10 @@ class ReceiverTypingMixin(found = self._typed_receiver_lookup(file_path, call, caller_id, bare, type_name)if found is None and self._strategies_for(file_path).inherited_typed_receiver:return self._inherited_typed_target(file_path, call, caller_id, bare)+ if found is None and self._language_of(file_path) == "go":+ promoted = self._go_embedded_method(file_path, bare, call.target_name)+ if promoted is not None and promoted[1] != caller_id:+ return promoted[1], "import"return founddef _typed_receiver_lookup(diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/go.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/go.pyindex 76a356998..ce0e75b86 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/go.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/go.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport posixpath+from ..languages.go_interface_satisfaction import go_embedded_interfacesfrom ..models import Symbolfrom ..return_types import declared_return_type, go_first_resultfrom ..type_names import bare_type_name@@ -56,3 +57,76 @@ class GoReturnTypes:if posixpath.dirname(path) == package]return found[0] if len(found) == 1 else None+++ def _go_embedded_method(+ self, file_path: str, type_name: str, method_name: str+ ) -> tuple[str, str] | None:+ """Resolve a method promoted through a repository-defined Go interface embed."""+ type_id = self._go_visible_interface(file_path, type_name)+ if type_id is None:+ return None+ return self._embedded_interface_method(type_id, method_name, set(), 0)++ def _go_visible_interface(self, file_path: str, name: str) -> str | None:+ """The unique repository Go interface named *name* visible to this file."""+ parsed = self._parsed_files.get(file_path)+ visible = {posixpath.dirname(file_path)}+ for imp in parsed.imports if parsed else ():+ if imp.resolved_file and not imp.resolved_file.startswith("external:"):+ visible.add(posixpath.dirname(imp.resolved_file))+ ids = {+ identity[0]+ for path, identity, _ in self._declared_types_named(name)+ if posixpath.dirname(path) in visible+ and self._symbols_by_id[identity[0]].kind == "interface"+ and self._symbols_by_id[identity[0]].language == "go"+ }+ return next(iter(ids)) if len(ids) == 1 else None++ def _embedded_interface_method(+ self, type_id: str, method_name: str, seen: set[str], depth: int+ ) -> tuple[str, str] | None:+ """Walk embedded interfaces for a method, stopping on cycles or excessive depth."""+ if type_id in seen or depth > 6:+ return None+ seen.add(type_id)+ symbol = self._symbols_by_id[type_id]+ path = self._symbol_paths_by_id[type_id]+ lines = self._lines_of(path)[symbol.start_line - 1 : symbol.end_line]+ embeds = go_embedded_interfaces("\n".join(lines))+ if not embeds:+ return None++ package = posixpath.dirname(path)+ parsed = self._parsed_files.get(path)+ for qualifier, name in embeds:+ target_package = package+ if qualifier is not None:+ target_package = None+ for imp in parsed.imports if parsed else ():+ if qualifier in imp.local_names and imp.resolved_file:+ if not imp.resolved_file.startswith("external:"):+ target_package = posixpath.dirname(imp.resolved_file)+ break+ if target_package is None:+ continue++ ids = {+ identity[0]+ for p, identity, _ in self._declared_types_named(name)+ if posixpath.dirname(p) == target_package+ and self._symbols_by_id[identity[0]].kind == "interface"+ }+ if len(ids) != 1:+ continue++ embedded_id = next(iter(ids))+ hit = self._package_method(embedded_id, method_name)+ if hit is None:+ hit = self._embedded_interface_method(+ embedded_id, method_name, seen, depth + 1+ )+ if hit is not None:+ return hit+ return Nonediff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 9fa4c4a81..27319f655 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -509,7 +509,13 @@ class CallResolver(index_id = representatives.get(sym.id, sym.id)decl_key = (sym.parent_name, sym.name)if sym.is_declaration:- declarations.append((path, index_id, decl_key))+ # A Go interface method spec is not a prototype: its body is+ # never defined, and the structural implementers that carry one+ # differ from the interface by name or package. Pairing on+ # ``(parent, name)`` would redirect the spec onto an unrelated+ # type's method, so it stays unlinked.+ if sym.language != "go":+ declarations.append((path, index_id, decl_key))else:definitions[decl_key].append((path, index_id))_index_bare_name(sym, index_id, file_syms, top_level)@@ -1696,9 +1702,30 @@ class CallResolver(# Every strategy below ends in a lookup keyed on the method name, so a# name the repo declares nowhere cannot resolve.- if method_name not in self._global_symbols:+ # A Go interface method spec is bodiless, so ``_global_symbols`` leaves it+ # out; the method index holds it, and it is what an interface-typed+ # receiver binds to.+ if method_name not in self._global_symbols and not (+ self._language_of(file_path) == "go" and method_name in self._method_names()+ ):return False, None+ # A Go local, parameter or ``var`` the body declares is read through its+ # declared type, never as a type name: ``reader.Peek()`` on a+ # ``reader text.Reader`` is the interface's method, not the unexported+ # struct ``reader``'s. Go has no method call on a type name outside a+ # method expression, so the variable reading is the right one.+ if self._go_receiver_is_variable(file_path, call, caller_id):+ hit = self._first_strategy_hit(+ self._strategies_for(file_path).member, file_path, call, caller_id+ )+ if hit is not None:+ return True, hit+ hit = self._unclassed_receiver_call(file_path, call, caller_id)+ if hit is None and self._receiver_type_is_external(file_path, call, caller_id):+ return True, None+ return hit is not None, hit+# The caller's own file first, ahead of the language strategies: a# private inner class here outranks a same-named package sibling.own_file = self._file_methods.get(file_path, {}).get((receiver_name, method_name))@@ -1727,6 +1754,13 @@ class CallResolver(return True, Nonereturn hit is not None, hit+ def _go_receiver_is_variable(self, file_path: str, call: CallSite, caller_id: str) -> bool:+ """Whether a Go call's receiver is a typed local, parameter or ``var`` of the caller."""+ receiver_name = call.receiver_name or ""+ if "." in receiver_name or self._language_of(file_path) != "go":+ return False+ return receiver_name in self._declared_types_in(file_path, caller_id, "go")+def _unclassed_receiver_call(self,file_path: str,diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 168ed6ac8..8e26e44c0 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -188,6 +188,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {symbol_node_types={"function_declaration": "function","method_declaration": "method",+ "method_elem": "method", # interface method spec; bodiless"type_spec": "struct", # refined in post-processing"const_spec": "variable", # const MaxRetries = 3"var_spec": "variable", # var ErrNotFound = errors.New(...)@@ -197,6 +198,9 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {visibility_fn=go_visibility,parent_extraction="receiver",parent_class_types=frozenset(),+ # An interface method spec promises a body it does not carry; keep it+ # out of the definition indexes, as Rust trait signatures are.+ declaration_node_types=frozenset({"method_elem"}),),"rust": LanguageConfig(import_extractor=RUST_IMPORTS,diff --git a/packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.py b/packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.pyindex f82ee54ee..8e3a002bc 100644--- a/packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.py+++ b/packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.py@@ -50,6 +50,7 @@ from typing import TYPE_CHECKING, Anyimport structlogfrom ..heritage_resolver import heritage_ancestors+from ..type_names import bare_type_name, type_qualifierif TYPE_CHECKING:import networkx as nx@@ -126,7 +127,7 @@ def _interface_facts(iface_node: Node, src: bytes) -> tuple[set[str], list[str]]# method-bearing embeds.if "|" in text or "~" in text:continue- bare = text.split(".")[-1].strip()+ bare = bare_type_name(text)if bare and bare[0].isalpha():embedded.append(bare)return methods, embedded@@ -189,6 +190,45 @@ def _parse_go(src: bytes) -> Node | None:return Parser(lang).parse(src).root_node+def go_embedded_interfaces(type_source: str) -> list[tuple[str | None, str]]:+ """``(package qualifier, name)`` of each interface embedded in *type_source*.++ *type_source* is the text of one ``type X interface { ... }`` declaration.+ ``io.RuneReader`` yields ``("io", "RuneReader")`` and ``Base`` yields+ ``(None, "Base")``. Type-set constraints (``~int | string``) are skipped, as+ in ``_interface_facts``: they are generic bounds, not method-bearing embeds.+ """+ root = _parse_go(b"package p\n" + type_source.encode("utf-8"))+ if root is None:+ return []+ src = b"package p\n" + type_source.encode("utf-8")+ found: list[tuple[str | None, str]] = []++ def first_interface(node: Node) -> Node | None:+ if node.type == "interface_type":+ return node+ for child in node.children:+ hit = first_interface(child)+ if hit is not None:+ return hit+ return None++ iface = first_interface(root)+ if iface is None:+ return found+ for elem in iface.children:+ if elem.type != "type_elem":+ continue+ text = src[elem.start_byte : elem.end_byte].decode("utf-8", "ignore").strip()+ if "|" in text or "~" in text or "[" in text:+ continue+ qualifier = type_qualifier(text) or None+ name = bare_type_name(text)+ if name and name[0].isalpha():+ found.append((qualifier, name))+ return found++def resolve_go_interface_satisfaction(graph: nx.DiGraph, parsed_files: dict[str, Any]) -> int:diff --git a/packages/core/src/repowise/core/ingestion/parser/symbols.py b/packages/core/src/repowise/core/ingestion/parser/symbols.pyindex 13bb092b9..ca19b01cc 100644--- a/packages/core/src/repowise/core/ingestion/parser/symbols.py+++ b/packages/core/src/repowise/core/ingestion/parser/symbols.py@@ -345,6 +345,10 @@ def _symbol_from_match(capture_dict: dict, file: _SymbolPass) -> tuple[Symbol, Nexport_type_parents=file.cpp_exports.parents,)+ # Anonymous Go interface methods have no named owner and are not symbols.+ if node_type == "method_elem" and parent_name is None:+ return None+# A ``field_declaration`` cannot occur outside a class body, so a# missing parent means the class did not parse. Grammar recovery,# not a member function.@@ -527,6 +531,18 @@ def _resolve_parent_name(return None+def _go_interface_owner(def_node: Node, src: str) -> str | None:+ """Name of the interface type_spec that directly declares def_node."""+ iface = def_node.parent+ if iface is None or iface.type != "interface_type":+ return None+ spec = iface.parent+ if spec is None or spec.type != "type_spec":+ return None+ name = spec.child_by_field_name("name")+ return _node_text(name, src).strip() if name is not None else None++def _find_parent(def_node: Node,config: LanguageConfig,@@ -535,6 +551,9 @@ def _find_parent() -> str | None:"""Determine the parent class/type for a symbol."""if config.parent_extraction == "receiver":+ # Go interface methods belong to their named interface declaration.+ if def_node.type == "method_elem":+ return _go_interface_owner(def_node, src)# Go: extract type name from receiver parameter listif receiver_nodes:return extract_go_receiver_type(_node_text(receiver_nodes[0], src))diff --git a/packages/core/src/repowise/core/ingestion/queries/go.scm b/packages/core/src/repowise/core/ingestion/queries/go.scmindex 966a47f28..0e530ea69 100644--- a/packages/core/src/repowise/core/ingestion/queries/go.scm+++ b/packages/core/src/repowise/core/ingestion/queries/go.scm@@ -26,6 +26,15 @@name: (type_identifier) @symbol.name) @symbol.def+; Interface method spec: type Reader interface { Peek() byte }+; A bodiless declaration parented by its interface (see parser._find_parent).+; Methods of an anonymous interface (a field or parameter type) have no named+; owner and are dropped there.+(method_elem+ name: (field_identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def+; Package-level const: const MaxRetries = 3(const_specname: (identifier) @symbol.namediff --git a/tests/unit/ingestion/test_go_extractors.py b/tests/unit/ingestion/test_go_extractors.pyindex 30309b7d2..679b6177c 100644--- a/tests/unit/ingestion/test_go_extractors.py+++ b/tests/unit/ingestion/test_go_extractors.py@@ -40,6 +40,49 @@ class TestGoSymbols:assert "Hello" in names+class TestGoInterfaceMethodSpecs:+ """A ``method_elem`` of a named interface is a bodiless method symbol."""++ _SRC = (+ b"package x\n\n"+ b"type Base interface{ Close() error }\n\n"+ b"type Reader interface {\n"+ b"\tBase\n"+ b"\tPeek() byte\n"+ b"\tAdvance(n int)\n"+ b"}\n"+ )++ def test_each_method_is_a_symbol_parented_by_the_interface(self, parser: ASTParser) -> None:+ result = parser.parse_file(_file("x/reader.go"), self._SRC)+ specs = {s.id: s for s in result.symbols if s.parent_name == "Reader"}+ assert set(specs) == {"x/reader.go::Reader::Peek", "x/reader.go::Reader::Advance"}+ for spec in specs.values():+ assert spec.kind == "method"+ assert spec.is_declaration++ def test_an_embedded_interface_is_not_a_method_symbol(self, parser: ASTParser) -> None:+ result = parser.parse_file(_file("x/reader.go"), self._SRC)+ assert not any(s.name == "Base" and s.kind == "method" for s in result.symbols)+ assert not any(s.parent_name == "Reader" and s.name == "Base" for s in result.symbols)++ def test_the_interface_itself_is_unchanged(self, parser: ASTParser) -> None:+ result = parser.parse_file(_file("x/reader.go"), self._SRC)+ iface = next(s for s in result.symbols if s.id == "x/reader.go::Reader")+ assert iface.kind == "interface"++ def test_an_anonymous_interface_declares_no_symbol(self, parser: ASTParser) -> None:+ src = (+ b"package x\n\n"+ b"type Holder struct{ v interface{ Foo() } }\n\n"+ b"func take(a interface{ Bar() }) {}\n\n"+ b"func local() { type L interface{ Baz() } }\n"+ )+ result = parser.parse_file(_file(), src)+ names = {s.name for s in result.symbols}+ assert not names & {"Foo", "Bar", "Baz"}++class TestGoHeritage:def test_struct_embedding(self, parser: ASTParser) -> None:src = b"package x\n\ntype Base struct{}\n\ntype Foo struct {\n Base\n Name string\n}\n"diff --git a/tests/unit/ingestion/test_go_resolver.py b/tests/unit/ingestion/test_go_resolver.pyindex 0e319cf62..76c59f25d 100644--- a/tests/unit/ingestion/test_go_resolver.py+++ b/tests/unit/ingestion/test_go_resolver.py@@ -2,10 +2,14 @@from __future__ import annotations+from datetime import datetimefrom pathlib import Pathimport networkx as nx+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParserfrom repowise.core.ingestion.resolvers.context import ResolverContextfrom repowise.core.ingestion.resolvers.go import (read_go_modules,@@ -136,3 +140,139 @@ class TestLegacyModulePathFallback:# ...but it is not a real module, so nothing counts as exported.assert index.modules == ()assert exported_go_files(index) == []+++# ---------------------------------------------------------------------------+# Calls through an interface-typed variable+# ---------------------------------------------------------------------------++_IFACE_SOURCES: dict[str, str] = {+ "go.mod": "module example.com/md\n\ngo 1.22\n",+ "text/reader.go": (+ "package text\n\n"+ 'import "io"\n\n'+ "type Base interface{ Close() error }\n\n"+ "type Reader interface {\n\tio.RuneReader\n\tBase\n\tPeek() byte\n\tAdvance(n int)\n}\n\n"+ "type reader struct{ src []byte; pos int }\n\n"+ "func (r *reader) Peek() byte { return r.src[r.pos] }\n"+ "func (r *reader) Advance(n int) { r.pos += n }\n\n"+ "func NewReader(src []byte) Reader { return &reader{src: src} }\n"+ ),+ "text/block.go": (+ "package text\n\n"+ "type blockReader struct{ pos int }\n\n"+ "func (b *blockReader) Peek() byte { return 0 }\n"+ "func (b *blockReader) Advance(n int) { b.pos += n }\n"+ ),+ "parser/parser.go": (+ "package parser\n\n"+ 'import "example.com/md/text"\n\n'+ "func parseParam(reader text.Reader) byte {\n\treader.Advance(1)\n\treturn reader.Peek()\n}\n\n"+ "func parseVar(src []byte) byte {\n"+ "\tvar reader text.Reader = text.NewReader(src)\n\treturn reader.Peek()\n}\n\n"+ "func parseOther(r text.Reader) byte { return r.Peek() }\n\n"+ "func promotedInRepo(r text.Reader) error { return r.Close() }\n\n"+ "func promotedExternal(r text.Reader) { r.ReadRune() }\n"+ ),+}+++def _call_edges(repo: Path, sources: dict[str, str]) -> set[tuple[str, str]]:+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for rel, body in sources.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ for rel in sources:+ if not rel.endswith(".go"):+ continue+ info = FileInfo(+ path=rel,+ abs_path=str((repo / rel).resolve()),+ language="go",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ builder.add_file(parser.parse_file(info, (repo / rel).read_bytes()))+ graph = builder.build()+ return {+ (u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"+ }+++class TestInterfaceTypedReceiverCalls:+ def test_a_parameter_named_like_a_struct_binds_to_the_interface(self, tmp_path: Path) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ caller = "parser/parser.go::parseParam"+ assert (caller, "text/reader.go::Reader::Peek") in edges+ assert (caller, "text/reader.go::Reader::Advance") in edges++ def test_a_var_named_like_a_struct_binds_to_the_interface(self, tmp_path: Path) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ assert ("parser/parser.go::parseVar", "text/reader.go::Reader::Peek") in edges++ def test_an_interface_variable_with_any_other_name_binds_to_the_interface(+ self, tmp_path: Path+ ) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ assert ("parser/parser.go::parseOther", "text/reader.go::Reader::Peek") in edges++ def test_no_call_binds_to_an_implementer(self, tmp_path: Path) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ for caller, callee in edges:+ if caller.startswith("parser/parser.go::"):+ assert "::reader::" not in callee, (caller, callee)+ assert "::blockReader::" not in callee, (caller, callee)++ def test_a_method_promoted_from_an_in_repo_embedded_interface_binds_its_spec(+ self, tmp_path: Path+ ) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ assert ("parser/parser.go::promotedInRepo", "text/reader.go::Base::Close") in edges++ def test_a_method_promoted_from_an_external_interface_binds_nothing(+ self, tmp_path: Path+ ) -> None:+ edges = _call_edges(tmp_path, _IFACE_SOURCES)+ assert not {e for e in edges if e[0] == "parser/parser.go::promotedExternal"}++ def test_a_concrete_receiver_still_binds_to_its_own_method(self, tmp_path: Path) -> None:+ sources = dict(_IFACE_SOURCES)+ sources["parser/concrete.go"] = (+ "package parser\n\n"+ 'import "example.com/md/text"\n\n'+ "func viaStruct(reader *text.Impl) byte { return reader.Peek() }\n"+ )+ sources["text/impl.go"] = (+ "package text\n\ntype Impl struct{}\n\nfunc (i *Impl) Peek() byte { return 0 }\n"+ )+ edges = _call_edges(tmp_path, sources)+ assert ("parser/concrete.go::viaStruct", "text/impl.go::Impl::Peek") in edges++ def test_a_spec_is_not_paired_with_a_same_named_type_in_another_package(+ self, tmp_path: Path+ ) -> None:+ sources = {+ "go.mod": "module example.com/app\n\ngo 1.22\n",+ "detect/store.go": (+ "package detect\n\ntype Store interface{ Save() int }\n\n"+ "func Open() Store { return nil }\n"+ ),+ "other/store.go": (+ "package other\n\ntype Store struct{}\n\n"+ "func (s *Store) Save() int { return 1 }\n"+ ),+ "cmd/run.go": (+ 'package cmd\n\nimport "example.com/app/detect"\n\n'+ "func run() {\n\ts := detect.Open()\n\ts.Save()\n}\n"+ ),+ }+ edges = _call_edges(tmp_path, sources)+ assert ("cmd/run.go::run", "detect/store.go::Store::Save") in edges+ assert ("cmd/run.go::run", "other/store.go::Store::Save") not in edgesdiff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.pyindex 0e9d1ebe7..0d15010ee 100644--- a/tests/unit/test_no_bare_type_name_copies.py+++ b/tests/unit/test_no_bare_type_name_copies.py@@ -132,7 +132,6 @@ _KNOWN: dict[str, int] = {_PREFIX + "framework_edges/micronaut.py": 2,_PREFIX + "framework_edges/spring.py": 4,_PREFIX + "parser_helpers.py": 1,- _PREFIX + "languages/go_interface_satisfaction.py": 1,}# Builtin-type lists are language identity data and belong on the spec beside