Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat: bring Go indexing to C#/Rust parity (#267)

Raghav Chamadiya3d6f2260b6ef
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index ba65bb7eb..3e2c834ce 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -39,7 +39,7 @@ call resolution, named bindings, heritage extraction, and docstrings.
| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `export { x } from 'y'` & `export * from 'y'` re-export barrels / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |
| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` |
| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` |
-| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match) |
+| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match); a package import fans out to **all** `.go` files in the package directory |
| **Rust** | `.rs` | `main.rs` `lib.rs` | `use crate::` / `use super::` / `use self::` with `Cargo.toml` |
| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `main.cpp` `main.cc` | `#include` with `compile_commands.json` resolution |
| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using Acme.Domain` / `global using` / `using static` / `using Alias = X.Y.Z` with `.csproj` / `.sln` / `Directory.Build.props` resolution |
@@ -50,9 +50,10 @@ All eight languages support:
- Named binding extraction (mapping imported names to source symbols)
- Heritage extraction (class/interface/trait/record inheritance chains)
- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)
-- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)
-- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)
+- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router + stdlib `net/http` (`http.HandleFunc` / `mux.Handle`) + gRPC `RegisterXxxServer` → handler/impl files for Go; Axum/Actix `.route` → handler files for Rust)
+- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`)
- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields → PascalCase property, `[RelayCommand]` methods → `<Name>Command`)
+- For Go only: a package-granular workspace index (`GoPackageIndex`) built as a warmup phase — a package import resolves to every file in the package directory, and package-qualified calls (`pkg.Func`) / same-package bare calls resolve across all of a package's files; type-reference resolution emits `type_use` edges for field / parameter / return / composite-literal types (unwrapping `*T` / `[]T` / `map[K]V` / `pkg.T` / generics); package-aware dead-code reachability (a file is reachable when its package is imported or is a `package main` entry); structural interface satisfaction — concrete types are matched to the interfaces their method set satisfies (embedded interfaces expanded) and emit `method_implements` edges so interfaces reached only through implementors are not flagged dead; and Go never-flag conventions (`*_test.go`, `cmd/**/main.go`, `doc.go`, `magefile.go`, generated `*.pb.go` / `*_string.go` / `zz_generated*` / `bindata.go`) plus `init` / `TestMain` / `Test*` / `Benchmark*` / `Example*` / `Fuzz*` entry handling
- For C/C++ only: visibility tracked from access specifiers (`public:` / `private:` / `protected:`), `static` file-scope storage class, and export attributes (`__declspec(dllexport)`, `__attribute__((visibility("default")))`); COM / I-prefixed bases emit `implements` edges (rest are `extends`); Windows DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`) are never flagged as dead
- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml→xaml `dynamic_uses` edges
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 84da5eaf5..a3aeb0948 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -28,6 +28,7 @@ from .constants import (
_is_fixture_path,
)
from .contract_methods import is_contract_method
+from .go_reachability import build_go_package_files, is_go_file_reachable
# Symbol kinds that cannot be independently imported by name in any
# supported language. Flagging them as "unused exports" is a guaranteed
@@ -84,11 +85,32 @@ def _non_importable_kinds(language: str) -> frozenset[str]:
# New code should prefer ``_non_importable_kinds(language)``.
_NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = _UNIVERSAL_NON_IMPORTABLE | frozenset({"interface"})
+# Aggregate *type* kinds that are never call targets. The unused-internal
+# pass is a call-graph check ("private symbol with no incoming CALL edges"),
+# which is meaningful for functions/methods but not for types: a struct or
+# interface used only as a field/parameter/return type — especially within
+# its own file — has no call edge and no observable symbol-level type edge,
+# so "no callers" is not evidence of deadness. Such types are still subject
+# to the *unused-export* pass (which reasons over import names / type_use),
+# so genuinely-dead exported types are still surfaced there.
+_UNCALLABLE_TYPE_KINDS: frozenset[str] = frozenset({
+ "struct",
+ "interface",
+ "enum",
+ "type_alias",
+})
+
# Symbol names that are language-runtime entry points or compiler-implicit
# anchors — never invoked by user-authored callers, never dead.
_ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
"Main", # C#, Java, Kotlin, Go, Rust, Swift, Scala
"main", # most others
+ # ---- Go runtime / test conventions ------------------------------
+ # ``func init`` is run by the Go runtime when the package is linked —
+ # never called by name, so it has no inbound call edge. ``TestMain``
+ # is the test-binary entry the ``go test`` runner invokes by reflection.
+ "init",
+ "TestMain",
"MauiProgram", # .NET MAUI
"Program", # C# top-level / classic console
"Startup", # ASP.NET Core legacy
@@ -200,6 +222,15 @@ class DeadCodeAnalyzer:
self._dynamic_import_files = find_dynamic_import_files(
parsed_files or {}
) | find_dynamic_edge_files(graph)
+ # Lazily-built ``.go`` package-directory → file-node map, used by the
+ # Go package-granular reachability hook (see ``go_reachability``).
+ self._go_package_files: dict[str, list[str]] | None = None
+
+ def _go_packages(self) -> dict[str, list[str]]:
+ """Return the cached Go package map, building it on first use."""
+ if self._go_package_files is None:
+ self._go_package_files = build_go_package_files(self.graph)
+ return self._go_package_files
def analyze(
self,
@@ -342,8 +373,14 @@ class DeadCodeAnalyzer:
if self._is_api_contract(node_data):
continue
- in_deg = self.graph.in_degree(node)
- if in_deg > 0:
+ # Go reachability is package-granular: a file with no direct
+ # importer can still be live (entry-package sibling next to
+ # main.go, or a package whose siblings carry the import). Delegate
+ # to the Go helper instead of the raw file-level in_degree check.
+ if str(node).endswith(".go"):
+ if is_go_file_reachable(str(node), self.graph, self._go_packages()):
+ continue
+ elif self.graph.in_degree(node) > 0:
continue
finding = self._make_unreachable_finding(str(node), node_data, dynamic_patterns)
@@ -457,9 +494,21 @@ class DeadCodeAnalyzer:
# via ``cargo.<attr>`` and we cannot tell statically which
# attribute is being called. Treat all public symbols as live.
# Generic across Python and TS/JS — no repo-specific assumptions.
+ #
+ # Excluded for Go: every Go import names the *package*, and a
+ # file commonly shares its package's name (``dynacache.go`` in
+ # package ``dynacache``), which would blanket-rescue every public
+ # symbol in such files. Go package-qualified calls are now
+ # resolved precisely (call_resolver._resolve_go_package_call), so
+ # the imprecise namespace rescue is both unnecessary and harmful
+ # here — it would hide genuinely dead exports.
file_stem = Path(str(node)).stem
file_imported_as_namespace = False
- if file_stem and file_stem not in ("__init__", "index"):
+ if (
+ file_stem
+ and file_stem not in ("__init__", "index")
+ and node_data.get("language") != "go"
+ ):
for pred in self.graph.predecessors(node):
edge = self.graph.get_edge_data(pred, node, {})
if edge.get("edge_type") != "imports":
@@ -681,6 +730,11 @@ class DeadCodeAnalyzer:
# Skip the entire language until call-edge support lands.
if node_data.get("language") == "rust":
continue
+ # Go's call resolver now resolves same-package (sibling-file) and
+ # package-qualified calls (see call_resolver._resolve_go_*), so
+ # private symbols used across a package's files carry real
+ # ``calls`` edges and no longer read as universally uncalled. The
+ # blanket exemption that Phase 2 added has been lifted.
if node_data.get("visibility") not in ("private", "internal"):
continue
file_path = node_data.get("file_path", "")
@@ -705,6 +759,11 @@ class DeadCodeAnalyzer:
continue
if node_data.get("kind") in _non_importable_kinds(node_data.get("language", "unknown")):
continue
+ # Non-callable type kinds can't have CALL edges; the call-graph
+ # check this pass performs is meaningless for them (see
+ # _UNCALLABLE_TYPE_KINDS). They remain covered by unused_export.
+ if node_data.get("kind") in _UNCALLABLE_TYPE_KINDS:
+ continue
if is_contract_method(
sym_name, node_data.get("kind"), node_data.get("language", "unknown")
):
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index ffd97a5dc..7ae1e8406 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -212,6 +212,38 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"**/generated/**/*.rs",
# Protocol buffer generated code
"**/proto/**/*.rs",
+ # ---- Go conventions --------------------------------------------------
+ # ``fnmatch`` does not treat ``/`` specially, so a leading ``*`` already
+ # spans directory separators; the ``*/`` + bare pairs below match both
+ # nested and repo-root locations.
+ # Test files are compiled and run by ``go test`` via the runner, never
+ # imported by other packages.
+ "*_test.go",
+ # ``package main`` entry points — invoked by the Go toolchain / OS, never
+ # imported. Covers ``cmd/<name>/main.go`` and a repo-root ``main.go``.
+ "*/main.go",
+ "main.go",
+ # Package documentation stubs (the ``doc.go`` / ``docs.go`` convention):
+ # a file holding only the package-level doc comment, frequently the sole
+ # file in an aggregating directory, so it has no importer by design.
+ "*/doc.go",
+ "doc.go",
+ "*/docs.go",
+ "docs.go",
+ # Mage build files (``//go:build mage``, ``package main``) — run by the
+ # ``mage`` tool, excluded from normal builds, never imported.
+ "*/magefile.go",
+ "magefile.go",
+ # Generated code: stringer (``*_string.go``), protobuf (``*.pb.go``),
+ # gRPC (``*_grpc.pb.go``), go-bindata (``*bindata.go``), and the
+ # Kubernetes ``zz_generated*`` / generic ``*_gen.go`` / ``*.gen.go``
+ # conventions. Wired in at build time, no static importer.
+ "*.gen.go",
+ "*_gen.go",
+ "*.pb.go",
+ "*_string.go",
+ "*zz_generated*.go",
+ "*bindata.go",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index 7bfb1de77..f49e66cd7 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -61,6 +61,16 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
"reflect.New(",
"reflect.TypeOf(",
"reflect.ValueOf(",
+ # Compiler / linker directives. Files that drive code generation
+ # (``//go:generate``), embed assets (``//go:embed``), or link to a
+ # symbol defined elsewhere (``//go:linkname``) participate in the
+ # build outside the import graph — treat their package as dynamic.
+ # (Struct tags like ``json:"…"`` were considered but rejected: they
+ # appear in nearly every Go file, so they are too broad to be a
+ # useful dynamic signal.)
+ "//go:generate",
+ "//go:embed",
+ "//go:linkname",
),
".swift": (
"NSClassFromString(",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py
new file mode 100644
index 000000000..11de7fe78
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/go_reachability.py
@@ -0,0 +1,76 @@
+"""Package-granular reachability for Go.
+
+Go's unit of compilation is the *package* (a directory of ``.go`` files
+sharing a ``package X`` clause), not the file. The generic unreachable-file
+pass treats ``in_degree == 0`` as dead, which mis-flags two Go-specific
+shapes the file-level view cannot see:
+
+- **Entry-package siblings.** ``cmd/foo/main.go`` is an entry point, but the
+ helper files next to it (``cmd/foo/server.go`` …) are never *imported* —
+ they are compiled into the ``package main`` binary alongside ``main.go``.
+ File-level reachability flags them; package-level reachability does not.
+- **Belt-and-suspenders for a partially-linked package.** Phase 1's import
+ fan-out gives every file in an imported package an inbound edge, so an
+ imported package is normally all-or-nothing. If any sibling still carries
+ an importer, the whole package is live.
+
+``func init`` deliberately does **not** rescue a package here: ``init`` runs
+only when the package is *linked*, which requires the package to be imported
+(or to be ``package main``). An otherwise-unimported package whose only
+signal is ``func init`` is genuinely dead, so we let it surface.
+
+The helper derives packages from the graph itself (``.go`` file nodes grouped
+by parent directory) — the ``GoPackageIndex`` built during ingestion is not
+threaded into the analyzer, and the directory grouping is all reachability
+needs.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from typing import Any
+
+
+def _pkg_dir(node: str) -> str:
+ """Repo-relative POSIX directory of a ``.go`` file ("" = repo root)."""
+ parent = PurePosixPath(node).parent.as_posix()
+ return "" if parent == "." else parent
+
+
+def build_go_package_files(graph: Any) -> dict[str, list[str]]:
+ """Group every ``.go`` file node in *graph* by its package directory."""
+ packages: dict[str, list[str]] = {}
+ for node in graph.nodes():
+ s = str(node)
+ if not s.endswith(".go"):
+ continue
+ packages.setdefault(_pkg_dir(s), []).append(s)
+ return packages
+
+
+def is_go_file_reachable(
+ node: str,
+ graph: Any,
+ package_files: dict[str, list[str]],
+) -> bool:
+ """Return True if a Go file is reachable at *package* granularity.
+
+ Called from the analyzer only for ``.go`` nodes that already survived the
+ generic skips (entry point, test, never-flag) and have ``in_degree == 0``.
+ A file is reachable when any sibling in its package is imported from
+ outside the package, or when any sibling is an entry-point file (the
+ package is an entry ``package main``). See the module docstring for the
+ ``func init`` rationale.
+ """
+ if graph.in_degree(node) > 0:
+ return True
+
+ for sibling in package_files.get(_pkg_dir(node), ()):
+ if sibling == node:
+ continue
+ if graph.in_degree(sibling) > 0:
+ return True
+ if graph.nodes.get(sibling, {}).get("is_entry_point", False):
+ return True
+
+ return False
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index b1adc8347..69610bc82 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -24,6 +24,7 @@ from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
+from typing import Any
import structlog
@@ -98,6 +99,12 @@ class CallResolver:
self._repo_path = repo_path
self._rust_crate_src: dict[str, str] | None = None # lazy
+ # Go package-scoped resolution (lazy GoPackageIndex). ``_go_index``
+ # holds the built index; ``_go_index_built`` distinguishes "not yet
+ # built" from "built but unavailable" (no repo_path / no go files).
+ self._go_index: Any = None
+ self._go_index_built = False
+
self._build_indices(parsed_files)
self._follow_barrel_exports()
@@ -166,6 +173,95 @@ class CallResolver:
self._rust_crate_src[normalized] = crate.src_dir
return self._rust_crate_src
+ def _get_go_index(self) -> Any:
+ """Lazily build the GoPackageIndex (or None if unavailable).
+
+ Mirrors ``_get_rust_crate_src``: the resolver runs without a
+ ``ResolverContext``, so it constructs a minimal stand-in and rebuilds
+ the package index. The build is one walk over the ``.go`` files; the
+ result is cached for the lifetime of the resolver.
+ """
+ if self._go_index_built:
+ return self._go_index
+ self._go_index_built = True
+ if not self._repo_path:
+ return None
+ from pathlib import Path
+
+ from .resolvers.go_workspace import build_go_package_index
+
+ class _Ctx:
+ def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:
+ self.repo_path = Path(rp)
+ self.path_set = set(pf.keys())
+ self.parsed_files = pf
+ self.go_modules: tuple[tuple[str, str], ...] = ()
+ self.go_module_path: str | None = None
+
+ self._go_index = build_go_package_index(_Ctx(self._repo_path, self._parsed_files))
+ return self._go_index
+
+ def _is_go(self, file_path: str) -> bool:
+ parsed = self._parsed_files.get(file_path)
+ return bool(parsed and parsed.file_info.language == "go")
+
+ def _resolve_go_package_call(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve ``pkg.Func()`` against *every* file in the package.
+
+ The legacy module-alias strategy resolves only against the single
+ representative file the import resolved to; a function defined in a
+ sibling file of that package is missed. Look it up across the whole
+ package directory via the GoPackageIndex.
+ """
+ index = self._get_go_index()
+ if index is None:
+ return None
+ module_file = self._module_aliases.get(file_path, {}).get(call.receiver_name)
+ if not module_file:
+ return None
+ pkg = index.package_for_file(module_file)
+ if pkg is None:
+ return None
+ for sibling in pkg.files:
+ syms = self._file_symbols.get(sibling, {})
+ sym_id = syms.get(call.target_name)
+ if sym_id is not None and sym_id != caller_id:
+ return ResolvedCall(caller_id, sym_id, 0.88, call.line)
+ return None
+
+ def _resolve_go_same_package(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve a bare call to a function defined in a sibling file.
+
+ Files in the same Go package share a namespace with no import
+ statement, so a bare ``Helper()`` may be defined in any sibling
+ file. Search the package directory (excluding the caller's own
+ file, already covered by the same-file tier).
+ """
+ index = self._get_go_index()
+ if index is None:
+ return None
+ pkg = index.package_for_file(file_path)
+ if pkg is None:
+ return None
+ for sibling in pkg.files:
+ if sibling == file_path:
+ continue
+ syms = self._file_symbols.get(sibling, {})
+ sym_id = syms.get(call.target_name)
+ if sym_id is not None and sym_id != caller_id:
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line)
+ return None
+
def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
"""Build all lookup indices from parsed file data."""
for path, parsed in parsed_files.items():
@@ -257,6 +353,14 @@ class CallResolver:
if callee_id != caller_id: # no self-recursion edges for now
return ResolvedCall(caller_id, callee_id, 0.95, call.line)
+ # Go: a bare call may target a function defined in a sibling file of
+ # the same package (shared namespace, no import). Resolve against the
+ # package before the weaker import/global tiers.
+ if self._is_go(file_path):
+ go_same_pkg = self._resolve_go_same_package(file_path, call, caller_id)
+ if go_same_pkg is not None:
+ return go_same_pkg
+
# Tier 2: import-scoped
# 2a: Check specific imported name → source file (binding-aware)
binding = self._import_bindings.get(file_path, {}).get(target_name)
@@ -312,6 +416,15 @@ class CallResolver:
method_name = call.target_name
assert receiver_name is not None
+ # Go: ``pkg.Func()`` where ``pkg`` is an import alias resolves to the
+ # function in *any* file of that package, not just the single
+ # representative the import resolved to. Try this first for Go so a
+ # multi-file package's exported funcs are reached correctly.
+ if self._is_go(file_path):
+ go_pkg_call = self._resolve_go_package_call(file_path, call, caller_id)
+ if go_pkg_call is not None:
+ return go_pkg_call
+
# Strategy 1: receiver is a module alias (e.g. "import models" → "models.User()")
module_file = self._module_aliases.get(file_path, {}).get(receiver_name)
if module_file:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
index cf9cf0e79..64a5bd94a 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
@@ -9,8 +9,12 @@ from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"vendor", "node_modules", ".git", "bin"}
-# reflect.TypeOf(Foo{}) / reflect.New(reflect.TypeOf(Foo{}))
-_REFLECT_TYPEOF_RE = re.compile(r"reflect\.TypeOf\s*\(\s*([A-Za-z_]\w*)")
+# reflect.TypeOf(Foo{}) / reflect.New(Foo{}) / reflect.ValueOf(Foo{}) — and
+# the pointer-nil idiom reflect.TypeOf((*Foo)(nil)). Capture the bare or
+# package-qualified type/value head; the qualifier is dropped at resolve time.
+_REFLECT_USE_RE = re.compile(
+ r"reflect\.(?:TypeOf|New|ValueOf)\s*\(\s*(?:&|\(\s*\*)?\s*([A-Za-z_][\w.]*)"
+)
# plugin.Open("./plugin.so")
_PLUGIN_OPEN_RE = re.compile(r"plugin\.Open\s*\(\s*[\"']([^\"']+)[\"']")
# plugin.Lookup("Foo")
@@ -56,8 +60,12 @@ class GoDynamicHints(DynamicHintExtractor):
except ValueError:
continue
- for match in _REFLECT_TYPEOF_RE.finditer(text):
- target = type_to_file.get(match.group(1))
+ for match in _REFLECT_USE_RE.finditer(text):
+ # Drop any package qualifier (``pkg.Foo`` → ``Foo``); reflect
+ # arguments are values/types whose defining file we look up by
+ # bare name.
+ bare = match.group(1).split(".")[-1]
+ target = type_to_file.get(bare) or func_to_file.get(bare)
if target and target != rel:
edges.append(DynamicEdge(
source=rel, target=target,
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/go.py b/packages/core/src/repowise/core/ingestion/framework_edges/go.py
index e29b7a56d..e5d402d8a 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/go.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/go.py
@@ -1,6 +1,17 @@
-"""Gin / Echo / Chi (Go) router convention edges.
+"""Go web/RPC framework convention edges.
-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.
+Covers the route/handler wiring that carries no import edge:
+
+* **Router frameworks** — Gin / Echo / Chi ``r.GET("/path", handler)``.
+* **stdlib ``net/http``** — ``http.HandleFunc("/path", handler)`` and
+ ``mux.Handle("/path", handler)`` (same ``.HandleFunc`` / ``.Handle``
+ selector shape as the router frameworks, so one regex serves both —
+ the only difference is which import gates emission).
+* **gRPC** — ``pb.RegisterXxxServer(s, &impl{})`` connects the registration
+ site to the file defining the server implementation type.
+
+Split out of ``framework_edges.py`` (PR 3.5); net/http + gRPC added in the
+Go-parity work (Phase 4).
"""
from __future__ import annotations
@@ -27,28 +38,49 @@ _GO_ROUTER_PKG_PATTERNS = (
"github.com/labstack/echo",
"github.com/go-chi/chi",
)
+# stdlib net/http is gated separately: its handler-registration calls share
+# the ``.HandleFunc`` / ``.Handle`` selector shape with the router frameworks.
+_GO_HTTP_PKG = "net/http"
+
_GO_ROUTE_CALL_RE = re.compile(
r"\.\s*(?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|HandleFunc|Handle|Any)"
r"\s*\(\s*[\"'][^\"']*[\"']\s*,\s*([\w.]+)"
)
+# gRPC generated registration: ``pb.RegisterGreeterServer(s, &greeter{})`` or
+# ``RegisterGreeterServer(srv, impl)``. Capture the implementation argument
+# (the second positional arg); we resolve its leading type identifier.
+_GO_GRPC_REGISTER_RE = re.compile(
+ r"\bRegister\w+Server\s*\(\s*[\w.]+\s*,\s*&?\s*([A-Za-z_][\w.]*)"
+)
+
+
+def _imports_any(parsed: Any, *prefixes: str) -> bool:
+ return any(
+ imp.module_path.startswith(pkg) for pkg in prefixes for imp in parsed.imports
+ )
-def _has_go_router_imports(parsed_files: dict[str, Any]) -> bool:
+
+def _has_go_web_imports(parsed_files: dict[str, Any]) -> bool:
for parsed in parsed_files.values():
if parsed.file_info.language != "go":
continue
- for imp in parsed.imports:
- mp = imp.module_path
- if any(mp.startswith(pkg) for pkg in _GO_ROUTER_PKG_PATTERNS):
- return True
+ if _imports_any(parsed, *_GO_ROUTER_PKG_PATTERNS, _GO_HTTP_PKG):
+ return True
return False
-def _add_go_router_edges(
+def _add_go_route_edges(
graph: nx.DiGraph,
parsed_files: dict[str, Any],
path_set: set[str],
) -> int:
+ """Emit edges for router-framework + net/http handler registrations.
+
+ Only emit for files that themselves both reference a route call and
+ import a router or ``net/http`` — conservative, mirrors the original
+ router behaviour while admitting stdlib HTTP.
+ """
count = 0
func_to_files = _build_function_to_file(parsed_files, ("go",))
class_to_file = _build_class_to_file(parsed_files, ("go",))
@@ -56,18 +88,11 @@ def _add_go_router_edges(
for path, parsed in parsed_files.items():
if parsed.file_info.language != "go":
continue
+ if not _imports_any(parsed, *_GO_ROUTER_PKG_PATTERNS, _GO_HTTP_PKG):
+ continue
text = read_text(parsed)
if not text:
continue
- if not any(
- imp.module_path.startswith(pkg)
- for pkg in _GO_ROUTER_PKG_PATTERNS
- for imp in parsed.imports
- ):
- # Allow if some other go file in the repo imports a router (router
- # setup may be split across files); be conservative and only emit
- # edges for files that themselves reference router calls.
- pass
for m in _GO_ROUTE_CALL_RE.finditer(text):
handler = m.group(1)
@@ -79,13 +104,39 @@ def _add_go_router_edges(
return count
+def _add_go_grpc_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ """Connect ``RegisterXxxServer(s, &impl{})`` sites to the impl-type file."""
+ count = 0
+ func_to_files = _build_function_to_file(parsed_files, ("go",))
+ class_to_file = _build_class_to_file(parsed_files, ("go",))
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "go":
+ continue
+ text = read_text(parsed)
+ if not text or "Server(" not in text:
+ continue
+ for m in _GO_GRPC_REGISTER_RE.finditer(text):
+ impl = m.group(1)
+ targets = _resolve_go_handler(impl, parsed, func_to_files, class_to_file)
+ for target in targets:
+ if target != path and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
def _resolve_go_handler(
handler: str,
parsed: Any,
func_to_files: dict[str, list[str]],
class_to_file: dict[str, str],
) -> list[str]:
- """Resolve `pkg.Func` / `recv.Method` / `Func` to candidate file paths."""
+ """Resolve `pkg.Func` / `recv.Method` / `Func` / `Type` to file paths."""
if "." in handler:
prefix, name = handler.rsplit(".", 1)
# First: was prefix imported as a package?
@@ -107,13 +158,20 @@ def _resolve_go_handler(
return [type_file]
# Third: fall back to any file declaring the bare name
return list(func_to_files.get(name, []))
- return list(func_to_files.get(handler, []))
+ # Bare identifier: a function/method name, or a type (gRPC ``&impl{}``).
+ funcs = func_to_files.get(handler)
+ if funcs:
+ return list(funcs)
+ type_file = class_to_file.get(handler)
+ return [type_file] if type_file else []
-class _GoRouterHandler:
+class _GoWebHandler:
def detect(self, dctx: DetectionContext) -> bool:
- go_router_in_stack = any(token in dctx.stack_lower for token in ("gin", "echo", "chi"))
- return go_router_in_stack or _has_go_router_imports(dctx.parsed_files)
+ go_web_in_stack = any(
+ token in dctx.stack_lower for token in ("gin", "echo", "chi", "grpc")
+ )
+ return go_web_in_stack or _has_go_web_imports(dctx.parsed_files)
def add_edges(
self,
@@ -122,7 +180,9 @@ class _GoRouterHandler:
ctx: ResolverContext,
path_set: set[str],
) -> int:
- return _add_go_router_edges(graph, parsed_files, path_set)
+ count = _add_go_route_edges(graph, parsed_files, path_set)
+ count += _add_go_grpc_edges(graph, parsed_files, path_set)
+ return count
-HANDLERS: list[FrameworkHandler] = [_GoRouterHandler()]
+HANDLERS: list[FrameworkHandler] = [_GoWebHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index d33767ba1..b05804161 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -93,6 +93,40 @@ class ResolveMixin:
if callable(done):
done(phase)
+ def _resolve_go_interface_satisfaction(self, progress: Any | None = None) -> None:
+ """Emit ``method_implements`` edges for Go structural interface
+ satisfaction.
+
+ Go has no nominal ``implements`` clause, so interfaces reached only
+ through their concrete implementors look like unreferenced exports.
+ This pass connects each concrete type to the interfaces its method
+ set satisfies, landing a usage signal on the interface symbol. Runs
+ after heritage so the interface / type symbols already exist as nodes.
+ """
+ from ..languages.go_interface_satisfaction import (
+ resolve_go_interface_satisfaction,
+ )
+
+ has_go = any(
+ pf.file_info.language == "go" for pf in self._parsed_files.values()
+ )
+ if not has_go:
+ return
+
+ phase = "graph.go_interfaces"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ added = resolve_go_interface_satisfaction(self._graph, self._parsed_files)
+ log.info("interface_satisfaction_edges", language="go", added=added)
+ except Exception as exc:
+ log.warning("go_interface_satisfaction_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
def _resolve_calls(
self,
import_targets: dict[str, set[str]],
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index abedbfc96..a18dbcd00 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -232,9 +232,20 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
_t0 = _t.monotonic()
file_imports: set[str] = set()
for imp in parsed.imports:
- target = resolve_import(imp.module_path, path, parsed.file_info.language, ctx)
- if target:
- imp.resolved_file = target
+ # Go imports name a package *directory*; fan the edge out to
+ # every ``.go`` file in the resolved package so sibling files
+ # share importers (otherwise they look unreachable). Other
+ # languages resolve to a single representative target.
+ if _lang == "go":
+ from ..resolvers.go import resolve_go_import_all
+
+ targets = resolve_go_import_all(imp.module_path, path, ctx)
+ else:
+ single = resolve_import(imp.module_path, path, _lang, ctx)
+ targets = (single,) if single else ()
+ if targets:
+ imp.resolved_file = targets[0]
+ for target in targets:
file_imports.add(target)
# Aggregate imported_names on parallel edges
if self._graph.has_edge(path, target):
@@ -295,6 +306,12 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# --- Phase 2: Resolve heritage (extends/implements) ---
self._resolve_heritage(import_targets, progress=progress)
+ # --- Phase 2b: Resolve Go structural interface satisfaction ---
+ # Go has no `implements` keyword; connect concrete types to the
+ # interfaces their method set satisfies so interfaces reached only
+ # through implementors are not flagged as dead exports.
+ self._resolve_go_interface_satisfaction(progress=progress)
+
# --- Phase 3: Resolve symbol-level calls ---
self._resolve_calls(import_targets, progress=progress)
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index 6b1f12234..d4bb03cf3 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -40,10 +40,17 @@ def _warmup_dotnet(ctx: "ResolverContext") -> None:
get_or_build_index(ctx)
+def _warmup_go(ctx: "ResolverContext") -> None:
+ from .resolvers.go_workspace import get_or_build_go_index
+
+ get_or_build_go_index(ctx)
+
+
# Map language tag → (phase-event name, warmup function). The phase
# name shows up in the CLI progress bar and in ``state.json`` timings.
_WARMUPS: dict[str, tuple[str, Warmup]] = {
"csharp": ("graph.dotnet_index", _warmup_dotnet),
+ "go": ("graph.go_index", _warmup_go),
}
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.py
new file mode 100644
index 000000000..a5a30c02b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.py
@@ -0,0 +1,312 @@
+"""Go structural interface satisfaction.
+
+Background
+----------
+Go interfaces are satisfied *structurally*: a concrete type implements an
+interface iff its method set is a superset of the interface's method set.
+There is no ``implements`` keyword and no import recording the relationship,
+so nothing in the import / heritage / call graph connects a concrete type to
+the interfaces it satisfies. The consequence for dead-code analysis is that
+an interface whose only consumers reach it through a concrete implementor
+(``var w io.Writer = &File{}``; dependency-injected services; the
+``return concrete`` / accept-interface-return-struct idiom) reads as an
+unreferenced public export — the dominant residual ``unused_export`` bucket
+for Go after call/type resolution lands (Phase 3).
+
+This pass closes that gap the way C#/Java heritage edges do, but computed
+structurally because Go has no nominal ``implements`` clause:
+
+1. For every concrete type, collect its method set from method declarations
+ (receiver type → method names), aggregated across the package's files.
+2. For every interface, collect its method set from ``method_elem`` members,
+ expanding embedded interfaces (``type_elem``) transitively within the repo.
+3. A concrete type *satisfies* an interface when its method set ⊇ the
+ interface's (non-empty) method set. Emit a ``method_implements`` edge
+ ``concrete_type → interface_type``.
+
+The edge direction (implementor → interface) lands the usage signal on the
+**interface** symbol, which the dead-code analyzer reads as "something
+implements this, so it is not dead" — exactly the existing treatment of
+incoming ``method_implements`` edges (shared with C++/C# qualified-method
+resolution). ``method_implements`` is reused rather than a plain heritage
+``implements`` edge so the suppression is Go-local and needs no change to
+the analyzer's edge-type tables.
+
+The pass is **self-contained**: it parses Go source with the shared
+tree-sitter grammar and emits edges. It does not depend on the resolver
+context, the call resolver, or ``GoPackageIndex``. Matching is by method
+*name* (signatures are not compared), so it is a deliberate over-approximation
+of Go's structural rule — it can connect a type to an interface it does not
+truly satisfy when names coincide. For dead-code that is the safe direction:
+it suppresses *false* "dead interface" findings; it never invents a finding.
+A genuinely dead interface with no name-matching implementor is still flagged.
+"""
+
+from __future__ import annotations
+
+import posixpath
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+if TYPE_CHECKING:
+ import networkx as nx
+ from tree_sitter import Node
+
+log = structlog.get_logger(__name__)
+
+_IMPLEMENTS_CONFIDENCE = 0.6
+
+# Cap on embedded-interface expansion depth — guards against cyclic or
+# pathological embedding chains. Real Go embedding nests only a level or two.
+_MAX_EMBED_DEPTH = 6
+
+
+def _receiver_type_name(method_node: "Node", src: bytes) -> str | None:
+ """Return the bare receiver type of a ``method_declaration``.
+
+ ``func (f *File) M()`` → ``File``; ``func (f File) M()`` → ``File``.
+ The receiver is the first ``parameter_list`` child (the one preceding the
+ method name); the declared type may be wrapped in a ``pointer_type``.
+ """
+ recv = None
+ for child in method_node.children:
+ if child.type == "parameter_list":
+ recv = child
+ break
+ if recv is None:
+ return None
+ for pdecl in recv.children:
+ if pdecl.type != "parameter_declaration":
+ continue
+ type_node = pdecl.child_by_field_name("type")
+ if type_node is None:
+ continue
+ if type_node.type == "pointer_type":
+ for c in type_node.children:
+ if c.type in ("type_identifier", "generic_type"):
+ type_node = c
+ break
+ if type_node.type == "generic_type":
+ inner = type_node.child_by_field_name("type")
+ if inner is not None:
+ type_node = inner
+ if type_node.type == "type_identifier":
+ return src[type_node.start_byte : type_node.end_byte].decode(
+ "utf-8", "ignore"
+ )
+ return None
+
+
+def _interface_facts(iface_node: "Node", src: bytes) -> tuple[set[str], list[str]]:
+ """Return (explicit method names, embedded interface bare names)."""
+ methods: set[str] = set()
+ embedded: list[str] = []
+ for elem in iface_node.children:
+ if elem.type == "method_elem":
+ name_node = elem.child_by_field_name("name")
+ if name_node is None:
+ # Older grammars expose the name as the first field_identifier.
+ name_node = next(
+ (c for c in elem.children if c.type == "field_identifier"), None
+ )
+ if name_node is not None:
+ methods.add(
+ src[name_node.start_byte : name_node.end_byte].decode(
+ "utf-8", "ignore"
+ )
+ )
+ elif elem.type == "type_elem":
+ text = src[elem.start_byte : elem.end_byte].decode("utf-8", "ignore").strip()
+ # Embedded interface: ``io.Reader`` / ``Reader``. Skip type-set
+ # constraints (``~int | string``) — those are generic bounds, not
+ # method-bearing embeds.
+ if "|" in text or "~" in text:
+ continue
+ bare = text.split(".")[-1].strip()
+ if bare and bare[0].isalpha():
+ embedded.append(bare)
+ return methods, embedded
+
+
+class _FileFacts:
+ __slots__ = ("interfaces", "concrete_methods", "type_kind")
+
+ def __init__(self) -> None:
+ # name -> (explicit methods, embedded bare names)
+ self.interfaces: dict[str, tuple[set[str], list[str]]] = {}
+ # receiver type name -> method names declared in this file
+ self.concrete_methods: dict[str, set[str]] = {}
+ # type name -> "interface" | "concrete"
+ self.type_kind: dict[str, str] = {}
+
+
+def _extract_file_facts(root: "Node", src: bytes) -> _FileFacts:
+ facts = _FileFacts()
+
+ def walk(node: "Node") -> None:
+ if node.type == "type_spec":
+ name_node = node.child_by_field_name("name")
+ type_node = node.child_by_field_name("type")
+ if name_node is not None and type_node is not None:
+ name = src[name_node.start_byte : name_node.end_byte].decode(
+ "utf-8", "ignore"
+ )
+ if type_node.type == "interface_type":
+ facts.interfaces[name] = _interface_facts(type_node, src)
+ facts.type_kind[name] = "interface"
+ else:
+ facts.type_kind[name] = "concrete"
+ elif node.type == "method_declaration":
+ recv = _receiver_type_name(node, src)
+ name_node = node.child_by_field_name("name")
+ if recv is not None and name_node is not None:
+ mname = src[name_node.start_byte : name_node.end_byte].decode(
+ "utf-8", "ignore"
+ )
+ facts.concrete_methods.setdefault(recv, set()).add(mname)
+ for child in node.children:
+ walk(child)
+
+ walk(root)
+ return facts
+
+
+def _parse_go(src: bytes) -> "Node | None":
+ """Parse Go source into a tree-sitter root node using the shared grammar."""
+ from ..parser import _get_language # local import: avoid cycle at module load
+
+ try:
+ from tree_sitter import Parser
+ except Exception: # pragma: no cover - tree_sitter always present in practice
+ return None
+ lang = _get_language("go")
+ if lang is None:
+ return None
+ return Parser(lang).parse(src).root_node
+
+
+def resolve_go_interface_satisfaction(
+ graph: "nx.DiGraph", parsed_files: dict[str, Any]
+) -> int:
+ """Emit ``method_implements`` edges for structural Go interface satisfaction.
+
+ Returns the number of edges added.
+ """
+ go_files = {
+ path: parsed
+ for path, parsed in parsed_files.items()
+ if parsed.file_info.language == "go"
+ }
+ if not go_files:
+ return 0
+
+ # --- Pass 1: collect per-file facts -----------------------------------
+ # Per package directory: type name -> defining file, and method sets.
+ # Go's package is a directory, so methods of a type may be spread across
+ # sibling files; aggregate by (pkg_dir, type_name).
+ type_def_file: dict[tuple[str, str], str] = {}
+ concrete_methods: dict[tuple[str, str], set[str]] = {}
+ interface_methods: dict[tuple[str, str], set[str]] = {}
+ interface_embeds: dict[tuple[str, str], list[str]] = {}
+
+ for path, parsed in go_files.items():
+ try:
+ src = parsed.file_info.abs_path
+ with open(src, "rb") as fh:
+ data = fh.read()
+ except OSError:
+ continue
+ root = _parse_go(data)
+ if root is None:
+ continue
+ facts = _extract_file_facts(root, data)
+ pkg = posixpath.dirname(path)
+
+ for tname, kind in facts.type_kind.items():
+ type_def_file[(pkg, tname)] = path
+ if kind == "interface":
+ methods, embeds = facts.interfaces[tname]
+ interface_methods.setdefault((pkg, tname), set()).update(methods)
+ interface_embeds.setdefault((pkg, tname), []).extend(embeds)
+ for recv, mnames in facts.concrete_methods.items():
+ concrete_methods.setdefault((pkg, recv), set()).update(mnames)
+
+ if not interface_methods:
+ return 0
+
+ # --- Pass 2: expand embedded interfaces (transitive, within repo) ------
+ # Resolve an embedded bare name to an interface in the same package first,
+ # then any package. External embeds (io.Reader) stay unresolved — their
+ # methods are simply absent from the set, which only makes matching more
+ # conservative (a concrete type still needs the explicit methods).
+ name_to_iface_keys: dict[str, list[tuple[str, str]]] = {}
+ for key in interface_methods:
+ name_to_iface_keys.setdefault(key[1], []).append(key)
+
+ def _expand(key: tuple[str, str], depth: int, seen: set) -> set[str]:
+ if key in seen or depth > _MAX_EMBED_DEPTH:
+ return set(interface_methods.get(key, set()))
+ seen.add(key)
+ result = set(interface_methods.get(key, set()))
+ pkg = key[0]
+ for bare in interface_embeds.get(key, ()):
+ # Prefer an embedded interface in the same package.
+ target = None
+ if (pkg, bare) in interface_methods:
+ target = (pkg, bare)
+ else:
+ candidates = name_to_iface_keys.get(bare)
+ if candidates and len(candidates) == 1:
+ target = candidates[0]
+ if target is not None:
+ result |= _expand(target, depth + 1, seen)
+ return result
+
+ expanded_iface: dict[tuple[str, str], frozenset[str]] = {}
+ for key in interface_methods:
+ methods = _expand(key, 0, set())
+ if methods:
+ expanded_iface[key] = frozenset(methods)
+
+ # --- Pass 3: index concrete types by method name, then match ----------
+ method_to_concrete: dict[str, list[tuple[str, str]]] = {}
+ for ckey, mnames in concrete_methods.items():
+ for m in mnames:
+ method_to_concrete.setdefault(m, []).append(ckey)
+
+ count = 0
+ for ikey, imethods in expanded_iface.items():
+ iface_file = type_def_file.get(ikey)
+ if iface_file is None:
+ continue
+ iface_id = f"{iface_file}::{ikey[1]}"
+ if not graph.has_node(iface_id):
+ continue
+ # Candidate concrete types = those declaring the interface's rarest
+ # method; verify the full superset relation against each.
+ rarest = min(imethods, key=lambda m: len(method_to_concrete.get(m, ())))
+ candidates = method_to_concrete.get(rarest, ())
+ for ckey in candidates:
+ if ckey == ikey:
+ continue
+ if not imethods <= concrete_methods.get(ckey, set()):
+ continue
+ concrete_file = type_def_file.get(ckey)
+ if concrete_file is None:
+ continue
+ concrete_id = f"{concrete_file}::{ckey[1]}"
+ if concrete_id == iface_id or not graph.has_node(concrete_id):
+ continue
+ if graph.has_edge(concrete_id, iface_id):
+ continue
+ graph.add_edge(
+ concrete_id,
+ iface_id,
+ edge_type="method_implements",
+ confidence=_IMPLEMENTS_CONFIDENCE,
+ imported_names=[],
+ )
+ count += 1
+
+ return count
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 715369db1..47e53be40 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -259,7 +259,10 @@ class TypeReference:
type_name: str # head identifier (e.g. "IBasketService" from "IBasketService<T>")
line: int # 1-indexed source line
- origin: Literal["ctor_param", "method_param", "delegate_param"] = "ctor_param"
+ origin: Literal[
+ "ctor_param", "method_param", "delegate_param", # C#
+ "param_type", "field_type", "composite_literal", # Go
+ ] = "ctor_param"
@dataclass
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 087305f5e..c49f403fe 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -66,6 +66,7 @@ from .parser_helpers import (
_is_async_node,
_qualified_cpp_parent,
_run_query,
+ TYPE_HEAD_EXTRACTORS,
)
log = structlog.get_logger(__name__)
@@ -270,7 +271,7 @@ class ASTParser:
heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)
exports = self._derive_exports(symbols, config, src)
docstring = extract_module_docstring(root, src, lang)
- type_refs = self._extract_type_refs(tree, query, src)
+ type_refs = self._extract_type_refs(tree, query, src, lang)
if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
log.warning(
@@ -678,23 +679,29 @@ class ASTParser:
tree: object,
query: object,
src: str,
+ lang: str = "",
) -> list[TypeReference]:
"""Collect ``@param.type`` captures into TypeReference records.
- Currently only the C# query emits these captures (constructor /
- method / delegate / primary-ctor parameter types). The graph
+ C# emits these from constructor / method / delegate / primary-ctor
+ parameter types; Go emits them from parameter, struct-field, return,
+ and composite-literal type positions (see ``go.scm``). The graph
builder resolves each reference to a defining file via the
language-specific resolver index and emits a file-level edge.
- Capture origin is inferred from the parameter's enclosing node:
- ``constructor_declaration`` → ``ctor_param`` (highest signal:
- canonical DI vector), ``method_declaration`` → ``method_param``,
- ``delegate_declaration`` → ``delegate_param``. Primary
- constructors on records / classes also resolve to ``ctor_param``.
+ The head-identifier extractor is language-specific (Go unwraps
+ ``*T`` / ``[]T`` / ``map[K]V`` / ``pkg.T``); see
+ ``TYPE_HEAD_EXTRACTORS``. Capture origin is inferred from the
+ enclosing node: ``constructor_declaration`` → ``ctor_param``,
+ ``method_declaration`` → ``method_param`` (C#);
+ ``field_declaration`` → ``field_type``, ``composite_literal`` →
+ ``composite_literal`` (Go).
"""
if query is None:
return []
+ head_of = TYPE_HEAD_EXTRACTORS.get(lang, _head_type_identifier)
+
refs: list[TypeReference] = []
seen: set[tuple[str, int]] = set()
@@ -703,7 +710,7 @@ class ASTParser:
if not type_nodes:
continue
for type_node in type_nodes:
- head = _head_type_identifier(type_node, src)
+ head = head_of(type_node, src)
if not head:
continue
line = type_node.start_point[0] + 1
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 4346caadc..d35b580bf 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -9,6 +9,7 @@ this one holds the free functions it calls. No state, no imports from
from __future__ import annotations
+from collections.abc import Callable
from pathlib import Path
import structlog
@@ -172,6 +173,12 @@ _PARAM_ORIGIN_BY_ANCESTOR: dict[str, str] = {
"record_declaration": "ctor_param",
"class_declaration": "ctor_param",
"struct_declaration": "ctor_param",
+ # Go type positions — node types are Go-only so they never collide with
+ # the C# entries above. The origin is provenance only; resolution treats
+ # all type-use edges equally.
+ "field_declaration": "field_type",
+ "parameter_declaration": "param_type",
+ "composite_literal": "composite_literal",
}
@@ -283,6 +290,103 @@ def _classify_param_origin(type_node: Node) -> str:
return "method_param"
+# ---------------------------------------------------------------------------
+# Go type-reference head extraction
+# ---------------------------------------------------------------------------
+
+# Predeclared Go type names — never resolve to a user-defined type, so they
+# are dropped before the resolver lookup. ``error``/``any``/``comparable``
+# are predeclared identifiers, not keywords, but behave as builtins here.
+_GO_BUILTIN_TYPES: frozenset[str] = frozenset(
+ {
+ "string", "bool", "byte", "rune", "error", "any", "comparable",
+ "int", "int8", "int16", "int32", "int64",
+ "uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
+ "float32", "float64", "complex64", "complex128",
+ }
+)
+
+
+def _go_head_type_identifier(type_node: Node, src: str) -> str | None:
+ """Return the head type name of a Go type expression, or None.
+
+ Unwraps the modifier shells Go layers around a named type so the
+ resolver sees the bare identifier it indexes by:
+
+ ``Options`` → "Options"
+ ``*Cache`` → "Cache"
+ ``[]Partition`` → "Partition"
+ ``map[string]Config`` → "Config" (value type; string filtered)
+ ``chan Event`` → "Event"
+ ``dynacache.Cache`` → "Cache" (qualifier dropped)
+ ``List[Inner]`` → "List" (generic head)
+ ``string`` / ``int`` → None (builtin)
+ ``(Foo, error)`` → None (parameter_list; the inner
+ declarations are captured
+ separately)
+ ``interface{...}`` / ``struct{...}`` / ``func(...)`` → None (anonymous)
+
+ The qualifier in ``pkg.Cache`` is intentionally dropped: the Go type-ref
+ strategy resolves the bare name against same-package siblings and
+ imported package files, mirroring the Rust strategy. Keeping the head
+ name unqualified matches the symbol-index keys.
+ """
+ node: Node | None = type_node
+ text = ""
+ for _ in range(8):
+ if node is None:
+ return None
+ kind = node.type
+ if kind == "type_identifier":
+ text = _node_text(node, src)
+ break
+ if kind == "qualified_type":
+ name = node.child_by_field_name("name") or next(
+ (c for c in reversed(node.children) if c.type == "type_identifier"),
+ None,
+ )
+ text = _node_text(name, src) if name else ""
+ break
+ if kind == "generic_type":
+ node = node.child_by_field_name("type")
+ continue
+ if kind in ("slice_type", "array_type"):
+ node = node.child_by_field_name("element")
+ continue
+ if kind == "map_type":
+ node = node.child_by_field_name("value")
+ continue
+ if kind == "channel_type":
+ node = node.child_by_field_name("value")
+ continue
+ if kind in ("pointer_type", "parenthesized_type"):
+ # No field name on the inner type — take the first named child.
+ node = node.named_children[0] if node.named_children else None
+ continue
+ # parameter_list (multi-return), interface_type, struct_type,
+ # function_type, and anything else: no single named type to resolve.
+ return None
+ else:
+ return None
+
+ if not text or (not text[0].isalpha() and text[0] != "_"):
+ return None
+ if text in _GO_BUILTIN_TYPES:
+ return None
+ # Single-uppercase-letter heads are overwhelmingly generic type params.
+ if len(text) == 1 and text.isupper():
+ return None
+ return text
+
+
+# Per-language head-identifier extractor for ``@param.type`` captures.
+# Defaults to the C#-shaped extractor; languages with a differently-shaped
+# type grammar register their own here.
+TYPE_HEAD_EXTRACTORS: dict[str, "Callable[[Node, str], str | None]"] = {
+ "go": _go_head_type_identifier,
+}
+
+
# ---------------------------------------------------------------------------
# Call extraction helpers
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/go.scm b/packages/core/src/repowise/core/ingestion/queries/go.scm
index a649fc0d8..3a57c15b3 100644
--- a/packages/core/src/repowise/core/ingestion/queries/go.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/go.scm
@@ -76,3 +76,33 @@
)
arguments: (argument_list) @call.arguments
) @call.site
+
+; ---------------------------------------------------------------------------
+; Type references — drive file-level ``type_use`` edges
+; ---------------------------------------------------------------------------
+; Go places a large share of its dependency surface in type positions that
+; carry no import statement: a struct field of type ``pkg.Config``, a
+; parameter or return of a sibling-package type, a ``pkg.Options{}``
+; composite literal. The single ``@param.type`` capture name is reused
+; across languages (see parser._extract_type_refs); the Go-specific head
+; extractor unwraps ``*T`` / ``[]T`` / ``map[K]V`` / ``pkg.T`` / ``T[U]``.
+
+; Parameter and receiver types: func f(o Options), func (c *Cache) ...
+(parameter_declaration
+ type: (_) @param.type)
+
+; Struct field types: struct { Inner *Partition }
+(field_declaration
+ type: (_) @param.type)
+
+; Single return type: func New() *Cache (multi-returns are parameter_lists,
+; already covered by the parameter_declaration pattern above)
+(function_declaration
+ result: (_) @param.type)
+(method_declaration
+ result: (_) @param.type)
+
+; Composite-literal type: Options{...}, pkg.Cache{...} — the key signal that
+; rescues struct types used only as values, never imported by name.
+(composite_literal
+ type: (_) @param.type)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/go.py b/packages/core/src/repowise/core/ingestion/resolvers/go.py
index 78db5d5b7..2120dde32 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/go.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/go.py
@@ -104,3 +104,34 @@ def resolve_go_import(module_path: str, importer_path: str, ctx: ResolverContext
# External package
return ctx.add_external_node(module_path)
+
+
+def resolve_go_import_all(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> tuple[str, ...]:
+ """Resolve a Go import to **every** ``.go`` file in the target package.
+
+ Go imports name a package *directory*; the package's symbols are spread
+ across all its sibling ``.go`` files with no per-file import. The
+ legacy :func:`resolve_go_import` returns a single representative file,
+ which leaves the package's other files with ``in_degree == 0`` and
+ mis-flagged as unreachable. This variant consults the
+ :class:`GoPackageIndex` and returns the full file set so the builder
+ can fan an IMPORTS edge out to each one.
+
+ External packages (no local ``go.mod`` match) resolve to a single
+ external node — exactly as :func:`resolve_go_import` would — and are
+ returned as a one-tuple. Returns an empty tuple only when nothing at
+ all resolves.
+ """
+ from .go_workspace import get_or_build_go_index
+
+ index = get_or_build_go_index(ctx)
+ files = index.files_for_import(module_path)
+ if files:
+ return files
+
+ # Not a known local package directory — defer to the single-target
+ # resolver (handles longest-prefix stem matches and external nodes).
+ single = resolve_go_import(module_path, importer_path, ctx)
+ return (single,) if single else ()
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py
new file mode 100644
index 000000000..1f7958225
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py
@@ -0,0 +1,215 @@
+"""Go package index — groups ``.go`` files by their package directory.
+
+Go's unit of compilation is the *package*: a directory of ``.go`` files
+sharing a ``package X`` clause. Files in the same package reference each
+other's symbols with **no import statement**, and a cross-package import
+names a *package directory*, not a file. The legacy resolver
+(``resolve_go_import``) returns only the first ``.go`` file it finds in an
+imported package directory, so sibling files in that package get
+``in_degree == 0`` and are mis-flagged as unreachable.
+
+``GoPackageIndex`` models packages as first-class directories and maps an
+import path → every ``.go`` file in the resolved package. It is the
+foundation the call/type-ref/dead-code phases consume. Built once per
+resolver run via :func:`get_or_build_go_index` and cached on the context,
+mirroring the ``DotNetProjectIndex`` / ``CargoWorkspaceIndex`` pattern.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING
+
+import structlog
+
+from .go import read_go_modules
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+
+@dataclass(frozen=True)
+class GoPackage:
+ """A single Go package — one directory of sibling ``.go`` files."""
+
+ dir: str # repo-relative POSIX path of the package directory ("" = repo root)
+ pkg_name: str # the ``package X`` clause (best-effort; "" if undetected)
+ is_main: bool # any file declares ``package main``
+ files: tuple[str, ...] # repo-relative POSIX ``.go`` paths, sorted
+ build_constrained: bool = False # any file carries //go:build or // +build
+ has_init: bool = False # any file declares a top-level ``func init``
+ # name → defining file(s) within this package. Deferred to Phase 3
+ # (call/type-ref resolution) — left empty here to keep the warmup pure
+ # and dependency-light. See GO_PARITY_PLAN.md Phase 3.
+ exported_symbols: dict[str, tuple[str, ...]] = field(default_factory=dict)
+
+
+@dataclass
+class GoPackageIndex:
+ """Repo-scoped view of every local Go package."""
+
+ packages: dict[str, GoPackage] = field(default_factory=dict)
+ """Keyed by package directory (repo-relative POSIX)."""
+
+ import_path_to_dir: dict[str, str] = field(default_factory=dict)
+ """Maps a fully-qualified import path → its package directory."""
+
+ def files_for_import(self, import_path: str) -> tuple[str, ...]:
+ """Return every ``.go`` file in the package the import resolves to.
+
+ Empty tuple when the import path is not a local package (e.g. an
+ external ``github.com/...`` dependency) — callers fall back to the
+ external-node path for those.
+ """
+ pkg_dir = self.import_path_to_dir.get(import_path)
+ if pkg_dir is None:
+ return ()
+ pkg = self.packages.get(pkg_dir)
+ return pkg.files if pkg else ()
+
+ def package_for_file(self, file_path: str) -> GoPackage | None:
+ """Return the package owning *file_path*, or None."""
+ parent = PurePosixPath(file_path).parent.as_posix()
+ if parent == ".":
+ parent = ""
+ return self.packages.get(parent)
+
+
+_BUILD_TAG_PREFIXES = ("//go:build", "// +build", "//+build")
+
+
+def _scan_go_file(text: str) -> tuple[str, bool, bool, bool]:
+ """Return ``(pkg_name, is_main, build_constrained, has_init)``.
+
+ Reads only what's needed to characterise the file: the ``package``
+ clause, whether a build constraint is present (must appear before the
+ package clause, in the leading comment block), and whether a top-level
+ ``func init()`` is declared. Cheap line scan — no tree-sitter.
+ """
+ pkg_name = ""
+ build_constrained = False
+ has_init = False
+ seen_package = False
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line:
+ continue
+ if not seen_package and line.startswith(_BUILD_TAG_PREFIXES):
+ build_constrained = True
+ continue
+ if not seen_package and line.startswith("package "):
+ pkg_name = line.split(None, 1)[1].split()[0].strip()
+ seen_package = True
+ continue
+ # Top-level ``func init()`` — no receiver, exact name.
+ if seen_package and line.startswith("func init(") and "init()" in line.replace(" ", ""):
+ has_init = True
+ return pkg_name, pkg_name == "main", build_constrained, has_init
+
+
+def _read_text(ctx: "ResolverContext", rel_path: str) -> str:
+ if ctx.repo_path is None:
+ return ""
+ try:
+ return (ctx.repo_path / rel_path).read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ return ""
+
+
+def _import_path_for_dir(
+ pkg_dir: str, go_modules: tuple[tuple[str, str], ...]
+) -> str | None:
+ """Compute a package's import path from the enclosing module.
+
+ *go_modules* is ``((module_dir, module_path), ...)`` sorted longest
+ module-path first; we re-rank by the longest matching *module_dir* so
+ nested modules in a monorepo win over the root module.
+ """
+ best: tuple[str, str] | None = None
+ best_len = -1
+ for module_dir, mod_path in go_modules:
+ if module_dir == "" or pkg_dir == module_dir or pkg_dir.startswith(module_dir + "/"):
+ if len(module_dir) > best_len:
+ best = (module_dir, mod_path)
+ best_len = len(module_dir)
+ if best is None:
+ return None
+ module_dir, mod_path = best
+ suffix = pkg_dir[len(module_dir):].lstrip("/") if module_dir else pkg_dir
+ return f"{mod_path}/{suffix}" if suffix else mod_path
+
+
+def build_go_package_index(ctx: "ResolverContext") -> GoPackageIndex:
+ """Group every ``.go`` file in ``ctx.path_set`` by package directory.
+
+ One walk over the path set; each file is read at most once to detect
+ ``package main`` / build tags / ``func init``. The import-path → dir
+ mapping reuses ``read_go_modules`` for monorepo correctness.
+ """
+ # Resolve the module list. Prefer the context's pre-read tuple; fall
+ # back to a fresh read, then to the legacy single-module field so
+ # manually-built test contexts still map import paths.
+ go_modules = ctx.go_modules or read_go_modules(ctx.repo_path)
+ if not go_modules and ctx.go_module_path:
+ go_modules = (("", ctx.go_module_path),)
+
+ files_by_dir: dict[str, list[str]] = {}
+ for path in ctx.path_set:
+ if not path.endswith(".go"):
+ continue
+ parent = PurePosixPath(path).parent.as_posix()
+ if parent == ".":
+ parent = ""
+ files_by_dir.setdefault(parent, []).append(path)
+
+ index = GoPackageIndex()
+ for pkg_dir, files in files_by_dir.items():
+ files.sort()
+ pkg_name = ""
+ is_main = False
+ build_constrained = False
+ has_init = False
+ for f in files:
+ name, file_main, file_bc, file_init = _scan_go_file(_read_text(ctx, f))
+ # First non-empty package name wins (sibling files agree by
+ # Go rule, except for the ``_test`` external-test package).
+ if name and not pkg_name:
+ pkg_name = name
+ is_main = is_main or file_main
+ build_constrained = build_constrained or file_bc
+ has_init = has_init or file_init
+ index.packages[pkg_dir] = GoPackage(
+ dir=pkg_dir,
+ pkg_name=pkg_name,
+ is_main=is_main,
+ files=tuple(files),
+ build_constrained=build_constrained,
+ has_init=has_init,
+ )
+ import_path = _import_path_for_dir(pkg_dir, go_modules)
+ if import_path is not None:
+ index.import_path_to_dir[import_path] = pkg_dir
+
+ log.debug(
+ "Built Go package index",
+ packages=len(index.packages),
+ import_paths=len(index.import_path_to_dir),
+ modules=len(go_modules),
+ )
+ return index
+
+
+_INDEX_KEY = "_go_package_index"
+
+
+def get_or_build_go_index(ctx: "ResolverContext") -> GoPackageIndex:
+ """Return the cached GoPackageIndex, building it on first access."""
+ cached = getattr(ctx, _INDEX_KEY, None)
+ if cached is not None:
+ return cached
+ index = build_go_package_index(ctx)
+ setattr(ctx, _INDEX_KEY, index)
+ return index
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index 167719350..44f76dc9c 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -197,6 +197,85 @@ def _find_rust_type_file(
return None
+# ---------------------------------------------------------------------------
+# Strategy: Go
+# ---------------------------------------------------------------------------
+
+def _resolve_go_type_refs(
+ parsed: ParsedFile,
+ ctx: "ResolverContext",
+ graph: "nx.DiGraph",
+) -> int:
+ """Resolve Go ``@param.type`` captures via the Go package index.
+
+ Go references a type either bare (same package — no import) or
+ package-qualified (``pkg.Type`` — the qualifier was already stripped by
+ the head extractor). The candidate set is therefore the file's own
+ package siblings plus every ``.go`` file in each imported local package.
+ The type name is matched against the symbols those files define, and a
+ file-level ``type_use`` edge is emitted — which is what lets the
+ unused-export pass see a struct used only as a field/param/return type.
+ """
+ if not parsed.type_refs:
+ return 0
+
+ from .parser_helpers import _GO_BUILTIN_TYPES
+ from .resolvers.go_workspace import get_or_build_go_index
+
+ index = get_or_build_go_index(ctx)
+ from_path = parsed.file_info.path
+
+ # Candidate defining files: same-package siblings (referenced with no
+ # import) + every file in each imported local package (Phase 1 fan-out
+ # means a single import already maps to all of a package's files).
+ candidates: set[str] = set()
+ own_pkg = index.package_for_file(from_path)
+ if own_pkg:
+ candidates.update(own_pkg.files)
+ for imp in parsed.imports:
+ files = index.files_for_import(imp.module_path)
+ if files:
+ candidates.update(files)
+ elif imp.resolved_file and not imp.resolved_file.startswith("external:"):
+ candidates.add(imp.resolved_file)
+ candidates.discard(from_path)
+ if not candidates:
+ return 0
+
+ emitted = 0
+ seen_targets: set[tuple[str, str]] = set()
+ for ref in parsed.type_refs:
+ name = ref.type_name
+ if not name or name in _GO_BUILTIN_TYPES:
+ continue
+ target = _find_go_type_file(name, candidates, graph)
+ if target is None or target == from_path:
+ continue
+ if (name, target) in seen_targets:
+ continue
+ seen_targets.add((name, target))
+ _add_or_merge_type_use_edge(graph, src=from_path, dst=target,
+ type_name=name, origin=ref.origin)
+ emitted += 1
+ return emitted
+
+
+def _find_go_type_file(
+ type_name: str,
+ candidate_files: set[str],
+ graph: "nx.DiGraph",
+) -> str | None:
+ """Return a candidate file that defines a type named *type_name*."""
+ for cand in candidate_files:
+ if not graph.has_node(cand):
+ continue
+ for succ in graph.successors(cand):
+ nd = graph.nodes.get(succ, {})
+ if nd.get("node_type") == "symbol" and nd.get("name") == type_name:
+ return cand
+ return None
+
+
# ---------------------------------------------------------------------------
# Strategy registry
# ---------------------------------------------------------------------------
@@ -209,6 +288,7 @@ Strategy = Callable[[ParsedFile, "ResolverContext", "nx.DiGraph"], int]
_STRATEGIES: dict[str, Strategy] = {
"csharp": _resolve_csharp_type_refs,
"rust": _resolve_rust_type_refs,
+ "go": _resolve_go_type_refs,
}
@@ -256,24 +336,25 @@ def _add_or_merge_type_use_edge(
(dead-code's ``in_degree`` check, PageRank, blast-radius) operate
across edge types and still pick it up.
- If a stronger ``imports`` edge from a real ``using`` directive
- already connects the same files, leave it alone — the directive is
- strictly stronger evidence — and just record the type name in
- ``type_uses`` for traceability. Likewise, parallel type_use edges
- between the same pair of files are merged into one row with the
- full list of referenced types in ``imported_names``.
+ If a stronger ``imports`` edge from a real ``using``/package directive
+ already connects the same files, leave its ``edge_type`` and confidence
+ alone — the directive is strictly stronger evidence — but still record
+ the referenced type in both ``type_uses`` (provenance) and
+ ``imported_names``. The latter matters because the unused-export pass
+ treats ``imported_names`` as the set of names used from a file: a type
+ referenced as a field/param/return is genuinely used, and Go's package
+ import fan-out means the defining file almost always already carries an
+ ``imports`` edge keyed by the *package* alias, not the type name —
+ without this the type would still read as an unused export.
"""
if graph.has_edge(src, dst):
data = graph[src][dst]
type_uses = data.setdefault("type_uses", [])
if type_name not in type_uses:
type_uses.append(type_name)
- # Keep imported_names in sync so the unused-export analyzer can
- # see the referenced type name as evidence of import-like usage.
- if data.get("edge_type") == "type_use":
- names = data.setdefault("imported_names", [])
- if type_name not in names:
- names.append(type_name)
+ names = data.setdefault("imported_names", [])
+ if type_name not in names:
+ names.append(type_name)
return
graph.add_edge(
src,
diff --git a/tests/fixtures/go_sample/cmd/app/main.go b/tests/fixtures/go_sample/cmd/app/main.go
new file mode 100644
index 000000000..937e9a120
--- /dev/null
+++ b/tests/fixtures/go_sample/cmd/app/main.go
@@ -0,0 +1,18 @@
+// Command app is the entry point that reaches the store and service packages.
+package main
+
+import (
+ "example.com/gosample/service"
+ "example.com/gosample/store"
+)
+
+// run wires the concrete store into a service. Naming *store.MemStore (a
+// parameter type) and *service.Service (a return type) exercises the type_use
+// resolution that keeps constructor-returned concrete types reachable.
+func run(st *store.MemStore) *service.Service {
+ return service.New(st)
+}
+
+func main() {
+ run(store.NewMemStore()).Run()
+}
diff --git a/tests/fixtures/go_sample/doc.go b/tests/fixtures/go_sample/doc.go
new file mode 100644
index 000000000..43f93c92b
--- /dev/null
+++ b/tests/fixtures/go_sample/doc.go
@@ -0,0 +1,6 @@
+// Package gosample is a fixture module exercising Go dead-code analysis.
+//
+// It is intentionally only a doc file at the module root; doc.go must be
+// exempt from unreachable-file flagging by the never-flag conventions even
+// though nothing imports the root package.
+package gosample
diff --git a/tests/fixtures/go_sample/go.mod b/tests/fixtures/go_sample/go.mod
new file mode 100644
index 000000000..d4d778cff
--- /dev/null
+++ b/tests/fixtures/go_sample/go.mod
@@ -0,0 +1,3 @@
+module example.com/gosample
+
+go 1.22
diff --git a/tests/fixtures/go_sample/orphan/orphan.go b/tests/fixtures/go_sample/orphan/orphan.go
new file mode 100644
index 000000000..5e58f605d
--- /dev/null
+++ b/tests/fixtures/go_sample/orphan/orphan.go
@@ -0,0 +1,6 @@
+// Package orphan is never imported by any other package in the module — it
+// is genuinely dead and its file must be flagged unreachable.
+package orphan
+
+// Lonely is exported but unreachable: nothing imports this package.
+func Lonely() {}
diff --git a/tests/fixtures/go_sample/service/helpers.go b/tests/fixtures/go_sample/service/helpers.go
new file mode 100644
index 000000000..ad93469e8
--- /dev/null
+++ b/tests/fixtures/go_sample/service/helpers.go
@@ -0,0 +1,12 @@
+package service
+
+// greeting is a private sibling-file helper, called by Service.Run in
+// service.go. It must not be flagged as unused_internal.
+func greeting() string {
+ return "hello"
+}
+
+// DeadExport is exported but referenced from nowhere in the module — the
+// planted genuinely-dead symbol the analyzer MUST still surface. If this
+// stops being reported, the Go dead-code pass has gone silent.
+func DeadExport() {}
diff --git a/tests/fixtures/go_sample/service/service.go b/tests/fixtures/go_sample/service/service.go
new file mode 100644
index 000000000..1ac50aa0f
--- /dev/null
+++ b/tests/fixtures/go_sample/service/service.go
@@ -0,0 +1,24 @@
+// Package service wires a Store into a runnable unit.
+package service
+
+import "example.com/gosample/store"
+
+// Service holds the injected store and, as its only use of store.Config, a
+// configuration field.
+type Service struct {
+ backing store.Store
+ cfg *store.Config
+}
+
+// New builds a Service from a Store. Called cross-package from cmd/app via
+// the package-qualified call service.New(...).
+func New(s store.Store) *Service {
+ return &Service{backing: s}
+}
+
+// Run uses the injected store and a private helper defined in the sibling
+// file helpers.go (same-package cross-file reference).
+func (s *Service) Run() {
+ s.backing.Put("greeting", greeting())
+ _ = s.backing.Get("greeting")
+}
diff --git a/tests/fixtures/go_sample/service/service_test.go b/tests/fixtures/go_sample/service/service_test.go
new file mode 100644
index 000000000..bfd978680
--- /dev/null
+++ b/tests/fixtures/go_sample/service/service_test.go
@@ -0,0 +1,12 @@
+package service
+
+import "testing"
+
+// TestRun is present so the fixture has a _test.go file; the file (and its
+// Test function) must be exempt from dead-code flagging by convention.
+func TestRun(t *testing.T) {
+ svc := New(nil)
+ if svc == nil {
+ t.Fatal("expected a service")
+ }
+}
diff --git a/tests/fixtures/go_sample/store/memory.go b/tests/fixtures/go_sample/store/memory.go
new file mode 100644
index 000000000..faca8f2ec
--- /dev/null
+++ b/tests/fixtures/go_sample/store/memory.go
@@ -0,0 +1,16 @@
+package store
+
+// MemStore is an in-memory Store implementation. It satisfies Store
+// structurally via its Get/Put method set.
+type MemStore struct {
+ data map[string]string
+}
+
+// NewMemStore constructs a MemStore. Called cross-package from cmd/app.
+func NewMemStore() *MemStore {
+ return &MemStore{data: make(map[string]string)}
+}
+
+func (m *MemStore) Get(key string) string { return m.data[key] }
+
+func (m *MemStore) Put(key, value string) { m.data[key] = value }
diff --git a/tests/fixtures/go_sample/store/store.go b/tests/fixtures/go_sample/store/store.go
new file mode 100644
index 000000000..49993dfce
--- /dev/null
+++ b/tests/fixtures/go_sample/store/store.go
@@ -0,0 +1,17 @@
+// Package store defines the persistence contract.
+package store
+
+// Store is the persistence interface. It is implemented by MemStore in the
+// sibling file memory.go — there is no `implements` keyword, so only the
+// structural interface-satisfaction pass connects them.
+type Store interface {
+ Get(key string) string
+ Put(key, value string)
+}
+
+// Config is consumed only as a field type by service.Service. It is never
+// imported by name nor built via a composite literal, so only the type_use
+// rescue keeps it from reading as a dead export.
+type Config struct {
+ Namespace string
+}
diff --git a/tests/integration/test_go_dead_code.py b/tests/integration/test_go_dead_code.py
new file mode 100644
index 000000000..f8bcf832e
--- /dev/null
+++ b/tests/integration/test_go_dead_code.py
@@ -0,0 +1,93 @@
+"""End-to-end Go dead-code regression test for the go_sample fixture.
+
+Runs the full FileTraverser → ASTParser → GraphBuilder → DeadCodeAnalyzer
+pipeline against tests/fixtures/go_sample and proves the Go-parity work
+(Phases 1-4) holds together: the one planted genuinely-dead exported
+function is flagged, the genuinely-unimported package is unreachable, and
+everything that is actually used — across multi-file packages, package
+boundaries, structural interface satisfaction, and field-only type use —
+is NOT flagged.
+
+This is the regression guard that keeps the Go analyzer honest: if a future
+change makes it over-suppress (the live assertions hold but the dead ones
+fail) or regress to false positives (the dead assertions hold but a live one
+fails), this test breaks.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+GO_SAMPLE = Path(__file__).parent.parent / "fixtures" / "go_sample"
+
+
[email protected](scope="module")
+def go_report():
+ traverser = FileTraverser(GO_SAMPLE)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=GO_SAMPLE)
+
+ for fi in traverser.traverse():
+ source = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, source))
+
+ graph = builder.build()
+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})
+ report = analyzer.analyze({"min_confidence": 0.0})
+ return report
+
+
+def _names(report, kind) -> set[str]:
+ return {f.symbol_name for f in report.findings if f.kind == kind}
+
+
+def _paths(report, kind) -> set[str]:
+ return {f.file_path for f in report.findings if f.kind == kind}
+
+
+class TestGoSampleHonesty:
+ def test_planted_dead_export_is_flagged(self, go_report) -> None:
+ exports = _names(go_report, DeadCodeKind.UNUSED_EXPORT)
+ assert "DeadExport" in exports
+
+ def test_orphan_package_is_unreachable(self, go_report) -> None:
+ unreachable = _paths(go_report, DeadCodeKind.UNREACHABLE_FILE)
+ assert any("orphan/orphan.go" in p for p in unreachable)
+
+
+class TestGoSampleNoFalsePositives:
+ def test_live_exports_not_flagged(self, go_report) -> None:
+ exports = _names(go_report, DeadCodeKind.UNUSED_EXPORT)
+ # Store/ReadWriter via interface satisfaction; New via cross-package
+ # call; NewMemStore via cmd/app; Config via field-only type_use;
+ # MemStore via constructor return + implements.
+ for live in ("Store", "Config", "New", "NewMemStore", "MemStore"):
+ assert live not in exports, f"{live} wrongly flagged unused_export"
+
+ def test_sibling_helper_not_flagged_internal(self, go_report) -> None:
+ internals = _names(go_report, DeadCodeKind.UNUSED_INTERNAL)
+ # greeting() is private but called from the sibling service.go.
+ assert "greeting" not in internals
+
+ def test_live_packages_not_unreachable(self, go_report) -> None:
+ unreachable = _paths(go_report, DeadCodeKind.UNREACHABLE_FILE)
+ for live in (
+ "cmd/app/main.go",
+ "store/store.go",
+ "store/memory.go",
+ "service/service.go",
+ "service/helpers.go",
+ "doc.go", # exempt via never-flag convention despite no importer
+ ):
+ assert not any(live in p for p in unreachable), f"{live} wrongly unreachable"
+
+ def test_test_file_not_flagged(self, go_report) -> None:
+ unreachable = _paths(go_report, DeadCodeKind.UNREACHABLE_FILE)
+ exports = _names(go_report, DeadCodeKind.UNUSED_EXPORT)
+ assert not any("service_test.go" in p for p in unreachable)
+ assert "TestRun" not in exports
diff --git a/tests/unit/analysis/test_go_reachability.py b/tests/unit/analysis/test_go_reachability.py
new file mode 100644
index 000000000..d4cfcd446
--- /dev/null
+++ b/tests/unit/analysis/test_go_reachability.py
@@ -0,0 +1,302 @@
+"""Phase 2 regression tests: Go package-aware reachability & never-flag rules.
+
+Validates that Go-specific dead-code semantics hold:
+- package-granular reachability (entry-package siblings, imported siblings),
+- ``func init`` does NOT rescue an otherwise-unimported package,
+- Go never-flag path patterns and entry-symbol names,
+- Go dynamic-import markers,
+- ``unused_internal`` now applies to Go (the Phase 2 exemption was lifted in
+ Phase 3 once package-aware call edges landed).
+"""
+from __future__ import annotations
+
+import fnmatch
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.go_reachability import (
+ build_go_package_files,
+ is_go_file_reachable,
+)
+
+
+# ---------------------------------------------------------------------------
+# Graph helper (mirrors tests/unit/test_dead_code.py)
+# ---------------------------------------------------------------------------
+
+def _build_graph(nodes: dict[str, dict], edges: list | None = None) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for name, attrs in nodes.items():
+ attrs = dict(attrs)
+ sym_list = attrs.pop("symbols", [])
+ g.add_node(name, **attrs)
+ for sym in sym_list:
+ sym_id = f"{name}::{sym['name']}"
+ g.add_node(sym_id, node_type="symbol", file_path=name, **sym)
+ g.add_edge(name, sym_id, edge_type="defines")
+ for edge in edges or []:
+ if len(edge) == 3:
+ g.add_edge(edge[0], edge[1], **(edge[2]))
+ else:
+ g.add_edge(edge[0], edge[1])
+ return g
+
+
+def _go_file(**overrides: object) -> dict:
+ base = {
+ "language": "go",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ }
+ base.update(overrides)
+ return base
+
+
+# ---------------------------------------------------------------------------
+# is_go_file_reachable — unit level
+# ---------------------------------------------------------------------------
+
+class TestGoReachabilityHelper:
+ def test_entry_package_sibling_is_reachable(self):
+ """A helper next to ``main.go`` is reachable though nothing imports it."""
+ g = _build_graph(
+ nodes={
+ "cmd/app/main.go": _go_file(is_entry_point=True),
+ "cmd/app/server.go": _go_file(),
+ }
+ )
+ pkgs = build_go_package_files(g)
+ # server.go has no importer, but its package is an entry package.
+ assert is_go_file_reachable("cmd/app/server.go", g, pkgs)
+
+ def test_imported_sibling_makes_package_reachable(self):
+ """If any sibling carries an importer, the whole package is live."""
+ g = _build_graph(
+ nodes={
+ "pkg/cache/cache.go": _go_file(),
+ "pkg/cache/pruner.go": _go_file(),
+ "pkg/user/user.go": _go_file(),
+ },
+ edges=[("pkg/user/user.go", "pkg/cache/cache.go", {"edge_type": "imports"})],
+ )
+ pkgs = build_go_package_files(g)
+ # pruner.go itself has in_degree 0 but cache.go (its sibling) is imported.
+ assert is_go_file_reachable("pkg/cache/pruner.go", g, pkgs)
+
+ def test_orphaned_package_is_unreachable(self):
+ """A package nobody imports — no entry sibling — stays unreachable."""
+ g = _build_graph(
+ nodes={
+ "pkg/orphan/a.go": _go_file(),
+ "pkg/orphan/b.go": _go_file(),
+ }
+ )
+ pkgs = build_go_package_files(g)
+ assert not is_go_file_reachable("pkg/orphan/a.go", g, pkgs)
+
+ def test_func_init_alone_does_not_rescue_package(self):
+ """``func init`` in an unimported package does not make it live.
+
+ ``init`` runs only when the package is linked, which requires an
+ import; an unimported init-only package is genuinely dead.
+ """
+ g = _build_graph(
+ nodes={
+ "pkg/orphan/init.go": _go_file(
+ has_init=True,
+ symbols=[{
+ "name": "init",
+ "kind": "function",
+ "language": "go",
+ "visibility": "private",
+ "start_line": 1,
+ "end_line": 3,
+ }],
+ ),
+ }
+ )
+ pkgs = build_go_package_files(g)
+ assert not is_go_file_reachable("pkg/orphan/init.go", g, pkgs)
+
+
+# ---------------------------------------------------------------------------
+# Analyzer integration — _detect_unreachable_files
+# ---------------------------------------------------------------------------
+
+class TestGoUnreachableFiles:
+ def test_entry_package_helper_not_flagged(self):
+ g = _build_graph(
+ nodes={
+ "cmd/app/main.go": _go_file(is_entry_point=True),
+ "cmd/app/server.go": _go_file(),
+ }
+ )
+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ unreachable = {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+ assert "cmd/app/server.go" not in unreachable
+
+ def test_orphan_package_still_flagged(self):
+ """Honesty guard: a genuinely-unimported package still surfaces."""
+ g = _build_graph(nodes={"pkg/orphan/a.go": _go_file()})
+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ unreachable = {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+ assert "pkg/orphan/a.go" in unreachable
+
+
+# ---------------------------------------------------------------------------
+# Never-flag patterns
+# ---------------------------------------------------------------------------
+
+class TestGoNeverFlagPatterns:
+ def _matches(self, path: str) -> bool:
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ return any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_test_file(self):
+ assert self._matches("hugolib/page_test.go")
+
+ def test_cmd_main(self):
+ assert self._matches("cmd/hugo/main.go")
+
+ def test_root_main(self):
+ assert self._matches("main.go")
+
+ def test_doc_and_docs_stubs(self):
+ assert self._matches("cache/docs.go")
+ assert self._matches("tpl/openapi/docs.go")
+ assert self._matches("common/doc.go")
+
+ def test_magefile(self):
+ assert self._matches("magefile.go")
+
+ def test_generated_code(self):
+ assert self._matches("api/v1/types.pb.go")
+ assert self._matches("internal/color_string.go")
+ assert self._matches("apis/v1/zz_generated.deepcopy.go")
+ assert self._matches("assets/bindata.go")
+ assert self._matches("schema/model_gen.go")
+
+ def test_ordinary_go_file_not_flagged(self):
+ assert not self._matches("hugolib/page.go")
+
+
+class TestGoEntrySymbols:
+ def test_init_and_testmain_are_entry_symbols(self):
+ from repowise.core.analysis.dead_code.analyzer import _ENTRY_POINT_SYMBOL_NAMES
+ assert "init" in _ENTRY_POINT_SYMBOL_NAMES
+ assert "TestMain" in _ENTRY_POINT_SYMBOL_NAMES
+
+
+class TestGoDynamicMarkers:
+ def test_go_directives_present(self):
+ from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
+ go_markers = _DYNAMIC_IMPORT_MARKERS.get(".go", ())
+ assert "//go:generate" in go_markers
+ assert "//go:embed" in go_markers
+ assert "//go:linkname" in go_markers
+
+
+class TestGoUnusedInternals:
+ """Phase 3 lifted the blanket Go exemption: private Go symbols are now
+ subject to unused_internal, gated on real ``calls`` edges from the
+ package-aware call resolver."""
+
+ def _analyze(self, g: nx.DiGraph):
+ return DeadCodeAnalyzer(g, git_meta_map={}).analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "detect_unused_internals": True,
+ "min_confidence": 0.0,
+ }
+ )
+
+ def _sym(self) -> dict:
+ return {
+ "name": "helper",
+ "kind": "function",
+ "language": "go",
+ "visibility": "private",
+ "start_line": 1,
+ "end_line": 10,
+ }
+
+ def test_uncalled_private_go_symbol_is_flagged(self):
+ """No callers → flagged now that the exemption is lifted."""
+ g = _build_graph(
+ nodes={"pkg/util/util.go": _go_file(symbol_count=1, symbols=[self._sym()])}
+ )
+ report = self._analyze(g)
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert any(f.symbol_name == "helper" for f in internals)
+
+ def test_private_type_kinds_not_flagged_as_internal(self):
+ """Non-callable type kinds (struct/interface) are excluded from the
+ call-graph internal pass — they have no call edges and their type
+ usage isn't observable as a symbol-level edge."""
+ g = _build_graph(
+ nodes={
+ "pkg/util/util.go": _go_file(
+ symbol_count=2,
+ symbols=[
+ {"name": "config", "kind": "struct", "language": "go",
+ "visibility": "private", "start_line": 1, "end_line": 5},
+ {"name": "provider", "kind": "interface", "language": "go",
+ "visibility": "private", "start_line": 6, "end_line": 9},
+ ],
+ ),
+ }
+ )
+ report = self._analyze(g)
+ names = {
+ f.symbol_name for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_INTERNAL
+ }
+ assert "config" not in names
+ assert "provider" not in names
+
+ def test_called_private_go_symbol_not_flagged(self):
+ """A ``calls`` edge from a sibling keeps the symbol live."""
+ g = _build_graph(
+ nodes={
+ "pkg/util/util.go": _go_file(symbol_count=1, symbols=[self._sym()]),
+ "pkg/util/caller.go": _go_file(
+ symbol_count=1,
+ symbols=[{
+ "name": "Run",
+ "kind": "function",
+ "language": "go",
+ "visibility": "public",
+ "start_line": 1,
+ "end_line": 5,
+ }],
+ ),
+ },
+ edges=[(
+ "pkg/util/caller.go::Run",
+ "pkg/util/util.go::helper",
+ {"edge_type": "calls"},
+ )],
+ )
+ report = self._analyze(g)
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert all(f.symbol_name != "helper" for f in internals)
diff --git a/tests/unit/ingestion/test_dynamic_hints_per_language.py b/tests/unit/ingestion/test_dynamic_hints_per_language.py
index c7a6e138a..88c07d73d 100644
--- a/tests/unit/ingestion/test_dynamic_hints_per_language.py
+++ b/tests/unit/ingestion/test_dynamic_hints_per_language.py
@@ -166,6 +166,19 @@ class TestGoHints:
targets = {e.target for e in edges if e.hint_source == "go:reflect_typeof"}
assert "types.go" in targets
+ def test_reflect_new_and_valueof(self, tmp_path: Path) -> None:
+ (tmp_path / "types.go").write_text(
+ "package x\ntype Bar struct{}\ntype Baz struct{}\n"
+ )
+ (tmp_path / "use.go").write_text(
+ "package x\nimport \"reflect\"\n"
+ "var _ = reflect.New(Bar{})\n"
+ "var _ = reflect.ValueOf(Baz{})\n"
+ )
+ edges = GoDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "go:reflect_typeof"}
+ assert "types.go" in targets
+
def test_plugin_open_emits_external(self, tmp_path: Path) -> None:
(tmp_path / "main.go").write_text(
"package main\nimport \"plugin\"\nfunc main(){ plugin.Open(\"./p.so\") }\n"
diff --git a/tests/unit/ingestion/test_go_framework_edges.py b/tests/unit/ingestion/test_go_framework_edges.py
index f0d9dc07f..ee69f9a53 100644
--- a/tests/unit/ingestion/test_go_framework_edges.py
+++ b/tests/unit/ingestion/test_go_framework_edges.py
@@ -93,6 +93,77 @@ class TestGinRoutes:
assert not graph.has_edge("main.go", "main.go")
+class TestNetHTTP:
+ def test_handlefunc_pkg_function(self, tmp_path: Path) -> None:
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.21\n")
+ h = tmp_path / "handlers"
+ h.mkdir()
+ (h / "users.go").write_text(
+ "package handlers\n\nimport \"net/http\"\n\n"
+ "func Index(w http.ResponseWriter, r *http.Request) {}\n"
+ )
+ (tmp_path / "main.go").write_text(
+ "package main\n\nimport (\n \"net/http\"\n \"example.com/app/handlers\"\n)\n\n"
+ "func main() {\n"
+ " http.HandleFunc(\"/users\", handlers.Index)\n"
+ " http.ListenAndServe(\":8080\", nil)\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ added = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert added >= 1
+ assert graph.has_edge("main.go", "handlers/users.go")
+
+ def test_mux_handle_local_function(self, tmp_path: Path) -> None:
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.21\n")
+ (tmp_path / "routes.go").write_text(
+ "package main\n\nimport \"net/http\"\n\n"
+ "func register(mux *http.ServeMux) {\n"
+ " mux.Handle(\"/health\", health)\n"
+ "}\n"
+ )
+ (tmp_path / "health.go").write_text(
+ "package main\n\nimport \"net/http\"\n\n"
+ "var health http.Handler\n\n"
+ "func HealthHandler(w http.ResponseWriter, r *http.Request) {}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ # Should not crash; `health` is a var, not a function — no false edge.
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+
+
+class TestGoGRPC:
+ def test_register_server_to_impl_file(self, tmp_path: Path) -> None:
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.21\n")
+ (tmp_path / "server.go").write_text(
+ "package main\n\n"
+ "type greeterServer struct{}\n\n"
+ "func (s *greeterServer) SayHello() string { return \"hi\" }\n"
+ )
+ (tmp_path / "main.go").write_text(
+ "package main\n\nimport \"google.golang.org/grpc\"\n\n"
+ "func main() {\n"
+ " s := grpc.NewServer()\n"
+ " RegisterGreeterServer(s, &greeterServer{})\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["grpc"])
+ assert graph.has_edge("main.go", "server.go")
+
+
class TestGoRouterGate:
def test_non_router_unaffected(self, tmp_path: Path) -> None:
(tmp_path / "main.go").write_text(
diff --git a/tests/unit/ingestion/test_go_interface_satisfaction.py b/tests/unit/ingestion/test_go_interface_satisfaction.py
new file mode 100644
index 000000000..9756acd0f
--- /dev/null
+++ b/tests/unit/ingestion/test_go_interface_satisfaction.py
@@ -0,0 +1,159 @@
+"""Go Phase 4 — structural interface satisfaction edges.
+
+Go has no nominal ``implements`` clause: a concrete type satisfies an
+interface purely by having the right method set. The
+``go_interface_satisfaction`` pass reconstructs that relation and emits
+``method_implements`` edges (concrete type → interface) so the dead-code
+analyzer stops flagging interfaces reached only through their implementors.
+
+These tests drive the real parser, GraphBuilder and analyzer end-to-end.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _file_info(path: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=abs_path,
+ language="go",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=path.endswith("_test.go"),
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+# A two-package module:
+# * storage/store.go — defines interface Store (Get/Put) + a genuinely
+# dead interface Orphan (no implementor).
+# * storage/embed.go — interface ReadWriter embeds Store + adds Close.
+# * mem/mem.go — concrete *MemStore implements Store and ReadWriter
+# (methods split across two files in the package).
+# * mem/mem_close.go — the Close method of MemStore (sibling file).
+# * cmd/app/main.go — entry point.
+_SOURCES: dict[str, str] = {
+ "go.mod": "module example.com/app\n\ngo 1.22\n",
+ "storage/store.go": (
+ "package storage\n\n"
+ "// Store is implemented by mem.MemStore in another package.\n"
+ "type Store interface {\n"
+ "\tGet(k string) string\n"
+ "\tPut(k, v string)\n"
+ "}\n\n"
+ "// Orphan has no implementor anywhere — genuinely dead.\n"
+ "type Orphan interface {\n"
+ "\tFlux() int\n"
+ "\tReflux() int\n"
+ "}\n"
+ ),
+ "storage/embed.go": (
+ "package storage\n\n"
+ "// ReadWriter embeds Store and adds Close.\n"
+ "type ReadWriter interface {\n"
+ "\tStore\n"
+ "\tClose() error\n"
+ "}\n"
+ ),
+ "mem/mem.go": (
+ "package mem\n\n"
+ "// MemStore satisfies storage.Store and storage.ReadWriter.\n"
+ "type MemStore struct{ m map[string]string }\n\n"
+ "func (s *MemStore) Get(k string) string { return s.m[k] }\n"
+ "func (s *MemStore) Put(k, v string) { s.m[k] = v }\n"
+ ),
+ "mem/mem_close.go": (
+ "package mem\n\n"
+ "// Close lives in a sibling file of the same package.\n"
+ "func (s *MemStore) Close() error { return nil }\n"
+ ),
+ "cmd/app/main.go": ("package main\n\nfunc main() {}\n"),
+}
+
+
+def _build_graph(repo: Path) -> nx.DiGraph:
+ for rel, body in _SOURCES.items():
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+
+ builder = GraphBuilder(repo_path=repo)
+ for rel in _SOURCES:
+ if not rel.endswith(".go"):
+ continue
+ abs_path = str((repo / rel).resolve())
+ parsed = _PARSER.parse_file(_file_info(rel, abs_path), (repo / rel).read_bytes())
+ builder.add_file(parsed)
+ return builder.build()
+
+
+def _method_implements(graph: nx.DiGraph) -> set[tuple[str, str]]:
+ return {
+ (u, v)
+ for u, v, d in graph.edges(data=True)
+ if d.get("edge_type") == "method_implements"
+ }
+
+
+class TestInterfaceSatisfactionEdges:
+ def test_concrete_to_interface_edge_cross_package(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ edges = _method_implements(graph)
+ store_id = "storage/store.go::Store"
+ mem_id = "mem/mem.go::MemStore"
+ assert (mem_id, store_id) in edges
+
+ def test_embedded_interface_satisfied(self, tmp_path: Path) -> None:
+ # ReadWriter = Store (Get/Put) + Close. MemStore has all three, with
+ # Close declared in a sibling package file.
+ graph = _build_graph(tmp_path)
+ edges = _method_implements(graph)
+ rw_id = "storage/embed.go::ReadWriter"
+ mem_id = "mem/mem.go::MemStore"
+ assert (mem_id, rw_id) in edges
+
+ def test_orphan_interface_gets_no_edge(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ edges = _method_implements(graph)
+ orphan_id = "storage/store.go::Orphan"
+ assert not any(v == orphan_id for _, v in edges)
+
+
+class TestInterfaceSatisfactionDeadCode:
+ def _findings(self, repo: Path):
+ graph = _build_graph(repo)
+ analyzer = DeadCodeAnalyzer(graph)
+ return analyzer.analyze().findings
+
+ def _unused_exports(self, repo: Path) -> set[str]:
+ return {
+ f.symbol_name
+ for f in self._findings(repo)
+ if f.kind == DeadCodeKind.UNUSED_EXPORT
+ }
+
+ def test_satisfied_interfaces_not_flagged(self, tmp_path: Path) -> None:
+ exports = self._unused_exports(tmp_path)
+ # Store and ReadWriter have an implementor → not dead exports.
+ assert "Store" not in exports
+ assert "ReadWriter" not in exports
+
+ def test_orphan_interface_still_flagged(self, tmp_path: Path) -> None:
+ # The honesty guard: a genuinely unimplemented interface stays dead.
+ exports = self._unused_exports(tmp_path)
+ assert "Orphan" in exports
diff --git a/tests/unit/ingestion/test_go_resolver.py b/tests/unit/ingestion/test_go_resolver.py
index 9dd4b71bc..c07fb0c43 100644
--- a/tests/unit/ingestion/test_go_resolver.py
+++ b/tests/unit/ingestion/test_go_resolver.py
@@ -10,6 +10,7 @@ from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.go import (
read_go_modules,
resolve_go_import,
+ resolve_go_import_all,
)
@@ -82,3 +83,30 @@ class TestResolveGoImport:
ctx = _ctx(tmp_path, ["pkg/util.go"])
result = resolve_go_import("github.com/external/lib", "main.go", ctx)
assert result == "external:github.com/external/lib"
+
+
+class TestResolveGoImportAll:
+ def _write(self, repo: Path, rel: str, body: str = "package p\n") -> None:
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+
+ def test_returns_all_files_in_package(self, tmp_path: Path) -> None:
+ files = [
+ "cache/filecache/filecache.go",
+ "cache/filecache/filecache_config.go",
+ "cache/filecache/filecache_pruner.go",
+ ]
+ for f in files:
+ self._write(tmp_path, f, "package filecache\n")
+ ctx = _ctx(tmp_path, files, go_modules=(("", "github.com/gohugoio/hugo"),))
+ result = resolve_go_import_all(
+ "github.com/gohugoio/hugo/cache/filecache", "main.go", ctx
+ )
+ assert set(result) == set(files)
+
+ def test_external_is_single_node(self, tmp_path: Path) -> None:
+ self._write(tmp_path, "main.go", "package main\n")
+ ctx = _ctx(tmp_path, ["main.go"], go_modules=(("", "github.com/me/app"),))
+ result = resolve_go_import_all("github.com/spf13/cobra", "main.go", ctx)
+ assert result == ("external:github.com/spf13/cobra",)
diff --git a/tests/unit/ingestion/test_go_type_use.py b/tests/unit/ingestion/test_go_type_use.py
new file mode 100644
index 000000000..4ed321ff0
--- /dev/null
+++ b/tests/unit/ingestion/test_go_type_use.py
@@ -0,0 +1,264 @@
+"""Go Phase 3 — call & type-reference resolution.
+
+Covers the full chain that turns Go's package semantics into graph edges
+the dead-code analyzer can read:
+
+* ``@param.type`` capture → ``TypeReference`` extraction with the Go head
+ extractor (unwraps ``*T`` / ``[]T`` / ``map[K]V`` / ``pkg.T``);
+* ``_resolve_go_type_refs`` → ``type_use`` edges for types used only as
+ field / parameter / return / composite-literal types;
+* package-aware call resolution (``pkg.Func`` across a multi-file package,
+ and bare same-package sibling calls);
+* the end-to-end dead-code outcome: types/functions used cross-file or
+ cross-package are no longer flagged, while genuinely-dead symbols still
+ are (the honesty guard).
+
+All tests drive the real parser, GraphBuilder and analyzer — no mocking of
+the resolution path.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _file_info(path: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=abs_path,
+ language="go",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=path.endswith("_test.go"),
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+# --- A small multi-package module written to disk, mirroring Hugo's -------
+# cache/dynacache layout (multi-file package + cross-package consumer).
+
+_MODULE = "example.com/app"
+
+_SOURCES: dict[str, str] = {
+ "go.mod": "module example.com/app\n\ngo 1.22\n",
+ # --- dynacache: a multi-file package ---
+ "cache/dynacache/dynacache.go": (
+ "package dynacache\n\n"
+ "// Cache is used cross-package as a return type.\n"
+ "type Cache struct {\n"
+ "\tpart *Partition\n"
+ "}\n\n"
+ "// Partition is referenced from options.go (cross-file) and here.\n"
+ "type Partition struct{}\n\n"
+ "func (c *Cache) Part() *Partition { return c.part }\n\n"
+ "// newPartition is private and called from the sibling options.go.\n"
+ "func newPartition() *Partition { return &Partition{} }\n\n"
+ "// orphanInternal is private and never called — genuinely dead.\n"
+ "func orphanInternal() {}\n"
+ ),
+ "cache/dynacache/options.go": (
+ "package dynacache\n\n"
+ "// Options is used cross-package as a composite literal.\n"
+ "type Options struct {\n"
+ "\tseed *Partition\n"
+ "}\n\n"
+ "// New is exported and called cross-package from consumer.\n"
+ "func New(o Options) *Cache {\n"
+ "\t_ = newPartition()\n"
+ "\treturn &Cache{}\n"
+ "}\n"
+ ),
+ # --- consumer: imports dynacache, uses it only via types + a call ---
+ "consumer/consumer.go": (
+ "package consumer\n\n"
+ 'import "example.com/app/cache/dynacache"\n\n'
+ "// Build references New (call), Options (composite) and Cache\n"
+ "// (return type) across the package boundary.\n"
+ "func Build() *dynacache.Cache {\n"
+ "\treturn dynacache.New(dynacache.Options{})\n"
+ "}\n\n"
+ "// DeadExport is exported and never referenced — genuinely dead.\n"
+ "func DeadExport() {}\n"
+ ),
+ # --- main: the entry that reaches consumer.Build ---
+ "cmd/app/main.go": (
+ "package main\n\n"
+ 'import "example.com/app/consumer"\n\n'
+ "func main() { consumer.Build() }\n"
+ ),
+}
+
+
+def _build_graph(repo: Path) -> nx.DiGraph:
+ """Write the module to *repo*, parse every .go file, build the graph."""
+ for rel, body in _SOURCES.items():
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+
+ builder = GraphBuilder(repo_path=repo)
+ for rel in _SOURCES:
+ if not rel.endswith(".go"):
+ continue
+ abs_path = str((repo / rel).resolve())
+ parsed = _PARSER.parse_file(_file_info(rel, abs_path), (repo / rel).read_bytes())
+ builder.add_file(parsed)
+ return builder.build()
+
+
+# ---------------------------------------------------------------------------
+# Parser: Go type-ref extraction + head unwrapping
+# ---------------------------------------------------------------------------
+
+
+class TestGoTypeRefExtraction:
+ def _parse(self, body: str) -> list:
+ info = _file_info("p/f.go", "/repo/p/f.go")
+ return _PARSER.parse_file(info, body.encode("utf-8")).type_refs
+
+ def test_field_param_return_composite_captured(self) -> None:
+ refs = self._parse(
+ "package p\n"
+ "type Opt struct { inner *Bar }\n"
+ "func New(o Opt) *Baz { return &Baz{} }\n"
+ )
+ names = {r.type_name for r in refs}
+ assert {"Bar", "Opt", "Baz"} <= names
+
+ def test_builtins_filtered(self) -> None:
+ refs = self._parse(
+ "package p\n"
+ "func f(s string, n int, b bool, e error) (float64, byte) { return 0, 0 }\n"
+ )
+ names = {r.type_name for r in refs}
+ assert names.isdisjoint({"string", "int", "bool", "error", "float64", "byte"})
+
+ def test_qualifier_dropped_and_containers_unwrapped(self) -> None:
+ refs = self._parse(
+ "package p\n"
+ "type T struct {\n"
+ "\ta *Alpha\n"
+ "\tb []Beta\n"
+ "\tc map[string]Gamma\n"
+ "\td pkg.Delta\n"
+ "}\n"
+ )
+ names = {r.type_name for r in refs}
+ # Pointer/slice/map unwrapped to their named element; map key (string)
+ # filtered; qualifier on pkg.Delta dropped to the bare type.
+ assert {"Alpha", "Beta", "Gamma", "Delta"} <= names
+ assert "pkg" not in names
+ assert "string" not in names
+
+ def test_single_uppercase_generic_param_skipped(self) -> None:
+ refs = self._parse("package p\nfunc f[T any](x T) T { return x }\n")
+ assert "T" not in {r.type_name for r in refs}
+
+
+# ---------------------------------------------------------------------------
+# type_use edges + call edges (end-to-end through GraphBuilder)
+# ---------------------------------------------------------------------------
+
+
+class TestGoTypeUseEdges:
+ def test_cross_package_type_use_edges(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ consumer = "consumer/consumer.go"
+ # Cache lives in dynacache.go, Options in options.go — both reached
+ # from consumer only as types, never imported by name.
+ assert graph.has_edge(consumer, "cache/dynacache/dynacache.go")
+ assert graph.has_edge(consumer, "cache/dynacache/options.go")
+ cache_edge = graph[consumer]["cache/dynacache/dynacache.go"]
+ opt_edge = graph[consumer]["cache/dynacache/options.go"]
+ assert "Cache" in cache_edge.get("imported_names", [])
+ assert "Options" in opt_edge.get("imported_names", [])
+
+ def test_same_package_cross_file_type_use_edge(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ # options.go references Partition (defined in dynacache.go) as a field.
+ edge = graph.get_edge_data(
+ "cache/dynacache/options.go", "cache/dynacache/dynacache.go", {}
+ )
+ assert "Partition" in edge.get("imported_names", [])
+
+
+class TestGoCallResolution:
+ def test_package_qualified_call_resolves_across_files(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ # consumer.Build calls dynacache.New; New is defined in options.go,
+ # not the package's first file. The package-aware resolver must
+ # still produce the calls edge.
+ build_id = "consumer/consumer.go::Build"
+ new_id = "cache/dynacache/options.go::New"
+ assert graph.has_edge(build_id, new_id)
+ assert graph[build_id][new_id]["edge_type"] == "calls"
+
+ def test_same_package_bare_call_resolves(self, tmp_path: Path) -> None:
+ graph = _build_graph(tmp_path)
+ # New (options.go) calls newPartition (dynacache.go) with no import.
+ caller = "cache/dynacache/options.go::New"
+ callee = "cache/dynacache/dynacache.go::newPartition"
+ assert graph.has_edge(caller, callee)
+ assert graph[caller][callee]["edge_type"] == "calls"
+
+
+# ---------------------------------------------------------------------------
+# Dead-code outcome — the honesty guard
+# ---------------------------------------------------------------------------
+
+
+class TestGoDeadCodeOutcome:
+ def _report(self, graph: nx.DiGraph):
+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})
+ return analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "detect_unused_internals": True,
+ "min_confidence": 0.0,
+ }
+ )
+
+ def test_used_types_and_functions_not_flagged(self, tmp_path: Path) -> None:
+ report = self._report(_build_graph(tmp_path))
+ unused_exports = {
+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT
+ }
+ # Cross-package / cross-file uses must clear these.
+ assert {"New", "Cache", "Options", "Partition", "Build"}.isdisjoint(unused_exports)
+
+ def test_genuinely_dead_export_still_flagged(self, tmp_path: Path) -> None:
+ report = self._report(_build_graph(tmp_path))
+ unused_exports = {
+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT
+ }
+ assert "DeadExport" in unused_exports
+
+ def test_private_called_across_siblings_not_flagged(self, tmp_path: Path) -> None:
+ report = self._report(_build_graph(tmp_path))
+ unused_internals = {
+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL
+ }
+ # newPartition is called from a sibling file → live now that the Go
+ # exemption is lifted and same-package call edges exist.
+ assert "newPartition" not in unused_internals
+
+ def test_genuinely_dead_internal_still_flagged(self, tmp_path: Path) -> None:
+ report = self._report(_build_graph(tmp_path))
+ unused_internals = {
+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL
+ }
+ assert "orphanInternal" in unused_internals
diff --git a/tests/unit/ingestion/test_go_workspace.py b/tests/unit/ingestion/test_go_workspace.py
new file mode 100644
index 000000000..b3c20fcd3
--- /dev/null
+++ b/tests/unit/ingestion/test_go_workspace.py
@@ -0,0 +1,126 @@
+"""Unit tests for the Go package index (GoPackageIndex)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.go_workspace import (
+ build_go_package_index,
+ get_or_build_go_index,
+)
+
+
+def _ctx(repo: Path, paths: list[str], go_modules: tuple = ()) -> ResolverContext:
+ return ResolverContext(
+ path_set=set(paths),
+ stem_map={},
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ go_modules=go_modules,
+ )
+
+
+def _write(repo: Path, rel: str, body: str) -> None:
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+
+
+class TestBuildIndex:
+ def test_groups_sibling_files_into_one_package(self, tmp_path: Path) -> None:
+ files = [
+ "cache/filecache/filecache.go",
+ "cache/filecache/filecache_config.go",
+ "cache/filecache/filecache_pruner.go",
+ ]
+ for f in files:
+ _write(tmp_path, f, "package filecache\n")
+ ctx = _ctx(
+ tmp_path, files, go_modules=(("", "github.com/gohugoio/hugo"),)
+ )
+ index = build_go_package_index(ctx)
+ pkg = index.packages["cache/filecache"]
+ assert pkg.pkg_name == "filecache"
+ assert pkg.is_main is False
+ assert pkg.files == tuple(sorted(files))
+
+ def test_files_for_import_returns_all_package_files(self, tmp_path: Path) -> None:
+ files = [
+ "cache/filecache/filecache.go",
+ "cache/filecache/filecache_config.go",
+ "cache/filecache/filecache_pruner.go",
+ ]
+ for f in files:
+ _write(tmp_path, f, "package filecache\n")
+ ctx = _ctx(tmp_path, files, go_modules=(("", "github.com/gohugoio/hugo"),))
+ index = build_go_package_index(ctx)
+ resolved = index.files_for_import("github.com/gohugoio/hugo/cache/filecache")
+ assert set(resolved) == set(files)
+
+ def test_external_import_returns_empty(self, tmp_path: Path) -> None:
+ _write(tmp_path, "main.go", "package main\n")
+ ctx = _ctx(tmp_path, ["main.go"], go_modules=(("", "github.com/me/app"),))
+ index = build_go_package_index(ctx)
+ assert index.files_for_import("github.com/spf13/cobra") == ()
+
+ def test_is_main_detection(self, tmp_path: Path) -> None:
+ _write(tmp_path, "cmd/app/main.go", "package main\n\nfunc main() {}\n")
+ _write(tmp_path, "pkg/lib/lib.go", "package lib\n")
+ files = ["cmd/app/main.go", "pkg/lib/lib.go"]
+ ctx = _ctx(tmp_path, files, go_modules=(("", "github.com/me/app"),))
+ index = build_go_package_index(ctx)
+ assert index.packages["cmd/app"].is_main is True
+ assert index.packages["pkg/lib"].is_main is False
+
+ def test_init_and_build_tag_detection(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "pkg/feat/feat.go",
+ "//go:build linux\n\npackage feat\n\nfunc init() {}\n",
+ )
+ ctx = _ctx(tmp_path, ["pkg/feat/feat.go"], go_modules=(("", "m"),))
+ index = build_go_package_index(ctx)
+ pkg = index.packages["pkg/feat"]
+ assert pkg.has_init is True
+ assert pkg.build_constrained is True
+
+ def test_monorepo_longest_module_prefix(self, tmp_path: Path) -> None:
+ files = ["services/foo/handler.go", "libs/bar/util.go"]
+ for f in files:
+ _write(tmp_path, f, "package p\n")
+ modules = (
+ ("services/foo", "github.com/me/foo"),
+ ("", "github.com/me/root"),
+ )
+ ctx = _ctx(tmp_path, files, go_modules=modules)
+ index = build_go_package_index(ctx)
+ # The nested module's package gets the nested module's import path,
+ # not root/services/foo.
+ assert (
+ index.files_for_import("github.com/me/foo")
+ == ("services/foo/handler.go",)
+ )
+ # A package under the root module resolves via the root prefix.
+ assert (
+ index.files_for_import("github.com/me/root/libs/bar")
+ == ("libs/bar/util.go",)
+ )
+
+ def test_package_for_file(self, tmp_path: Path) -> None:
+ files = ["pkg/lib/a.go", "pkg/lib/b.go"]
+ for f in files:
+ _write(tmp_path, f, "package lib\n")
+ ctx = _ctx(tmp_path, files, go_modules=(("", "m"),))
+ index = build_go_package_index(ctx)
+ pkg = index.package_for_file("pkg/lib/a.go")
+ assert pkg is not None and pkg.dir == "pkg/lib"
+
+ def test_memoised_accessor_caches(self, tmp_path: Path) -> None:
+ _write(tmp_path, "main.go", "package main\n")
+ ctx = _ctx(tmp_path, ["main.go"], go_modules=(("", "m"),))
+ first = get_or_build_go_index(ctx)
+ second = get_or_build_go_index(ctx)
+ assert first is second