Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(dead-code): count Go package-scope and import-qualified uses (#2974)
Raghav Chamadiya3abb2259f71a
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 3347f97ef..b2946b924 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -66,6 +66,7 @@ from .file_reachability import (build_package_file_map,is_file_reachable,)+from .go_name_uses import drop_go_package_usesfrom .kotlin_multiplatform import settle_platform_declarationsfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReportfrom .module_strings import drop_named_modules@@ -978,6 +979,8 @@ class DeadCodeAnalyzer:self._preprocessed_declaration_sites(),self._unindexed_identifier_tokens(),)+ # Same for Go, scoped to the package and to importers naming it.+ findings = drop_go_package_uses(findings, self._source_map, self.graph)# Before the confidence filter, not after: a finding an unread importer# could explain must be able to fall *below* min_confidence and drop# out entirely, rather than being reported at a number it no longerdiff --git a/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py b/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.pyindex ed27d6dd6..f8c468345 100644--- a/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py+++ b/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py@@ -32,7 +32,7 @@ from pathlib import PurePosixPathfrom ...ingestion.languages.registry import REGISTRYfrom .constants import _NON_CODE_LANGUAGES, _PREPROCESSED_LANGUAGES-from .models import DeadCodeFindingData, DeadCodeKind+from .models import DeadCodeFindingData, drop_usedfrom .name_occurrences import IDENTIFIER_RE, occurrence_files#: Kinds a C/C++ type declaration's finding can carry.@@ -205,16 +205,6 @@ class _UseIndex:return self._lines[path]-def _is_candidate(finding: DeadCodeFindingData) -> bool:- """A spanned C/C++ symbol finding."""- return (- finding.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNUSED_INTERNAL)- and bool(finding.symbol_name)- and finding.end_line is not None- and is_preprocessed(finding.file_path)- )--def drop_preprocessed_named_elsewhere(findings: list[DeadCodeFindingData],source_map: Mapping[str, bytes],@@ -227,16 +217,17 @@ def drop_preprocessed_named_elsewhere(*unread_tokens* are the identifiers of files ingestion could not read (a``.def`` EXPORTS list), any of which is a use. Returns a new list."""- candidates = [f for f in findings if _is_candidate(f)]+ candidates = [f for f in findings if f.is_spanned_symbol and is_preprocessed(f.file_path)]if not candidates or not source_map:return findingsnames = {id(f): declared_names(f, source_map.get(f.file_path, b"")) for f in candidates}wanted = {n.encode() for group in names.values() for n in group if n.isascii()}uses = _UseIndex(source_map, wanted, declarations)- dropped = {- id(f)- for f in candidates- if not unread_tokens.isdisjoint(names[id(f)])- or any(uses.written_outside_declarations(f, n) for n in names[id(f)])- }- return [f for f in findings if id(f) not in dropped]++ def is_used(finding: DeadCodeFindingData) -> bool:+ own = names[id(finding)]+ if not unread_tokens.isdisjoint(own):+ return True+ return any(uses.written_outside_declarations(finding, n) for n in own)++ return drop_used(findings, candidates, is_used)diff --git a/packages/core/src/repowise/core/analysis/dead_code/go_name_uses.py b/packages/core/src/repowise/core/analysis/dead_code/go_name_uses.pynew file mode 100644index 000000000..0b0053e19--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/go_name_uses.py@@ -0,0 +1,278 @@+"""A Go symbol named by its package, or by an importer through the package, is used.++Go's unit of visibility is the package: a directory of ``.go`` files sharing a+``package`` clause. Any file of the package names a package-level function or+type bare, with no import, and most such uses carry no graph edge: a parser+passed as a value (``WithParserByGlobs(parsePubspec, ...)``), a lexer state+function returned from another, a handler stored in a sibling file's table.+An importer names it as ``pkg.Name``, which the call graph misses for a generic+instantiation (``pkg.New[T](...)``) and for a build-tag twin, where two files+declare the same function and calls resolve to only one of them.++So for a Go finding, the name written bare in a file of its own package, or+written ``q.Name`` in a file importing the package as ``q``, is a use and the+finding is dropped. It is the Go counterpart of the C/C++ rule in+:mod:`.c_name_uses`, scoped to the package instead of the whole program.++What does not count: the symbol's own span, the header line of any Go+declaration of the same name (a method ``func (e *Exec) New`` or a build-tag+twin), a method's receiver, a method spec of a declared interface, a field name+of a declared struct, a composite-literal key, a selector on something else+(``x.Name`` in the package, or ``y.Name`` under an unrelated qualifier in an+importer), and comments and string literals. A local, a parameter or a field+of an anonymous struct spelled like the symbol still counts: that is the+textual ceiling, and it only ever costs a true finding.+"""++from __future__ import annotations++import re+from collections.abc import Iterator, Mapping+from pathlib import PurePosixPath+from typing import Any++from .models import DeadCodeFindingData, drop_used+from .name_occurrences import IDENTIFIER_RE, occurrence_files++#: Comments and string literals, raw strings included, so ``"http://x"`` and a+#: backquoted struct tag are not read as a comment and a doc comment opening+#: with the function's own name is not read as a use.+_COMMENT_OR_STRING = re.compile(+ rb'`[^`]*`|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|/\*.*?\*/|//[^\n]*', re.DOTALL+)+_PACKAGE_CLAUSE = re.compile(rb"^[ \t]*package[ \t]+([A-Za-z_]\w*)", re.MULTILINE)+_QUALIFIER = re.compile(rb"([A-Za-z_]\w*)$")+#: A default import name taken from a major-version path suffix (``foo/v2``).+#: The package is then named by its own ``package`` clause, not by ``v2``.+_VERSION_SUFFIX = re.compile(r"v\d+")+#: Names a declared type's body declares rather than uses, by the type's kind:+#: an interface's method specs (``Name(...)``) and a struct's field names+#: (``A, B int``). An embedded type, written alone, stays a use.+_MEMBER_NAMES: dict[str, re.Pattern[bytes]] = {+ "interface": re.compile(rb"^\s*([A-Za-z_]\w*)\s*\("),+ "struct": re.compile(rb"^\s*([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*)\s+[^\s/]"),+}+#: A method's receiver: naming a type there declares a method on it, not a use.+_RECEIVER = re.compile(rb"^\s*func\s*\(([^)]*)\)")+#: A composite-literal key or a label (``Name: value``), never a ``case Name:``+#: arm. Neither can be a use of a function or a type, the kinds judged here.+_KEY = re.compile(rb"\s*:(?!=)")+_CASE = re.compile(rb"^\s*case\b")+_NOT_NEWLINE = re.compile(rb"[^\n]")+++def _blank(match: re.Match[bytes]) -> bytes:+ return _NOT_NEWLINE.sub(b" ", match.group())+++def _code_only(blob: bytes) -> bytes:+ """*blob* with comments and string literals blanked; line breaks kept.++ Every string goes, not only prose: Go cannot reach a function or a type+ through its name in a string.+ """+ return _COMMENT_OR_STRING.sub(_blank, blob)+++def _package_dir(path: str) -> str:+ parent = PurePosixPath(path).parent.as_posix()+ return "" if parent == "." else parent+++class _GoUses:+ """Where the candidate names are written, read per file at most once."""++ def __init__(self, source_map: Mapping[str, bytes], graph: Any, wanted: set[bytes]) -> None:+ self._source = source_map+ self._graph = graph+ self._writers = occurrence_files(source_map, wanted)+ self._code: dict[str, bytes] = {}+ self._clauses: dict[str, bytes | None] = {}+ self._headers, self._bodies = _declarations(graph, {w.decode() for w in wanted})++ def code(self, path: str) -> bytes:+ if path not in self._code:+ self._code[path] = _code_only(self._source.get(path, b""))+ return self._code[path]++ def clause(self, path: str) -> bytes | None:+ if path not in self._clauses:+ match = _PACKAGE_CLAUSE.search(self.code(path))+ self._clauses[path] = match.group(1) if match else None+ return self._clauses[path]++ def is_used(self, finding: DeadCodeFindingData) -> bool:+ token = finding.symbol_name.encode()+ own_dir = _package_dir(finding.file_path)+ own_clause = self.clause(finding.file_path)+ qualifiers = self._importer_qualifiers(finding.file_path, own_clause)+ for path in self._writers.get(token, ()):+ if not path.endswith(".go"):+ continue+ if _package_dir(path) == own_dir and self.clause(path) == own_clause:+ if self._written(finding, path, token, None):+ return True+ elif path in qualifiers and self._written(finding, path, token, qualifiers[path]):+ return True+ return False++ def _importer_qualifiers(+ self, path: str, clause: bytes | None+ ) -> dict[str, set[bytes]]:+ """``{importer: qualifiers}`` for the files importing *path*'s package.++ The fan-out gives every file of an imported package the same importers,+ so the declaring file's own import edges are enough. *clause* is the+ package's own name, which an importer writes when the import path ends+ in something else.+ """+ out: dict[str, set[bytes]] = {}+ if not self._graph.has_node(path):+ return out+ for pred in self._graph.predecessors(path):+ names = _qualifiers(self._graph.get_edge_data(pred, path, {}), clause)+ if names:+ out.setdefault(str(pred), set()).update(names)+ return out++ def _written(+ self,+ finding: DeadCodeFindingData,+ path: str,+ token: bytes,+ qualifiers: set[bytes] | None,+ ) -> bool:+ """Whether *path* writes *token* as a use: bare, or after a qualifier."""+ skipped = self._headers.get(finding.symbol_name, {}).get(path, set())+ own_span = (+ range(finding.start_line, finding.end_line + 1)+ if path == finding.file_path+ else range(0)+ )+ bodies = self._bodies.get(path, ())+ return any(+ token in line+ and lineno not in skipped+ and lineno not in own_span+ and _uses_on_line(line, token, _declared_names(line, lineno, bodies), qualifiers)+ for lineno, line in enumerate(self.code(path).split(b"\n"), start=1)+ )+++def _qualifiers(edge: Mapping[str, Any], clause: bytes | None) -> set[bytes]:+ """The names an import edge binds the imported package to, if any.++ The binding extractor records the last path segment when there is no+ alias. That is the package's name only by convention: ``foo/v2`` and+ ``gopkg.in/yaml.v3`` name packages ``foo`` and ``yaml``. An alias is always+ an identifier and never a version, so for any other segment the package's+ own *clause* is the name in use.+ """+ if edge.get("edge_type") != "imports":+ return set()+ names = edge.get("imported_names") or ()+ # A dot import records "*": every export of the package is already+ # counted as imported before this pass, so it needs no qualifier here.+ named = [n for n in names if n != "*"]+ out = {n.encode() for n in named if _is_alias(n)}+ if clause and not all(_is_alias(n) for n in named):+ out.add(clause)+ return out+++def _is_alias(name: str) -> bool:+ """Whether *name* can be what an importer writes before ``.Name``."""+ return name.isascii() and name.isidentifier() and not _VERSION_SUFFIX.fullmatch(name)+++def _uses_on_line(+ line: bytes, token: bytes, declared: set[int], qualifiers: set[bytes] | None+) -> bool:+ """Whether *line* writes *token* as a use rather than as a declaration or key."""+ return any(+ match.group() == token+ and match.start() not in declared+ and not _is_key(line, match.end())+ and _qualified_as(line, match.start(), qualifiers)+ for match in IDENTIFIER_RE.finditer(line)+ )+++def _declared_names(line: bytes, lineno: int, bodies: Any) -> set[int]:+ """Offsets of the names *line* declares: a receiver, or a member of a declared type."""+ match = _RECEIVER.match(line)+ if not match:+ match = next(+ (+ found+ for kind, start, end in bodies+ if start < lineno <= end and (found := _MEMBER_NAMES[kind].match(line))+ ),+ None,+ )+ if not match:+ return set()+ return {m.start() + match.start(1) for m in IDENTIFIER_RE.finditer(match.group(1))}+++def _is_key(line: bytes, end: int) -> bool:+ """Whether the name ending at *end* is a composite-literal key or a label."""+ return bool(_KEY.match(line, end)) and not _CASE.match(line)+++def _qualified_as(line: bytes, start: int, qualifiers: set[bytes] | None) -> bool:+ """Whether the name at *start* is bare (``None``) or follows one of *qualifiers*."""+ dotted = start > 0 and line[start - 1 : start] == b"."+ if qualifiers is None or not dotted:+ return qualifiers is None and not dotted+ head = line[: start - 1]+ match = _QUALIFIER.search(head)+ return bool(match) and match.group(1) in qualifiers and not head[: match.start()].endswith(b".")+++def _declarations(+ graph: Any, names: set[str]+) -> tuple[dict[str, dict[str, set[int]]], dict[str, list[tuple[str, int, int]]]]:+ """Go declarations, from one pass over the graph.++ ``{name: {path: header lines}}`` for every symbol named in *names*, and+ ``{path: [(kind, start, end)]}`` for every interface and struct body.+ """+ headers: dict[str, dict[str, set[int]]] = {}+ bodies: dict[str, list[tuple[str, int, int]]] = {}+ for data in _go_symbols(graph):+ path, start = data["file_path"], data["start_line"]+ if data.get("name") in names:+ headers.setdefault(data["name"], {}).setdefault(path, set()).add(start)+ if data.get("kind") in _MEMBER_NAMES and data.get("end_line"):+ bodies.setdefault(path, []).append((data["kind"], start, data["end_line"]))+ return headers, bodies+++def _go_symbols(graph: Any) -> Iterator[dict]:+ """The data of every Go symbol node with a known first line."""+ for _, data in graph.nodes(data=True):+ if data.get("node_type") != "symbol" or not data.get("start_line"):+ continue+ if (data.get("file_path") or "").endswith(".go"):+ yield data+++def drop_go_package_uses(+ findings: list[DeadCodeFindingData], source_map: Mapping[str, bytes], graph: Any+) -> list[DeadCodeFindingData]:+ """Drop Go symbol findings their package or an importer names. Returns a new list."""+ candidates = [f for f in findings if _is_candidate(f)]+ if not candidates or not source_map:+ return findings+ uses = _GoUses(source_map, graph, {f.symbol_name.encode() for f in candidates})+ return drop_used(findings, candidates, uses.is_used)+++def _is_candidate(finding: DeadCodeFindingData) -> bool:+ """A spanned Go symbol finding whose name the identifier scan can see."""+ return (+ finding.is_spanned_symbol+ and finding.file_path.endswith(".go")+ and finding.symbol_name.isascii()+ )diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.pyindex f01bff6de..70532f15a 100644--- a/packages/core/src/repowise/core/analysis/dead_code/models.py+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom enum import StrEnum@@ -42,6 +43,26 @@ class DeadCodeFindingData:start_line: int | None = Noneend_line: int | None = None+ @property+ def is_spanned_symbol(self) -> bool:+ """A named symbol finding whose declaration lines are known."""+ return (+ self.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNUSED_INTERNAL)+ and bool(self.symbol_name)+ and self.start_line is not None+ and self.end_line is not None+ )+++def drop_used(+ findings: list[DeadCodeFindingData],+ candidates: list[DeadCodeFindingData],+ is_used: Callable[[DeadCodeFindingData], bool],+) -> list[DeadCodeFindingData]:+ """*findings* without the *candidates* that *is_used* holds for. Returns a new list."""+ dropped = {id(f) for f in candidates if is_used(f)}+ return [f for f in findings if id(f) not in dropped]+@dataclassclass DeadCodeReport:diff --git a/tests/unit/dead_code/test_go_name_uses.py b/tests/unit/dead_code/test_go_name_uses.pynew file mode 100644index 000000000..661adb420--- /dev/null+++ b/tests/unit/dead_code/test_go_name_uses.py@@ -0,0 +1,280 @@+"""A Go symbol named by its own package, or by an importer through the package, is used.++Shapes from syft, hugo and gitleaks, each reported as dead: a parser passed as a+value from a sibling file, a lexer state function returned by another, a generic+constructor called as ``pkg.New[T](...)``, and a build-tag twin whose calls+resolve to the other file.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.analysis.dead_code.go_name_uses import drop_go_package_uses+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from tests.unit.dead_code._helpers import _build_graph+++def _finding(path, name, span, kind=DeadCodeKind.UNUSED_INTERNAL):+ start, end = span+ return DeadCodeFindingData(+ kind=kind,+ file_path=path,+ symbol_name=name,+ symbol_kind="function",+ confidence=0.65,+ reason="test",+ last_commit_at=None,+ commit_count_90d=0,+ lines=end - start + 1,+ evidence=[],+ safe_to_delete=False,+ primary_owner=None,+ age_days=None,+ start_line=start,+ end_line=end,+ )+++def _go(path, *symbols):+ return {+ "language": "go",+ "symbols": [+ {"name": n, "kind": "function", "language": "go", "start_line": s, "end_line": e}+ for n, s, e in symbols+ ],+ }+++_PARSER = b"""package dart++// parsePubspec is a parser function for pubspec.yaml contents.+func parsePubspec(path string) error {+\treturn parsePubspec(path)+}+"""+++def _kept(findings, source_map, graph):+ return {f.symbol_name for f in drop_go_package_uses(findings, source_map, graph)}+++def _parser_case(sibling: bytes, sibling_path="dart/cataloger.go"):+ source = {"dart/parse_pubspec.go": _PARSER, sibling_path: sibling}+ graph = _build_graph(+ {"dart/parse_pubspec.go": _go("dart/parse_pubspec.go", ("parsePubspec", 4, 6)),+ sibling_path: {"language": "go"}}+ )+ return _kept([_finding("dart/parse_pubspec.go", "parsePubspec", (4, 6))], source, graph)+++def test_value_passed_from_a_sibling_file_is_a_use():+ sibling = b"package dart\n\nfunc New() C {\n\treturn C{}.WithParserByGlobs(parsePubspec, \"**/pubspec.yaml\")\n}\n"+ assert _parser_case(sibling) == set()+++def test_doc_comment_and_recursive_call_are_not_uses():+ assert _parser_case(b"package dart\n") == {"parsePubspec"}+++def test_comment_and_strings_in_a_sibling_are_not_uses():+ sibling = b'package dart\n\n// see parsePubspec\nvar s = `parsePubspec runs` + "parsePubspec here"\n'+ assert _parser_case(sibling) == {"parsePubspec"}+ one_word = b'package dart\n\nvar s = map[string]int{"parsePubspec": 1, `parsePubspec`: 2}\n'+ assert _parser_case(one_word) == {"parsePubspec"}+++def test_selector_on_something_else_is_not_a_use():+ assert _parser_case(b"package dart\n\nvar f = other.parsePubspec\n") == {"parsePubspec"}+++def test_another_package_in_the_same_directory_is_not_the_package():+ sibling = b"package dart_test\n\nvar f = parsePubspec\n"+ assert _parser_case(sibling, "dart/parse_pubspec_test.go") == {"parsePubspec"}+++def test_another_directory_is_not_the_package():+ assert _parser_case(b"package dart\n\nvar f = parsePubspec\n", "yaml/x.go") == {"parsePubspec"}+++_QUEUE = b"package types\n\nfunc NewEvictingQueue[T any](size int) *Queue[T] {\n\treturn nil\n}\n"+++def _importer_case(importer: bytes, names):+ source = {"common/types/queue.go": _QUEUE, "commands/server.go": importer}+ graph = _build_graph(+ {"common/types/queue.go": _go("common/types/queue.go", ("NewEvictingQueue", 3, 5)),+ "commands/server.go": {"language": "go"}},+ [("commands/server.go", "common/types/queue.go",+ {"edge_type": "imports", "imported_names": names})],+ )+ finding = _finding("common/types/queue.go", "NewEvictingQueue", (3, 5), DeadCodeKind.UNUSED_EXPORT)+ return _kept([finding], source, graph)+++def test_generic_call_through_the_import_qualifier_is_a_use():+ importer = b"package commands\n\nvar q = types.NewEvictingQueue[string](20)\n"+ assert _importer_case(importer, ["types"]) == set()+++def test_aliased_import_qualifier_is_a_use():+ importer = b"package commands\n\nvar q = ht.NewEvictingQueue[string](20)\n"+ assert _importer_case(importer, ["ht"]) == set()+++def test_other_qualifier_or_bare_name_in_an_importer_is_not_a_use():+ importer = b"package commands\n\nvar q = other.NewEvictingQueue[string](20)\nvar r = NewEvictingQueue\n"+ assert _importer_case(importer, ["types"]) == {"NewEvictingQueue"}+++_STDLIB = b"//go:build !re2\n\npackage regexp\n\nfunc MustCompile(s string) *R {\n\treturn nil\n}\n"+_RE2 = b"//go:build re2\n\npackage regexp\n\nfunc MustCompile(s string) *R {\n\treturn nil\n}\n"+++def _twin_case(importer: bytes):+ source = {"regexp/stdlib.go": _STDLIB, "regexp/re2.go": _RE2, "config/rule.go": importer}+ graph = _build_graph(+ {"regexp/stdlib.go": _go("regexp/stdlib.go", ("MustCompile", 5, 7)),+ "regexp/re2.go": _go("regexp/re2.go", ("MustCompile", 5, 7)),+ "config/rule.go": {"language": "go"}},+ [("config/rule.go", "regexp/stdlib.go", {"edge_type": "imports", "imported_names": ["regexp"]}),+ ("config/rule.go", "regexp/re2.go", {"edge_type": "imports", "imported_names": ["regexp"]})],+ )+ finding = _finding("regexp/re2.go", "MustCompile", (5, 7), DeadCodeKind.UNUSED_EXPORT)+ return _kept([finding], source, graph)+++def test_build_tag_twin_shares_the_importers_use():+ assert _twin_case(b"package config\n\nvar r = regexp.MustCompile(`x`)\n") == set()+++def test_build_tag_twin_declaration_alone_is_not_a_use():+ assert _twin_case(b"package config\n") == {"MustCompile"}+++def test_same_named_method_header_is_not_a_use():+ source = {+ "hexec/exec.go": b"package hexec\n\nfunc New() *Exec {\n\treturn nil\n}\n",+ "hexec/run.go": b"package hexec\n\nfunc (e *Exec) New(name string) {\n}\n",+ }+ graph = _build_graph(+ {"hexec/exec.go": _go("hexec/exec.go", ("New", 3, 5)),+ "hexec/run.go": _go("hexec/run.go", ("Exec::New", 3, 4))}+ )+ graph.nodes["hexec/run.go::Exec::New"]["name"] = "New"+ finding = _finding("hexec/exec.go", "New", (3, 5), DeadCodeKind.UNUSED_EXPORT)+ assert _kept([finding], source, graph) == {"New"}+++def test_analyzer_drops_a_go_parser_registered_in_a_sibling():+ source = {+ "dart/parse_pubspec.go": _PARSER.replace(b"// parsePubspec is", b"// It is"),+ "dart/cataloger.go": b"package dart\n\nvar parsers = []P{parsePubspec}\n",+ "dart/unused.go": b"package dart\n\nfunc stale() {\n}\n",+ }+ graph = _build_graph(+ {+ "dart/parse_pubspec.go": _go("dart/parse_pubspec.go", ("parsePubspec", 4, 6)),+ "dart/cataloger.go": {"language": "go"},+ "dart/unused.go": _go("dart/unused.go", ("stale", 3, 4)),+ }+ )+ for node in ("dart/parse_pubspec.go::parsePubspec", "dart/unused.go::stale"):+ graph.nodes[node]["visibility"] = "private"+ report = DeadCodeAnalyzer(graph, source_map=source).analyze(+ {"detect_unreachable_files": False, "detect_zombie_packages": False}+ )+ assert {f.symbol_name for f in report.findings} == {"stale"}+++def _member_case(sibling: bytes, kind: str):+ source = {+ "compare/compare.go": b"package compare\n\nfunc ProbablyEq(a, b any) bool {\n\treturn a == b\n}\n",+ "compare/types.go": sibling,+ }+ graph = _build_graph(+ {"compare/compare.go": _go("compare/compare.go", ("ProbablyEq", 3, 5)),+ "compare/types.go": {"language": "go", "symbols": [+ {"name": "T", "kind": kind, "language": "go", "start_line": 3, "end_line": 6}]}}+ )+ finding = _finding("compare/compare.go", "ProbablyEq", (3, 5), DeadCodeKind.UNUSED_EXPORT)+ return _kept([finding], source, graph)+++def test_interface_method_spec_is_not_a_use():+ sibling = b"package compare\n\ntype T interface {\n\t// For internal use.\n\tProbablyEq(other any) bool\n}\n"+ assert _member_case(sibling, "interface") == {"ProbablyEq"}+++def test_struct_field_name_is_not_a_use_but_its_type_is():+ fields = b"package compare\n\ntype T struct {\n\tProbablyEq, Other int\n\tName ProbablyEq\n}\n"+ assert _member_case(fields, "struct") == set()+ only_field = b"package compare\n\ntype T struct {\n\tProbablyEq, Other int\n\tName string\n}\n"+ assert _member_case(only_field, "struct") == {"ProbablyEq"}+++def test_embedded_type_is_a_use():+ sibling = b"package compare\n\ntype T struct {\n\tProbablyEq\n\tName string\n}\n"+ assert _member_case(sibling, "struct") == set()+++def test_method_receiver_is_not_a_use_but_its_signature_is():+ receiver = b"package compare\n\nfunc (p *ProbablyEq) Name() string {\n\treturn \"\"\n}\n"+ assert _member_case(receiver, "function") == {"ProbablyEq"}+ returns = b"package compare\n\nfunc (p *ProbablyEq) Clone() *ProbablyEq {\n\treturn p\n}\n"+ assert _member_case(returns, "function") == set()+++def test_composite_literal_key_is_not_a_use_but_its_value_and_a_case_arm_are():+ key = b"package compare\n\nvar m = M{\n\tProbablyEq: probablyEq(1),\n}\n"+ assert _member_case(key, "function") == {"ProbablyEq"}+ value = b"package compare\n\nvar m = M{Fn: ProbablyEq}\n"+ assert _member_case(value, "function") == set()+ arm = b"package compare\n\nfunc f(v any) {\n\tswitch v.(type) {\n\tcase *ProbablyEq:\n\t}\n}\n"+ assert _member_case(arm, "function") == set()+++def test_versioned_import_path_is_qualified_by_the_package_clause():+ source = {"lib/v2/queue.go": _QUEUE.replace(b"package types", b"package lib"),+ "app/main.go": b"package app\n\nvar q = lib.NewEvictingQueue[int](1)\n"}+ graph = _build_graph(+ {"lib/v2/queue.go": _go("lib/v2/queue.go", ("NewEvictingQueue", 3, 5)),+ "app/main.go": {"language": "go"}},+ [("app/main.go", "lib/v2/queue.go", {"edge_type": "imports", "imported_names": ["v2"]})],+ )+ finding = _finding("lib/v2/queue.go", "NewEvictingQueue", (3, 5), DeadCodeKind.UNUSED_EXPORT)+ assert _kept([finding], source, graph) == set()+++def test_real_pipeline_dot_import_and_qualified_generic_call(tmp_path):+ root = tmp_path+ # The dot import is covered before this pass ("*" counts every export as+ # imported); the generic call through ``gen.`` has no call edge at all.+ files = {+ "go.mod": "module example.com/m\n\ngo 1.22\n",+ "dot/dot.go": "package dot\n\nfunc DotUsed() int { return 1 }\n",+ "gen/gen.go": (+ "package gen\n\nfunc NewQ[T any](n int) []T { return make([]T, n) }\n\n"+ "func GenDead() int { return 2 }\n"+ ),+ "cmd/app/main.go": (+ 'package main\n\nimport (\n\t. "example.com/m/dot"\n\t"example.com/m/gen"\n)\n\n'+ "func main() {\n\t_ = DotUsed()\n\t_ = gen.NewQ[string](2)\n}\n"+ ),+ }+ for rel, text in files.items():+ (root / rel).parent.mkdir(parents=True, exist_ok=True)+ (root / rel).write_text(text)+ traverser, parser, builder = FileTraverser(root), ASTParser(), GraphBuilder(repo_path=root)+ source_map = {}+ for fi in traverser.traverse():+ source_map[fi.path] = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))+ graph = builder.build()+ assert graph["cmd/app/main.go"]["dot/dot.go"]["imported_names"] == ["*"]+ report = DeadCodeAnalyzer(graph, source_map=source_map).analyze({"min_confidence": 0.0})+ exports = {f.symbol_name for f in report.findings if f.kind is DeadCodeKind.UNUSED_EXPORT}+ assert "GenDead" in exports+ assert not exports & {"DotUsed", "NewQ"}