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): see C# scanned plugins, Swift cross-file uses and Java classes named in resources (#3832)
Raghav Chamadiya103f2fac7ce3
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 75c7c9a60..b888df9c4 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -54,7 +54,11 @@ from .constants import (never_flag_path,)from .contract_methods import is_com_method_implementation, is_contract_method-from .csharp_reachability import build_csharp_named_files, build_csharp_named_types+from .csharp_reachability import (+ build_csharp_named_files,+ build_csharp_named_types,+ scanned_implementations,+)from .deletion_gate import apply_deletion_gatefrom .dynamic_markers import (find_dynamic_edge_files,@@ -101,6 +105,7 @@ from .risk_factors import (path_risk_factors,risk_evidence,)+from .swift_reachability import build_swift_named_filesfrom .vbnet_modules import vbnet_module_names#: The unindexed scan below and the repo-wide absence check ask the same@@ -880,6 +885,10 @@ class DeadCodeAnalyzer:# scopes the C# name rescue to the projects that can see a file.self._dotnet_index = dotnet_indexself._csharp_named_files: frozenset[str] | None = None+ self._swift_named_files: frozenset[str] | None = None+ # C# classes a plugin host or container finds by type, built on first use.+ self._csharp_discovered: frozenset[tuple[str, str]] | None = None+ self._parsed_files = parsed_files or {}self.git_meta_map = git_meta_map or {}# Source files ingestion could not read (currently: dropped on size).# An unread importer is invisible to the graph, so "no importers" stops@@ -961,6 +970,14 @@ class DeadCodeAnalyzer:self._meta_annotations = MetaAnnotations(self._source_map, _is_framework_registered)return self._meta_annotations.visible_in(path)+ def _csharp_discovered_classes(self) -> frozenset[tuple[str, str]]:+ """``(file, class)`` the runtime instantiates by type; see :func:`scanned_implementations`."""+ if self._csharp_discovered is None:+ self._csharp_discovered = scanned_implementations(+ self.graph, self._source_map, self._parsed_files+ )+ return self._csharp_discovered+def _reachability_rescues(self, whitelist: AbstractSet[str]) -> ReachabilityRescues:"""Assemble the rescue state the shared predicate reads."""if self._package_files is None:@@ -971,12 +988,16 @@ class DeadCodeAnalyzer:self._source_map,dotnet_index=self._dotnet_index,repo_root=self._repo_root,+ discovered=self._csharp_discovered_classes(),)+ if self._swift_named_files is None:+ self._swift_named_files = build_swift_named_files(self.graph, self._source_map)return ReachabilityRescues(bundler_alias_targets=frozenset(self._bundler_alias_targets),whitelist=frozenset(whitelist),package_files=self._package_files,csharp_named_files=self._csharp_named_files,+ swift_named_files=self._swift_named_files,)def analyze(@@ -1096,6 +1117,7 @@ class DeadCodeAnalyzer:_names_by_file(exports),dotnet_index=self._dotnet_index,repo_root=self._repo_root,+ discovered=self._csharp_discovered_classes(),)dropped = {id(f) for f in exports if (f.file_path, f.symbol_name) in named}demote_used_in_own_file([f for f in exports if id(f) not in dropped], self._source_map)diff --git a/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.pyindex 6e6ef82ff..2de868346 100644--- a/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py+++ b/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py@@ -31,6 +31,13 @@ A file linked into another project by ``<Compile Include>`` is visible fromthat project too. Ceiling: items pulled in through ``.projitems`` / ``.props``imports or wildcards, and reflection by a computed name, are not seen. Bothleave a finding as it was before this pass existed.++A plugin host names no implementation at all: ``GetExports<IScheduledTask>()``+instantiates every loaded type assignable to the interface. A concrete class+that inherits, directly or transitively, from a type passed to one of the+scanning call shapes in :func:`scanned_implementations`, or that MEF exports,+counts as named too. A DI registration that names the implementation+(``AddScoped<IFoo, Foo>()``) needs no rule: the name rescue already sees it."""from __future__ import annotations@@ -81,6 +88,52 @@ _ASSEMBLY_EFFECT = re.compile()+#: Calls that instantiate or register every type assignable to the type they+#: name, so no source names the implementations. Deliberately explicit: the+#: jellyfin/Emby plugin host (``GetExports<T>``, ``GetExportTypes<T>``), MEF+#: (``GetExportedValues<T>``), Scrutor (``AssignableTo<T>()``,+#: ``AssignableTo(typeof(T))``) and the hand-written reflection loop+#: (``typeof(T).IsAssignableFrom``, ``t.IsAssignableTo(typeof(T))``).+#: Group 1 is the type's name, namespace-qualified or not.+#: The NUnit constraint ``Is.AssignableTo<T>()`` is an assertion, not a scan,+#: and FluentAssertions' ``BeAssignableTo<T>()`` never meets the word boundary.+_SCANNING_CALL = re.compile(+ rb"\b(?:GetExports|GetExportTypes|GetExportedValues|(?<!Is\.)AssignableTo)"+ rb"\s*<\s*([A-Za-z_][\w.]*)"+ rb"|\btypeof\s*\(\s*([A-Za-z_][\w.]*)[^()]*\)\s*\.\s*IsAssignableFrom\b"+ rb"|\b(?:IsAssignableTo|(?<!Is\.)AssignableTo)\s*\(\s*typeof\s*\(\s*([A-Za-z_][\w.]*)"+)+_SCANNING_HINTS: tuple[bytes, ...] = (b"GetExport", b"Assignable")+#: Framework types nearly any class is assignable to. A scan over one of them+#: (``typeof(IDisposable).IsAssignableFrom`` in a cleanup loop) says nothing+#: about which plugin types a host loads, and would rescue every implementer+#: in the repository. Any ``System.``-qualified name is skipped too.+_UNSCANNED_TYPES: frozenset[str] = frozenset(+ {+ "IDisposable",+ "IAsyncDisposable",+ "IComparable",+ "IEquatable",+ "IEnumerable",+ "ICloneable",+ "Exception",+ "Attribute",+ "object",+ "Object",+ "Task",+ "Stream",+ "ValueType",+ }+)+#: MEF attributes: ``[Export]`` on a class exports it, ``[InheritedExport]`` on+#: a base type exports every type deriving from it.+_EXPORT_ATTRIBUTES: frozenset[str] = frozenset({"Export", "ExportAttribute"})+_INHERITED_EXPORT_ATTRIBUTES: frozenset[str] = frozenset(+ {"InheritedExport", "InheritedExportAttribute"}+)+_HERITAGE_EDGE_TYPES: frozenset[str] = frozenset({"extends", "implements"})++def _code_only(blob: bytes) -> bytes:"""*blob* with C-style comments replaced by a space; strings kept."""if b"/" not in blob:@@ -324,13 +377,15 @@ def build_csharp_named_files(*,dotnet_index: Any | None = None,repo_root: Path | None = None,+ discovered: AbstractSet[tuple[str, str]] = frozenset(),) -> frozenset[str]:"""The C# files with no importer that something names.One pass over the scanned corpus, collecting only the names some candidatedeclares, so the cost is linear in source size whatever the candidatecount. With no .NET index the scope is the whole repository, which is the- wider and therefore safer rescue.+ wider and therefore safer rescue. *discovered* is+ :func:`scanned_implementations`: their files count as named."""candidates = _candidates(graph)if not source_map and dotnet_index is None:@@ -349,7 +404,8 @@ def build_csharp_named_files(continuenames.add(path, {name: path for name in types}, {name: path for name in extensions})names.scan_corpus(graph, source_map, dotnet_index, repo_root)- return frozenset(assembly_level | names.named)+ found = {path for path, _name in discovered}+ return frozenset(assembly_level | names.named | found.intersection(candidates))def build_csharp_named_types(@@ -359,6 +415,7 @@ def build_csharp_named_types(*,dotnet_index: Any | None = None,repo_root: Path | None = None,+ discovered: AbstractSet[tuple[str, str]] = frozenset(),) -> frozenset[tuple[str, str]]:"""The ``(path, name)`` pairs of *wanted* that another file in scope names.@@ -366,8 +423,10 @@ def build_csharp_named_types(scope and the same rules, asked of one top-level type at a time: *wanted*maps a ``.cs`` file to the public types the unused-export pass wouldreport there. A holder class counts as named when one of its extension- methods is invoked as a member. With no source at all nothing is named,- which leaves every finding as it was before this pass.+ methods is invoked as a member, and a *discovered* class+ (:func:`scanned_implementations`) is named by the runtime. With no source+ at all nothing is named, which leaves every finding as it was before this+ pass."""if not source_map and dotnet_index is None:return frozenset()@@ -387,7 +446,116 @@ def build_csharp_named_types()names.add(path, types, extensions)names.scan_corpus(graph, source_map, dotnet_index, repo_root)- return frozenset(names.named)+ found = {pair for pair in discovered if pair[1] in wanted.get(pair[0], ())}+ return frozenset(names.named | found)+++def _attribute_bases(data: dict) -> set[str]:+ """``Export`` for ``[System.ComponentModel.Composition.Export(typeof(I))]``."""+ return {+ str(text).split("(", 1)[0].strip().rsplit(".", 1)[-1]+ for text in data.get("decorators") or ()+ }+++def _simple_type_name(name: str) -> str:+ """``IFoo`` for ``Ns.IFoo<A, B>``: generic arguments and namespace dropped."""+ return name.split("<", 1)[0].strip().rsplit(".", 1)[-1]+++def _scanned_type_names(graph: Any, source_map: Mapping[str, bytes]) -> set[str]:+ """Simple names of the types a scanning call shape collects implementations of.++ Test files are not read: a test that scans an assembly checks the host, it+ does not load plugins.+ """+ names: set[str] = set()+ for path, blob in source_map.items():+ if not path.endswith(CSHARP_SUFFIX) or not any(h in blob for h in _SCANNING_HINTS):+ continue+ if graph.nodes.get(path, {}).get("is_test", False):+ continue+ for match in _SCANNING_CALL.finditer(_code_only(blob)):+ raw = next(group for group in match.groups() if group).decode("utf-8", "ignore")+ name = _simple_type_name(raw)+ if not raw.startswith("System.") and name not in _UNSCANNED_TYPES:+ names.add(name)+ return names+++def _heritage_names(graph: Any, parsed_files: Mapping[str, Any]) -> dict[tuple[str, str], set[str]]:+ """``{(file, type name): its base type names}`` for C# types.++ Read from the parsed relations as well as the graph's heritage edges: the+ resolver leaves a generic base (``IRemoteMetadataProvider<Episode,+ EpisodeInfo>``) unresolved when the name has generic and plain+ declarations, and that is exactly the plugin interface shape.+ """+ out: dict[tuple[str, str], set[str]] = {}+ for path, parsed in parsed_files.items():+ if path.endswith(CSHARP_SUFFIX):+ for rel in getattr(parsed, "heritage", ()) or ():+ out.setdefault((path, rel.child_name), set()).add(+ _simple_type_name(rel.parent_name)+ )+ for child, parent, edge in graph.edges(data=True):+ if edge.get("edge_type") not in _HERITAGE_EDGE_TYPES:+ continue+ data = graph.nodes.get(child, {})+ if data.get("language") == "csharp" and data.get("name"):+ name = graph.nodes.get(parent, {}).get("name")+ if name:+ out.setdefault((data.get("file_path") or "", data["name"]), set()).add(name)+ return out+++def scanned_implementations(+ graph: Any, source_map: Mapping[str, bytes], parsed_files: Mapping[str, Any] | None = None+) -> frozenset[tuple[str, str]]:+ """``(file, class)`` for each concrete C# class the runtime discovers by type.++ A class qualifies when it inherits, directly or transitively, from a type a+ scanning call names (:data:`_SCANNING_CALL`), carries MEF ``[Export]``, or+ derives from a type carrying ``[InheritedExport]``. Above the class itself+ the walk is by simple name, so same-named bases union their parents, and a+ type parameter (``GetExports<T>`` inside the host's own generic method)+ matches nothing: a wider match only widens a rescue.+ """+ bases = _scanned_type_names(graph, source_map)+ classes: list[dict] = []+ for _node, data in graph.nodes(data=True):+ if data.get("node_type") != "symbol" or data.get("language") != "csharp":+ continue+ kind = data.get("kind")+ if kind not in _TYPE_KINDS:+ continue+ attributes = _attribute_bases(data)+ if attributes & _INHERITED_EXPORT_ATTRIBUTES:+ bases.add(data.get("name") or "")+ if kind in ("class", "record") and not {"abstract", "static"} & set(+ data.get("modifiers") or ()+ ):+ classes.append(data)+ exported = [d for d in classes if _attribute_bases(d) & _EXPORT_ATTRIBUTES]+ out = {(d.get("file_path") or "", d.get("name") or "") for d in exported}+ if not bases:+ return frozenset(out)+ heritage = _heritage_names(graph, parsed_files or {})+ by_name: dict[str, set[str]] = {}+ for (_path, name), parents in heritage.items():+ by_name.setdefault(name, set()).update(parents)+ for data in classes:+ key = (data.get("file_path") or "", data.get("name") or "")+ seen = set(heritage.get(key, ()))+ stack = list(seen)+ while stack and not seen & bases:+ for parent in by_name.get(stack.pop(), ()):+ if parent not in seen:+ seen.add(parent)+ stack.append(parent)+ if seen & bases:+ out.add(key)+ return frozenset(out)def _extension_holders(graph: Any, path: str) -> Iterable[tuple[bytes, str]]:diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.pyindex 164bab139..f25baa4b4 100644--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py@@ -61,6 +61,8 @@ _JVM_SUFFIXES: tuple[str, ...] = (".java", ".kt")CSHARP_SUFFIX = ".cs"+_SWIFT_SUFFIX = ".swift"+#: Objective-C implementation files, which no source ever imports._OBJC_SOURCE_SUFFIXES: tuple[str, ...] = (".m", ".mm")@@ -137,6 +139,10 @@ class ReachabilityRescues:#: so ``None`` is "not checked" and, like ``package_files``, resolves a#: ``.cs`` file to reachable.csharp_named_files: AbstractSet[str] | None = None+ #: Swift files with no importer that a use edge, a type name or an extended+ #: type reaches (see :mod:`swift_reachability`). ``None`` is "not checked"+ #: and resolves a ``.swift`` file to reachable, as for C#.+ swift_named_files: AbstractSet[str] | None = None#: Prefix of an :class:`repowise.core.ids.ExternalId`, matched textually rather@@ -317,5 +323,9 @@ def is_file_reachable(rescues.csharp_named_files is None or path in rescues.csharp_named_files):return True+ if path.endswith(_SWIFT_SUFFIX) and (+ rescues.swift_named_files is None or path in rescues.swift_named_files+ ):+ return Truereturn has_dependency_importer(graph, path)diff --git a/packages/core/src/repowise/core/analysis/dead_code/swift_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/swift_reachability.pynew file mode 100644index 000000000..67ed65726--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/swift_reachability.py@@ -0,0 +1,239 @@+"""Name-granular reachability for Swift.++Swift imports name a module, never a file. Files of one module see each other+with no import at all, and ``import DesignSystem`` from another package+resolves to a single file of that target. So ``in_degree == 0`` on a ``.swift``+file is mostly a property of the language: on IceCubesApp none of 30 judged+"unreachable" files was dead.++A Swift file nothing imports is reachable here when a *live* file (one that is+an entry, has an importer, is a test, or was itself reached) does one of:++* lands a use edge on a symbol the file declares (``TagRowView(tag:)`` lands a+ ``calls`` edge on the type, not on its file);+* writes a type the file declares in a type position: after ``:``, ``<``,+ ``[``, ``(``, ``,``, ``->``, ``as`` or ``is``, or followed by ``(`` or ``.``+ (``[StatusHistory]``, ``catch let error as ServerError``). Only a name one+ file of the repository declares counts, and never a ubiquitous+ Swift/Foundation/SwiftUI name, since the text cannot tell which one it means;+* for an extension of a type the repository declares, is the type's file; for+ an extension of a platform type (``extension Color``), uses one of the+ extension's members, by an edge or by ``.member`` / ``member(`` written+ elsewhere, when no other file declares that member name.++Uses are counted from live files only and the answer is a fixpoint, so two dead+files that name each other stay dead. Comments and string literals are+stripped before reading names. Like the C# pass it only rescues. Ceiling: a+principal class named only by an ``Info.plist`` or a storyboard, and a file+listed only in ``project.pbxproj``, are not seen.+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Mapping+from typing import Any++from repowise.core.ids import file_path_of, is_external++from ...entry_candidacy import is_reachability_root+from ...ingestion.languages.swift_same_module import _SWIFT_COMMON_TYPES+from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES+from .file_reachability import has_dependency_importer++SWIFT_SUFFIX = ".swift"++#: Top-level declarations: ``struct``/``class``/``enum``/``actor`` are emitted+#: as ``class``, a ``protocol`` as ``interface``, an ``extension`` as ``impl``.+_TYPE_KINDS: frozenset[str] = frozenset({"class", "interface"})+_EXTENSION_KIND = "impl"++_NAME = r"[^\W\d]\w*"+#: A name in a type position: the last component of an optionally qualified+#: name after a type-introducing token, or a name followed by ``(`` or ``.``.+_TYPE_USE = re.compile(+ rf"(?:[:<\[(,]|->|\bas[?!]?|\bis)\s*(?:{_NAME}\s*\.\s*)*({_NAME})|\b({_NAME})\s*[(.]"+)+#: A member written as ``.member`` or called as ``member(``.+_MEMBER_USE = re.compile(rf"\.\s*({_NAME})|\b({_NAME})\s*\(")+++def strip_comments_and_strings(text: str) -> str:+ """*text* with Swift comments and string literals blanked to spaces.++ Handles nested ``/* */`` comments, ``\"\"\"`` multi-line strings and raw+ strings (``#"..."#``, any number of ``#``). Interpolations inside a string+ are blanked with it, which only costs a rescue.+ """+ out: list[str] = []+ i, n = 0, len(text)+ while i < n:+ if text.startswith("//", i):+ end = text.find("\n", i)+ i = n if end < 0 else end+ continue+ if text.startswith("/*", i):+ depth, i = 1, i + 2+ while i < n and depth:+ if text.startswith("/*", i):+ depth, i = depth + 1, i + 2+ elif text.startswith("*/", i):+ depth, i = depth - 1, i + 2+ else:+ i += 1+ out.append(" ")+ continue+ hashes = 0+ while i + hashes < n and text[i + hashes] == "#":+ hashes += 1+ quote = i + hashes+ if quote < n and text[quote] == '"':+ delim = '"""' if text.startswith('"""', quote) else '"'+ close = delim + "#" * hashes+ j = quote + len(delim)+ while j < n and not text.startswith(close, j):+ j += 2 if text[j] == "\\" and not hashes else 1+ i = min(n, j + len(close))+ out.append(" ")+ continue+ out.append(text[i])+ i += 1+ return "".join(out)+++def _names(pattern: re.Pattern[str], text: str) -> set[str]:+ return {a or b for a, b in pattern.findall(text)}+++def _top_level(graph: Any, path: str) -> Iterable[dict]:+ for _path, symbol, edge in graph.out_edges(path, data=True):+ if edge.get("edge_type") == "defines":+ data = graph.nodes.get(symbol, {})+ if not data.get("parent_name") and data.get("name"):+ yield data+++def _defined(graph: Any, path: str) -> Iterable[tuple[str, dict]]:+ for _path, symbol, edge in graph.out_edges(path, data=True):+ if edge.get("edge_type") == "defines":+ yield symbol, graph.nodes.get(symbol, {})+++def _swift_files(graph: Any) -> list[str]:+ return [+ node+ for node, data in graph.nodes(data=True)+ if isinstance(node, str)+ and node.endswith(SWIFT_SUFFIX)+ and data.get("node_type", "file") == "file"+ ]+++class _SwiftFacts:+ """Declarations and name uses of every Swift file, read once."""++ def __init__(self, graph: Any, source_map: Mapping[str, bytes], files: list[str]) -> None:+ self.declares: dict[str, set[str]] = {} # type name -> declaring files+ self.declared: dict[str, set[str]] = {} # file -> type names it declares+ self.extends: dict[str, set[str]] = {} # file -> extended type names+ self.members: dict[str, set[str]] = {} # file -> its extensions' member names+ self.member_files: dict[str, set[str]] = {} # any symbol name -> declaring files+ self.own: dict[str, set[str]] = {} # file -> names it declares or extends+ self.type_users: dict[str, set[str]] = {} # name -> files writing it as a type+ self.member_users: dict[str, set[str]] = {} # name -> files writing it as a member+ for path in files:+ for data in _top_level(graph, path):+ if data.get("kind") == _EXTENSION_KIND:+ name = data["name"].rsplit(".", 1)[-1]+ self.extends.setdefault(path, set()).add(name)+ self.own.setdefault(path, set()).add(name)+ extended = self.extends.get(path, set())+ for _symbol, data in _defined(graph, path):+ name = (data.get("name") or "").strip("`") # ``func `if`()``+ if not name:+ continue+ self.member_files.setdefault(name, set()).add(path)+ # Nested types too: ``StatusEditor.EditorStore`` is declared+ # inside an extension of ``StatusEditor``.+ if data.get("kind") in _TYPE_KINDS:+ self.declares.setdefault(name, set()).add(path)+ self.declared.setdefault(path, set()).add(name)+ self.own.setdefault(path, set()).add(name)+ if (data.get("parent_name") or "").rsplit(".", 1)[-1] in extended:+ self.members.setdefault(path, set()).add(name)+ blob = source_map.get(path)+ if blob is None:+ continue+ text = strip_comments_and_strings(blob.decode("utf-8", "ignore"))+ for name in _names(_TYPE_USE, text):+ self.type_users.setdefault(name, set()).add(path)+ for name in _names(_MEMBER_USE, text):+ self.member_users.setdefault(name, set()).add(path)+++def build_swift_named_files(graph: Any, source_map: Mapping[str, bytes]) -> frozenset[str]:+ """The Swift files with no importer that a live file uses, names or extends.++ Starts from the files that are live on their own (an entry, an importer, a+ test) and adds a candidate only when a file already live reaches it, until+ nothing changes. With no source at all every candidate is returned:+ unchecked is reachable, the answer ``ReachabilityRescues`` gives a caller+ that cannot check.+ """+ files = _swift_files(graph)+ candidates = {+ path+ for path in files+ if not is_reachability_root(graph.nodes[path])+ and not graph.nodes[path].get("is_test", False)+ and not has_dependency_importer(graph, path)+ }+ if not source_map:+ return frozenset(candidates)+ facts = _SwiftFacts(graph, source_map, files)+ reached: set[str] = set()++ def live(path: str) -> bool:+ return path not in candidates or path in reached++ def used_by_live(path: str) -> bool:+ for symbol, _data in _defined(graph, path):+ for user, _symbol, use in graph.in_edges(symbol, data=True):+ if use.get("edge_type") not in REACHABILITY_USE_EDGE_TYPES or is_external(user):+ continue+ source = file_path_of(user)+ if source != path and live(source):+ return True+ return False++ def named_by_live(path: str) -> bool:+ for name in facts.declared.get(path, ()):+ if len(facts.declares.get(name, ())) != 1 or name in _SWIFT_COMMON_TYPES:+ continue+ for user in facts.type_users.get(name, ()):+ if user != path and live(user) and name not in facts.own.get(user, ()):+ return True+ return False++ def extends_live(path: str) -> bool:+ for name in facts.extends.get(path, ()):+ owners = facts.declares.get(name, set()) - {path}+ if owners:+ if any(live(owner) for owner in owners):+ return True+ continue+ for member in facts.members.get(path, ()):+ if facts.member_files.get(member, set()) != {path}:+ continue+ if any(u != path and live(u) for u in facts.member_users.get(member, ())):+ return True+ return False++ changed = True+ while changed:+ changed = False+ for path in sorted(candidates - reached):+ if used_by_live(path) or named_by_live(path) or extends_live(path):+ reached.add(path)+ changed = True+ return frozenset(reached)diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 5257656fd..a80cae60f 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -92,7 +92,7 @@ def _default_package_definers(graph: Any, index: Any, names: set[str]) -> set[stdef _warmup_jvm(ctx: ResolverContext) -> None:- from .resolvers.jvm_workspace import get_or_build_jvm_index+ from .resolvers.jvm_workspace import get_or_build_jvm_index, resource_class_namesindex = get_or_build_jvm_index(ctx)graph = getattr(ctx, "graph", None)@@ -116,6 +116,9 @@ def _warmup_jvm(ctx: ResolverContext) -> None:from .resolvers.jvm_gradle import build_script_class_namesentry_fqns.update(build_script_class_names(ctx))+ # Classes a main resource file names for a framework to load (Hibernate,+ # H2 aliases, MyBatis type handlers, P6Spy).+ entry_fqns.update(resource_class_names(ctx))root_paths = {path for fqn in entry_fqns for path in index.files_for_fqn(fqn)}# A bare name is a default-package class, which the index does not key.diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.pyindex 75da41cdc..ce32b321e 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py@@ -517,6 +517,64 @@ def _scan_spring_autoconfig(return {k: tuple(v) for k, v in result.items()}+#: Runtime resource files that name a class for a framework to load: Hibernate+#: ``metadata_builder_contributor`` in ``application.yml``, an H2 ``CREATE+#: ALIAS ... FOR "pkg.Cls.method"`` in an init ``.sql``, a MyBatis+#: ``typeHandler=`` in a mapper ``.xml``, a P6Spy ``logMessageFormat=`` in a+#: ``.properties``. Main resources only: a class named by test resources alone+#: is not live code.+_RESOURCE_CLASS_FILES: tuple[str, ...] = tuple(+ f"src/main/resources/*{suffix}" for suffix in (".xml", ".yml", ".yaml", ".properties", ".sql")+)+#: A dotted name ending in a capitalised segment: ``com.acme.db.JsonTypeHandler``,+#: also out of ``com.acme.db.JsonTypeHandler.parse``. Only a name that resolves+#: to a class in the repository counts, so a framework FQN matches nothing.+_RESOURCE_FQN_RE = re.compile(r"(?<![\w.$])((?:[a-z_][a-z0-9_]*\.)+[A-Z][A-Za-z0-9_]*)")+#: Comments per resource format: a class named only in one is not loaded.+#: XML ``<!-- -->``; YAML ``#`` at a line start or after whitespace;+#: ``.properties`` comment lines (``#`` or ``!``); SQL ``--`` and ``/* */``.+_YAML_COMMENT_RE = re.compile(r"(?:^|(?<=\s))#[^\n]*")+_RESOURCE_COMMENT_RE: dict[str, re.Pattern[str]] = {+ ".xml": re.compile(r"<!--.*?-->", re.DOTALL),+ ".yml": _YAML_COMMENT_RE,+ ".yaml": _YAML_COMMENT_RE,+ ".properties": re.compile(r"^[ \t]*[#!][^\n]*", re.MULTILINE),+ ".sql": re.compile(r"--[^\n]*|/\*.*?\*/", re.DOTALL),+}+#: Data dumps (a seed ``.sql`` of many megabytes) are skipped unread.+#: Ceiling: a class named only inside such a file is missed.+_RESOURCE_MAX_BYTES = 1_000_000+++def resource_class_names(ctx: ResolverContext) -> set[str]:+ """Fully qualified class names written in a module's main resource files.++ The resource-file counterpart of ``META-INF/services`` and of the Gradle+ names in ``jvm_gradle.build_script_class_names``: a framework reads the+ name and loads the class by reflection, so no source refers to it.+ """+ names: set[str] = set()+ if ctx.repo_path is None:+ return names+ for resource in glob_via(+ getattr(ctx, "walk_snapshot", None),+ ctx.repo_path,+ _RESOURCE_CLASS_FILES,+ prune_nested_git=ctx.prune_nested_git,+ ):+ try:+ if resource.stat().st_size > _RESOURCE_MAX_BYTES:+ continue+ text = resource.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ comments = _RESOURCE_COMMENT_RE.get(resource.suffix.lower())+ if comments is not None:+ text = comments.sub(" ", text)+ names.update(_RESOURCE_FQN_RE.findall(text))+ return names++def build_jvm_workspace_index(ctx: ResolverContext) -> JvmWorkspaceIndex:"""Build the JVM workspace index from all ``.java`` and ``.kt`` files in the path set.diff --git a/tests/unit/dead_code/test_csharp_file_confidence.py b/tests/unit/dead_code/test_csharp_file_confidence.pyindex 98f769dd0..0b98b5738 100644--- a/tests/unit/dead_code/test_csharp_file_confidence.py+++ b/tests/unit/dead_code/test_csharp_file_confidence.py@@ -73,22 +73,23 @@ def test_type_listed_in_a_reference_assembly_is_never_dead():def test_file_whose_type_another_file_names_is_capped():- # A Swift type is used across its module without an import.- path = "Sources/App/FilterType.swift"- user = "Sources/App/FilterRef.swift"+ # A Kotlin type is used from another package by its name alone. (A Swift+ # file in the same position is reachable outright: test_swift_reachability.)+ path = "core/src/main/kotlin/org/app/model/FilterType.kt"+ user = "app/src/main/kotlin/org/app/ui/FilterRef.kt"report = _analyze({- path: {"language": "swift", "symbols": [_cls("FilterType", "swift")]},- user: {"language": "swift", "is_entry_point": True},+ path: {"language": "kotlin", "symbols": [_cls("FilterType", "kotlin")]},+ user: {"language": "kotlin", "is_entry_point": True},},{- path: b"import Foundation\n\npublic enum FilterType { case a }\n",- user: b"struct FilterRef { var t: FilterType }\n",+ path: b"package org.app.model\n\nenum class FilterType { A }\n",+ user: b"package org.app.ui\n\nclass FilterRef(val t: FilterType)\n",},)finding = _file_finding(report, path)assert finding.confidence == pytest.approx(RISK_CAP_CONFIDENCE)- assert any("FilterRef.swift" in line for line in finding.evidence)+ assert any("FilterRef.kt" in line for line in finding.evidence)def test_file_whose_types_nothing_names_keeps_its_age_score():diff --git a/tests/unit/dead_code/test_csharp_scanned_roots.py b/tests/unit/dead_code/test_csharp_scanned_roots.pynew file mode 100644index 000000000..abab43401--- /dev/null+++ b/tests/unit/dead_code/test_csharp_scanned_roots.py@@ -0,0 +1,187 @@+"""C# classes a plugin host or container finds by type are not dead.++Shapes from jellyfin: ``ApplicationHost.GetExports<IScheduledTask>()``+instantiates every loaded type assignable to the interface, so no file names+``DeleteLogFileTask``. Its metadata providers implement a generic interface+(``IRemoteMetadataProvider<Episode, EpisodeInfo>``) whose name also has generic+and plain declarations, which the heritage resolver leaves unresolved. Plus the+Scrutor, reflection-loop and MEF spellings, and the controls that keep the+rescue from hiding a class nothing discovers.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.csharp_reachability import (+ _scanned_type_names,+ _simple_type_name,+)+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_FILES = {+ "Model/IScheduledTask.cs": "namespace Model;\npublic interface IScheduledTask { void Run(); }\n",+ "Model/IMetadataProvider.cs": (+ "namespace Model;\n"+ "public interface IMetadataProvider { string Name { get; } }\n"+ "public interface IMetadataProvider<TItem> : IMetadataProvider {}\n"+ ),+ "Model/IRemoteMetadataProvider.cs": (+ "namespace Model;\n"+ "public interface IRemoteMetadataProvider : IMetadataProvider {}\n"+ "public interface IRemoteMetadataProvider<TItem, TInfo> : IMetadataProvider<TItem>, "+ "IRemoteMetadataProvider {}\n"+ ),+ "Model/IUnscanned.cs": "namespace Model;\npublic interface IUnscanned { void Go(); }\n",+ "Host/ApplicationHost.cs": (+ "namespace Host;\nusing Model;\n"+ "public class ApplicationHost {\n"+ " public void Start() {\n"+ " var tasks = GetExports<IScheduledTask>(false);\n"+ " var providers = GetExports<Model.IMetadataProvider>();\n"+ " }\n"+ " public T[] GetExports<T>(bool manage = true) => new T[0];\n"+ "}\n"+ ),+ "Tasks/DeleteLogFileTask.cs": (+ "namespace Tasks;\nusing Model;\n"+ "public class DeleteLogFileTask : IScheduledTask { public void Run() {} }\n"+ ),+ "Tasks/BaseTask.cs": (+ "namespace Tasks;\nusing Model;\n"+ "public abstract class BaseTask : IScheduledTask { public abstract void Run(); }\n"+ ),+ "Tasks/OptimizeTask.cs": (+ "namespace Tasks;\npublic class OptimizeTask : BaseTask { public override void Run() {} }\n"+ ),+ "Providers/TmdbEpisodeProvider.cs": (+ "namespace Providers;\nusing Model;\n"+ "public class TmdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>\n"+ "{\n public string Name => \"Tmdb\";\n}\n"+ ),+ "Plugins/Scan.cs": (+ "namespace Plugins;\n"+ "public interface IHandler {}\npublic interface IPlugin {}\n"+ "public static class Scan {\n"+ " public static void Wire(object services, System.Type[] types) {\n"+ " services.Scan(s => s.AddClasses(c => c.AssignableTo<IHandler>()));\n"+ " foreach (var t in types) { if (typeof(IPlugin).IsAssignableFrom(t)) {} }\n"+ " }\n"+ "}\n"+ ),+ "Plugins/OrderHandler.cs": "namespace Plugins;\npublic class OrderHandler : IHandler {}\n",+ "Plugins/AudioPlugin.cs": "namespace Plugins;\npublic class AudioPlugin : IPlugin {}\n",+ "Plugins/ExportedPart.cs": (+ "namespace Plugins;\n[System.ComponentModel.Composition.Export(typeof(object))]\n"+ "public class ExportedPart {}\n"+ ),+ "Unused/OrphanTask.cs": (+ "namespace Unused;\nusing Model;\npublic class OrphanTask : IUnscanned { public void Go() {} }\n"+ ),+ # Same simple name as the discovered task, implementing nothing.+ "Other/DeleteLogFileTask.cs": "namespace Other;\npublic class DeleteLogFileTask {}\n",+ # Scans over framework types say nothing about plugins.+ "Host/Cleanup.cs": (+ "namespace Host;\npublic static class Cleanup {\n"+ " public static void Run(System.Type t, object c) {\n"+ " if (typeof(IDisposable).IsAssignableFrom(t)) {}\n"+ " var all = c.GetExports<System.IComparable>();\n"+ " }\n}\n"+ ),+ "Unused/DisposableThing.cs": (+ "namespace Unused;\npublic class DisposableThing : IDisposable { public void Dispose() {} }\n"+ ),+ "Unused/ComparableThing.cs": (+ "namespace Unused;\npublic class ComparableThing : IComparable "+ "{ public int CompareTo(object o) => 0; }\n"+ ),+ # A test scanning its host, and an NUnit assertion, load nothing.+ "Model/ITestOnly.cs": "namespace Model;\npublic interface ITestOnly {}\npublic interface INunit {}\n",+ "tests/HostTests.cs": (+ "namespace Tests;\nusing Model;\npublic class HostTests {\n"+ " public void Scan(Host.ApplicationHost h, object x) {\n"+ " h.GetExports<ITestOnly>();\n"+ " }\n}\n"+ ),+ "Plugins/Assertions.cs": (+ "namespace Plugins;\nusing Model;\npublic static class Assertions {\n"+ " public static void Check(object x) { Assert.That(x, Is.AssignableTo<INunit>()); }\n}\n"+ ),+ "Unused/TestOnlyImpl.cs": "namespace Unused;\nusing Model;\npublic class TestOnlyImpl : ITestOnly {}\n",+ "Unused/NunitImpl.cs": "namespace Unused;\nusing Model;\npublic class NunitImpl : INunit {}\n",+}+++def _report(root: Path):+ source_map = {rel: text.encode() for rel, text in _FILES.items()}+ for rel, source in source_map.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(source)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=root)+ for fi in FileTraverser(root).traverse():+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))+ builder.set_source_map(source_map)+ graph = builder.build()+ analyzer = DeadCodeAnalyzer(+ graph,+ git_meta_map={},+ parsed_files=builder._parsed_files,+ source_map=source_map,+ repo_root=root,+ )+ return analyzer.analyze({"min_confidence": 0.0})+++def _flagged(report) -> set[str]:+ """Paths with an unused-export or unreachable-file finding."""+ return {+ f.file_path+ for f in report.findings+ if f.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNREACHABLE_FILE)+ }+++def test_classes_the_runtime_discovers_by_type_are_not_flagged(tmp_path: Path) -> None:+ flagged = _flagged(_report(tmp_path))+ discovered = {+ "Tasks/DeleteLogFileTask.cs", # GetExports<IScheduledTask>+ "Tasks/OptimizeTask.cs", # through an abstract base+ "Providers/TmdbEpisodeProvider.cs", # through an unresolved generic interface chain+ "Plugins/OrderHandler.cs", # Scrutor AssignableTo<IHandler>()+ "Plugins/AudioPlugin.cs", # typeof(IPlugin).IsAssignableFrom+ "Plugins/ExportedPart.cs", # MEF [Export]+ }+ assert flagged.isdisjoint(discovered), flagged & discovered+++def test_classes_no_production_scan_reaches_are_still_flagged(tmp_path: Path) -> None:+ flagged = _flagged(_report(tmp_path))+ assert {+ "Unused/OrphanTask.cs", # IUnscanned is never scanned+ "Other/DeleteLogFileTask.cs", # shares only a simple name with a discovered class+ "Unused/DisposableThing.cs", # a scan over IDisposable (the parser drops BCL bases too)+ "Unused/ComparableThing.cs", # a scan over a System.-qualified type+ "Unused/TestOnlyImpl.cs", # scanned only by a test+ "Unused/NunitImpl.cs", # Is.AssignableTo<> is an assertion+ } <= flagged, flagged+++def test_generic_arguments_and_namespaces_are_dropped_from_a_base_name() -> None:+ blob = b"var p = host.GetExports<Model.IRemoteMetadataProvider<Episode, EpisodeInfo>>();\n"+ assert _scanned_type_names(nx.DiGraph(), {"Host.cs": blob}) == {"IRemoteMetadataProvider"}+ assert _simple_type_name("Model.IFoo<A, B>") == "IFoo"+++def test_scans_over_framework_types_and_assertions_name_nothing() -> None:+ blob = (+ b"if (typeof(IDisposable).IsAssignableFrom(t)) {}\n"+ b"var a = host.GetExports<System.Collections.IList>();\n"+ b"Assert.That(x, Is.AssignableTo<IPlugin>());\n"+ b"x.Should().BeAssignableTo<IPlugin>();\n"+ )+ assert _scanned_type_names(nx.DiGraph(), {"Host.cs": blob}) == set()diff --git a/tests/unit/dead_code/test_jvm_resource_roots.py b/tests/unit/dead_code/test_jvm_resource_roots.pynew file mode 100644index 000000000..256902d4c--- /dev/null+++ b/tests/unit/dead_code/test_jvm_resource_roots.py@@ -0,0 +1,109 @@+"""JVM classes a main resource file names for a framework to load are not dead.++Shapes from apollo, eladmin and litemall, every one reported dead: an H2+``CREATE ALIAS ... FOR "pkg.H2Function.unixTimestamp"`` in an init ``.sql``, a+Hibernate ``metadata_builder_contributor`` in ``application.yml``, a MyBatis+``typeHandler=`` in a mapper ``.xml`` and a P6Spy ``logMessageFormat=`` in+``spy.properties``. A class named only by test resources, and one nothing+names, stay reported.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_COMMON = "common/src/main/java/org/sample/common"+_RES = "app/src/main/resources"+++def _cls(package: str, name: str) -> str:+ return f"package org.sample.{package};\n\npublic class {name} {{\n}}\n"+++_FILES = {+ "settings.gradle": "rootProject.name = 'sample'\ninclude 'common', 'app'\n",+ "build.gradle": "apply plugin: 'java'\n",+ f"{_COMMON}/jpa/H2Function.java": _cls("common.jpa", "H2Function"),+ f"{_COMMON}/hibernate/SqlFunctionsContributor.java": _cls(+ "common.hibernate", "SqlFunctionsContributor"+ ),+ f"{_COMMON}/mybatis/JsonStringArrayTypeHandler.java": _cls(+ "common.mybatis", "JsonStringArrayTypeHandler"+ ),+ f"{_COMMON}/logging/CustomP6SpyLogger.java": _cls("common.logging", "CustomP6SpyLogger"),+ f"{_COMMON}/testonly/TestOnlyFunction.java": _cls("common.testonly", "TestOnlyFunction"),+ f"{_COMMON}/orphan/Orphan.java": _cls("common.orphan", "Orphan"),+ # Each named only inside a comment of one resource format.+ **{+ f"{_COMMON}/{name.lower()}/{name}.java": _cls(f"common.{name.lower()}", name)+ for name in ("InXmlComment", "InYmlComment", "InPropsComment", "InSqlComment")+ },+ f"{_RES}/jpa/configdb.init.h2.sql": (+ "CREATE ALIAS IF NOT EXISTS UNIX_TIMESTAMP FOR "+ '"org.sample.common.jpa.H2Function.unixTimestamp";\n'+ "-- CREATE ALIAS OLD FOR \"org.sample.common.insqlcomment.InSqlComment.run\";\n"+ ),+ f"{_RES}/application.yml": (+ "spring:\n jpa:\n properties:\n hibernate:\n"+ " metadata_builder_contributor: "+ "org.sample.common.hibernate.SqlFunctionsContributor\n"+ " # was: org.sample.common.inymlcomment.InYmlComment\n"+ ),+ f"{_RES}/mapper/OrderMapper.xml": (+ '<mapper namespace="x">\n <result column="tags" property="tags" '+ 'typeHandler="org.sample.common.mybatis.JsonStringArrayTypeHandler"/>\n'+ " <!-- typeHandler=org.sample.common.inxmlcomment.InXmlComment -->\n</mapper>\n"+ ),+ f"{_RES}/spy.properties": (+ "logMessageFormat=org.sample.common.logging.CustomP6SpyLogger\n"+ "# logMessageFormat=org.sample.common.inpropscomment.InPropsComment\n"+ ),+ "app/src/test/resources/import.sql": (+ 'CREATE ALIAS T FOR "org.sample.common.testonly.TestOnlyFunction.run";\n'+ ),+}+++def _report(root: Path):+ for rel, text in _FILES.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ parser = ASTParser()+ builder = GraphBuilder(repo_path=root)+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(root).traverse():+ source = Path(fi.abs_path).read_bytes()+ source_map[fi.path] = source+ builder.add_file(parser.parse_file(fi, source))+ builder.set_source_map(source_map)+ graph = builder.build()+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={}, source_map=source_map, repo_root=root)+ return analyzer.analyze({"min_confidence": 0.0, "detect_zombie_packages": False})+++def _flagged(report) -> set[str]:+ return {+ f.symbol_name if f.kind is DeadCodeKind.UNUSED_EXPORT else Path(f.file_path).name+ for f in report.findings+ if f.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNREACHABLE_FILE)+ }+++def test_classes_main_resources_name_are_not_reported(tmp_path: Path) -> None:+ flagged = _flagged(_report(tmp_path))+ named = {"H2Function", "SqlFunctionsContributor", "JsonStringArrayTypeHandler", "CustomP6SpyLogger"}+ assert flagged.isdisjoint(named | {f"{n}.java" for n in named}), flagged+++def test_test_resources_and_unnamed_classes_are_still_reported(tmp_path: Path) -> None:+ flagged = _flagged(_report(tmp_path))+ assert {"TestOnlyFunction", "Orphan"} <= flagged+++def test_a_class_named_only_in_a_resource_comment_is_still_reported(tmp_path: Path) -> None:+ flagged = _flagged(_report(tmp_path))+ assert {"InXmlComment", "InYmlComment", "InPropsComment", "InSqlComment"} <= flaggeddiff --git a/tests/unit/dead_code/test_swift_reachability.py b/tests/unit/dead_code/test_swift_reachability.pynew file mode 100644index 000000000..07c27e045--- /dev/null+++ b/tests/unit/dead_code/test_swift_reachability.py@@ -0,0 +1,234 @@+"""Swift file reachability: a file is live when a live file uses, names or extends its types.++Shapes from IceCubesApp, where none of 30 judged "unreachable" files was dead:+a view constructed from another package (``TagRowView(tag:)``), a model named+only in a type annotation (``[StatusHistory]``), an ``extension Color`` whose+member is used, and an extension of a live in-repo type. Plus the controls+that keep the rescue from hiding dead code: two dead files naming each other,+a name declared twice or common to the platform, a name in a comment or a+string, and an unused extension of a platform type.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.swift_reachability import (+ build_swift_named_files,+ strip_comments_and_strings,+)+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_DS = "Packages/DesignSystem/Sources/DesignSystem"+_MODELS = "Packages/Models/Sources/Models"+_ACCOUNT = "Packages/Account/Sources/Account"+_ENTRY = f"{_ACCOUNT}/Tags/FollowedTagsListView.swift"+++def _package(name: str) -> str:+ return (+ "// swift-tools-version:5.9\nimport PackageDescription\n\n"+ f'let package = Package(name: "{name}", targets: [.target(name: "{name}")])\n'+ )+++_FILES = {+ "Packages/DesignSystem/Package.swift": _package("DesignSystem"),+ "Packages/Models/Package.swift": _package("Models"),+ "Packages/Account/Package.swift": _package("Account"),+ f"{_DS}/Views/TagRowView.swift": (+ "import SwiftUI\n\npublic struct TagRowView: View {\n"+ " let tag: String\n public init(tag: String) { self.tag = tag }\n"+ " public var body: some View { Text(tag) }\n}\n"+ ),+ f"{_DS}/Resources/Colors.swift": (+ "import SwiftUI\n\nextension Color {\n public static let brandTint = Color(.blue)\n}\n"+ ),+ f"{_MODELS}/StatusHistory.swift": (+ "import Foundation\n\npublic struct StatusHistory: Decodable {\n"+ " public let content: String\n}\n\nextension StatusHistory: Sendable {}\n"+ ),+ f"{_MODELS}/Editor/EditorStore.swift": (+ "import Foundation\n\npublic enum StatusEditor {\n"+ " public final class EditorStore {}\n}\n"+ ),+ f"{_MODELS}/Editor/EditorMode.swift": (+ "import Foundation\n\nextension StatusEditor.EditorStore {\n"+ " public enum Mode { case new, edit }\n}\n"+ ),+ f"{_MODELS}/PartialAccountWithAvatar.swift": (+ "import Foundation\n\npublic struct PartialAccountWithAvatar: Codable {\n"+ " public let id: String\n}\n"+ ),+ f"{_MODELS}/Legacy.swift": (+ "import Foundation\n\npublic struct LegacyThing {}\n\n"+ "extension LegacyThing {\n func old() {}\n}\n"+ ),+ _ENTRY: (+ "import SwiftUI\nimport DesignSystem\nimport Models\n\n"+ "// PartialAccountWithAvatar is only mentioned here.\n"+ "public struct FollowedTagsListView: View {\n"+ " @State private var history: [StatusHistory]?\n"+ " let store = StatusEditor.EditorStore()\n"+ ' let label = "LegacyThing"\n'+ " public var body: some View {\n"+ ' TagRowView(tag: "swift").foregroundColor(.brandTint)\n }\n}\n'+ ),+}+++def _report(root: Path):+ source_map = {rel: text.encode() for rel, text in _FILES.items()}+ for rel, source in source_map.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(source)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=root)+ for fi in FileTraverser(root).traverse():+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))+ builder.set_source_map(source_map)+ graph = builder.build()+ # Stands in for the app's ``@main`` entry, which reaches the list view.+ graph.nodes[_ENTRY]["is_entry_point"] = True+ analyzer = DeadCodeAnalyzer(+ graph,+ git_meta_map={},+ parsed_files=builder._parsed_files,+ source_map=source_map,+ repo_root=root,+ )+ return analyzer.analyze({"min_confidence": 0.0})+++def _unreachable(report) -> set[str]:+ return {+ Path(f.file_path).name+ for f in report.findings+ if f.kind is DeadCodeKind.UNREACHABLE_FILE+ }+++def test_files_a_live_file_uses_names_or_extends_are_reachable(tmp_path: Path) -> None:+ unreachable = _unreachable(_report(tmp_path))+ assert unreachable.isdisjoint(+ {+ "TagRowView.swift", # constructed from another package+ "StatusHistory.swift", # named in a type annotation+ "Colors.swift", # a member of its platform-type extension is used+ "EditorStore.swift",+ "EditorMode.swift", # extends a type declared in a reachable file+ }+ ), unreachable+++def test_a_type_only_a_comment_or_string_names_is_still_unreachable(tmp_path: Path) -> None:+ unreachable = _unreachable(_report(tmp_path))+ assert {"PartialAccountWithAvatar.swift", "Legacy.swift"} <= unreachable+++def test_no_source_means_unchecked_and_reachable() -> None:+ graph = nx.DiGraph()+ graph.add_node("A.swift", node_type="file", language="swift")+ assert build_swift_named_files(graph, {}) == frozenset({"A.swift"})+++def _graph(decls: dict[str, list[tuple[str, str, str | None]]], entry: str) -> nx.DiGraph:+ """Files declaring ``(name, kind, parent)`` symbols, no edge between them."""+ graph = nx.DiGraph()+ for path, symbols in decls.items():+ graph.add_node(path, node_type="file", language="swift", is_entry_point=path == entry)+ for name, kind, parent in symbols:+ sym = f"{path}::{parent + '.' if parent else ''}{name}"+ graph.add_node(+ sym, node_type="symbol", name=name, kind=kind, file_path=path, parent_name=parent+ )+ graph.add_edge(path, sym, edge_type="defines")+ return graph+++_ROOT = "App/Main.swift"+_DECLS: dict[str, list[tuple[str, str, str | None]]] = {+ _ROOT: [("Main", "class", None)],+ "Models/StatusHistory.swift": [("StatusHistory", "class", None)],+ "Models/Store.swift": [("Store", "class", None)],+ "Models/Store+Mode.swift": [("Store", "impl", None), ("Mode", "class", "Store")],+ "Views/Colors.swift": [("Color", "impl", None), ("brandTint", "variable", "Color")],+ "Probe/String+Probe.swift": [("String", "impl", None), ("probeTrimmed", "method", "String")],+ "Probe/URL+Id.swift": [("URL", "impl", None), ("id", "variable", "URL")],+ "Probe/Account.swift": [("Account", "class", None), ("id", "variable", "Account")],+ "Probe/DeadA.swift": [("DeadA", "class", None)],+ "Probe/DeadB.swift": [("DeadB", "class", None)],+ "Probe/Text.swift": [("Text", "class", None)],+ "Probe/ItemA.swift": [("Item", "class", None)],+ "Probe/ItemB.swift": [("Item", "class", None)],+ "Probe/ItemView.swift": [("ItemView", "class", None)],+ "Probe/Commented.swift": [("CommentedType", "class", None)],+ "Probe/Quoted.swift": [("QuotedType", "class", None), ("RawQuotedType", "class", None)],+ "Probe/Bare.swift": [("BareOperand", "class", None)],+}+_SOURCE = {+ _ROOT: (+ b"struct Main {\n"+ b" var h: [StatusHistory]\n let s = Store()\n"+ b" let c = Color.blue.opacity(1).brandTint\n"+ b" let t = Text(\"x\")\n let i = Item()\n let ids = urls.map { $0.id }\n"+ b" /* outer /* CommentedType */ still a comment: CommentedType */\n"+ b' let q = """\n QuotedType(\n """\n'+ b' let r = #"RawQuotedType( \\"#\n'+ b" let n = count + BareOperand\n"+ b' let v = "ItemView" // ItemView\n'+ b"}\n"+ ),+ "Models/StatusHistory.swift": b"struct StatusHistory {}\n",+ "Models/Store.swift": b"final class Store {}\n",+ "Models/Store+Mode.swift": b"extension Store { enum Mode {} }\n",+ "Views/Colors.swift": b"extension Color { static let brandTint = Color.red }\n",+ "Probe/String+Probe.swift": b"extension String { func probeTrimmed() -> String { self } }\n",+ "Probe/URL+Id.swift": b"extension URL { var id: String { absoluteString } }\n",+ "Probe/Account.swift": b"struct Account { let id: String }\n",+ "Probe/DeadA.swift": b"struct DeadA { let b: DeadB }\n",+ "Probe/DeadB.swift": b"struct DeadB { let a: [DeadA] }\n",+ "Probe/Text.swift": b"struct Text {}\n",+ "Probe/ItemA.swift": b"struct Item {}\n",+ "Probe/ItemB.swift": b"struct Item {}\n",+ "Probe/ItemView.swift": b"struct ItemView { let item: Item }\n",+ "Probe/Commented.swift": b"struct CommentedType {}\n",+ "Probe/Quoted.swift": b"struct QuotedType {}\nstruct RawQuotedType {}\n",+ "Probe/Bare.swift": b"struct BareOperand {}\n",+}+++def test_live_uses_in_type_and_member_positions_reach_a_file() -> None:+ named = build_swift_named_files(_graph(_DECLS, _ROOT), _SOURCE)+ assert {+ "Models/StatusHistory.swift", # [StatusHistory]+ "Models/Store.swift", # Store()+ "Models/Store+Mode.swift", # extends a reached type+ "Views/Colors.swift", # .brandTint, declared by no other file+ } <= named, named+++def test_dead_code_the_text_cannot_vouch_for_stays_unreachable() -> None:+ named = build_swift_named_files(_graph(_DECLS, _ROOT), _SOURCE)+ assert not named & {+ "Probe/String+Probe.swift", # an unused extension of a platform type+ "Probe/URL+Id.swift", # its only member name is declared elsewhere too+ "Probe/DeadA.swift", # two dead files naming each other+ "Probe/DeadB.swift",+ "Probe/Text.swift", # a platform name+ "Probe/ItemA.swift", # declared by two files+ "Probe/ItemB.swift",+ "Probe/ItemView.swift", # only in a string and a comment+ "Probe/Commented.swift", # inside a nested block comment+ "Probe/Quoted.swift", # inside multi-line and raw strings+ "Probe/Bare.swift", # an operand, not a type position+ }, named+++def test_comment_and_string_stripping() -> None:+ text = 'a /* x /* y */ z */ b "s\\"t" c """\nm\n""" d #"r"q"# e // f\ng'+ assert strip_comments_and_strings(text).split() == ["a", "b", "c", "d", "e", "g"]