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.

fix(dead-code): a C# file named by a project that can see it is reachable (#2912)

Raghav Chamadiyaa1f00cfda5e8
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index 71bf131dc..0822513d4 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -193,6 +193,7 @@ def _analyze_live(repo_path: Path, config: dict, notices: Any) -> DeadCodeReport
*traverser.stats.unknown_language_files,
)
],
+ dotnet_index=getattr(graph_builder, "dotnet_index", None),
)
return analyzer.analyze(config)
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 2176ea833..eac96324f 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -46,6 +46,7 @@ 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
from .dynamic_markers import (
find_dynamic_edge_files,
find_dynamic_import_files,
@@ -807,8 +808,13 @@ class DeadCodeAnalyzer:
source_map: dict[str, bytes] | None = None,
repo_root: Path | None = None,
unindexed_source_files: list[tuple[str, str]] | None = None,
+ dotnet_index: Any | None = None,
) -> None:
self.graph = graph
+ # The C# resolver's project index (``GraphBuilder.dotnet_index``):
+ # scopes the C# name rescue to the projects that can see a file.
+ self._dotnet_index = dotnet_index
+ self._csharp_named_files: frozenset[str] | None = None
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
@@ -886,10 +892,18 @@ class DeadCodeAnalyzer:
"""Assemble the rescue state the shared predicate reads."""
if self._package_files is None:
self._package_files = build_package_file_map(self.graph)
+ if self._csharp_named_files is None:
+ self._csharp_named_files = build_csharp_named_files(
+ self.graph,
+ self._source_map,
+ dotnet_index=self._dotnet_index,
+ repo_root=self._repo_root,
+ )
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,
)
def analyze(
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.py
new file mode 100644
index 000000000..d6743a4aa
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/csharp_reachability.py
@@ -0,0 +1,421 @@
+"""Name-granular reachability for C#.
+
+C# has no file import graph. A ``using X.Y`` names a namespace, a type in the
+file's own namespace needs no ``using`` at all, and ``new T()``, ``throw new
+T()``, an extension-method call and a WinForms ``*.Designer.cs`` file (skipped
+as generated) leave no file-level edge either. So ``in_degree == 0`` on a
+``.cs`` file is mostly a property of the language, not evidence of deadness:
+on one 3.5k-file C# repository about 86% of the files reported unreachable
+were named by another file of their own project.
+
+This module answers the question C# lets us ask instead: **is any type the
+file declares named in another file that could see it?** "Could see it" is the
+declaring file's own project or any project that references it, through the
+csproj ``ProjectReference`` graph the C# resolver already indexed. A static
+class holding extension methods also counts as named when one of those methods
+is invoked as a member (``x.Fit()``) in that scope. A file carrying
+assembly-level attributes or ``global using`` directives acts on its whole
+assembly and is never dead.
+
+It only rescues, never accuses, so every approximation is chosen to err toward
+"named". A comment mention does not count (doc comments ``cref`` dead types
+all the time), but a string does, since ``Type.GetType("Ns.Foo")`` is a use.
+Two same-named types in scope both count as named: binding the name to the
+right one would need the semantic model, and a wrong "dead" is worse than a
+missed one. A use from a file that is itself unreachable still counts, so a
+cluster of dead files that only name each other stays hidden; propagating
+deadness through an unreliable edge set would turn one wrong verdict into
+several.
+
+A file linked into another project by ``<Compile Include>`` is visible from
+that project too. Ceiling: items pulled in through ``.projitems`` / ``.props``
+imports or wildcards, and reflection by a computed name, are not seen. Both
+leave a finding as it was before this pass existed.
+"""
+
+from __future__ import annotations
+
+import os
+import posixpath
+import re
+from collections.abc import Iterable, Mapping
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from .constants import never_flag_match
+from .file_reachability import CSHARP_SUFFIX, has_dependency_importer
+
+#: Sources a C# type can be named from. ``.vb`` because a mixed solution can
+#: use a C# project's types; the markup forms because they name types as
+#: elements, ``x:Class`` and ``x:Type`` values.
+_SCANNED_SUFFIXES: tuple[str, ...] = (".cs", ".vb", ".xaml", ".axaml", ".razor", ".cshtml")
+
+_TYPE_KINDS: frozenset[str] = frozenset({"class", "interface", "struct", "enum", "record"})
+
+#: A string literal (kept, so a ``//`` in a URL is not a comment) or a comment.
+#: Verbatim and raw strings are not lexed; a quote inside one can leave a later
+#: comment on the same line unblanked, which only costs a finding.
+_STRING_OR_COMMENT = re.compile(rb'("(?:\\.|[^"\\\n])*")|/\*.*?\*/|//[^\n]*', re.DOTALL)
+_IDENT = re.compile(rb"[A-Za-z_][A-Za-z0-9_]*")
+_MEMBER = re.compile(rb"\.\s*([A-Za-z_][A-Za-z0-9_]*)")
+_ATTRIBUTE = b"Attribute"
+#: An extension method's first parameter; a long signature wraps after ``(``.
+_THIS_PARAM = re.compile(r"\(\s*this\s")
+#: ``delegate void Handler(...)``: the parser emits no symbol for a delegate.
+_DELEGATE_DECL = re.compile(rb"\bdelegate\s+[\w<>\[\],.?\s]+?\s([A-Za-z_]\w*)\s*[<(]")
+#: Assembly- or module-wide code: ``[assembly: ...]``, ``[module: ...]`` and
+#: ``global using``. ``AssemblyInfo.cs``, ``GlobalSuppressions.cs``,
+#: ``GlobalUsings.cs`` and ``TypeForwardedTo`` shims are made of it and named
+#: by nothing, so a file declaring no type that holds any of it is never dead.
+_ASSEMBLY_LEVEL = re.compile(
+ rb"^[ \t]*(?:\[[ \t]*(?:assembly|module)[ \t]*:|global[ \t]+using[ \t])", re.MULTILINE
+)
+#: The same minus ``SuppressMessage``. An attribute that changes the assembly
+#: (``InternalsVisibleTo``, ``TypeForwardedTo``, a ``global using``) keeps even
+#: a file that also declares types; a suppression parked above a class does not.
+_ASSEMBLY_EFFECT = re.compile(
+ rb"^[ \t]*(?:\[[ \t]*(?:assembly|module)[ \t]*:"
+ rb"(?![ \t]*(?:System\.Diagnostics\.CodeAnalysis\.)?SuppressMessage)|global[ \t]+using[ \t])",
+ re.MULTILINE,
+)
+
+
+def _code_only(blob: bytes) -> bytes:
+ """*blob* with C-style comments replaced by a space; strings kept."""
+ if b"/" not in blob:
+ return blob
+ # A template rather than a callback keeps the substitution in C: a string
+ # is put back (plus a space), a comment becomes the space.
+ return _STRING_OR_COMMENT.sub(rb"\1 ", blob)
+
+
+def _partner_paths(path: str) -> frozenset[str]:
+ """Files that are halves of *path* rather than users of it.
+
+ ``Foo.xaml`` / ``Foo.xaml.cs`` and ``Foo.cs`` / ``Foo.Designer.cs`` are one
+ class split by tooling: the markup or designer half names the type because
+ it *is* the type, which says nothing about whether anyone uses it.
+ """
+ stem = path[: -len(".cs")]
+ if stem.endswith(".xaml"):
+ stem = stem[: -len(".xaml")]
+ return frozenset(
+ f"{stem}{suffix}"
+ for suffix in (
+ ".xaml",
+ ".xaml.cs",
+ ".axaml",
+ ".axaml.cs",
+ ".Designer.cs",
+ ".designer.cs",
+ ".cs",
+ )
+ ) - {path}
+
+
+class _ProjectScopes:
+ """Which project each scanned file belongs to, and who can see a project."""
+
+ def __init__(self, dotnet_index: Any | None) -> None:
+ self._dir_to_project: dict[str, str] = {}
+ self._linked_by: dict[str, set[str]] = {}
+ self._referenced_by: dict[str, set[str]] = {}
+ self._users: dict[str, frozenset[str]] = {}
+ if dotnet_index is None:
+ return
+ root = Path(dotnet_index.repo_path)
+ for csproj, project in dotnet_index.projects.items():
+ rel = _relative(project.project_dir, root)
+ if rel is None:
+ continue
+ self._dir_to_project.setdefault(rel, str(csproj))
+ for item in project.compile_includes:
+ self._linked_by.setdefault(_link_key(rel, item), set()).add(str(csproj))
+ self._referenced_by = _referencing_projects(dotnet_index)
+
+ def project_of(self, path: str) -> str | None:
+ """The innermost project enclosing repo-relative *path*, if any."""
+ for parent in PurePosixPath(path).parents:
+ project = self._dir_to_project.get("" if str(parent) == "." else parent.as_posix())
+ if project is not None:
+ return project
+ return None
+
+ def seen_from(self, path: str) -> frozenset[str] | None:
+ """Projects whose files can name a type *path* declares; None for any.
+
+ Its own project and the projects linking it in by ``<Compile
+ Include>``, each with every project that references it. A link spelled
+ through an MSBuild property is matched by file name, so two same-named
+ files widen each other's scope, which only widens a rescue. A file
+ outside every project could be compiled from anywhere, so it is
+ visible from anywhere.
+ """
+ own = self.project_of(path)
+ if own is None:
+ return None
+ projects = {own}
+ for key in (path.lower(), _NAME_KEY + PurePosixPath(path).name.lower()):
+ projects |= self._linked_by.get(key, set())
+ return frozenset().union(*(self._users_of(project) for project in projects))
+
+ def _users_of(self, project: str) -> frozenset[str]:
+ """*project* and every project referencing it, directly or transitively.
+
+ SDK-style projects flow references transitively, and over-including
+ only widens a rescue.
+ """
+ cached = self._users.get(project)
+ if cached is not None:
+ return cached
+ seen = {project}
+ stack = [project]
+ while stack:
+ for user in self._referenced_by.get(stack.pop(), ()):
+ if user not in seen:
+ seen.add(user)
+ stack.append(user)
+ self._users[project] = frozenset(seen)
+ return self._users[project]
+
+
+#: Prefix of a ``<Compile Include>`` key matched by file name alone.
+_NAME_KEY = "*/"
+
+
+def _link_key(project_dir: str, item: str) -> str:
+ """Lookup key for one ``<Compile Include>`` item of a project.
+
+ The repo-relative path when the item can be resolved without evaluating
+ MSBuild, else the file name under :data:`_NAME_KEY`. Lower-cased: .NET
+ builds mostly run on case-insensitive file systems.
+ """
+ if "$(" in item:
+ return _NAME_KEY + PurePosixPath(item).name.lower()
+ return posixpath.normpath(posixpath.join(project_dir, item)).lower()
+
+
+def _referencing_projects(dotnet_index: Any) -> dict[str, set[str]]:
+ """Project -> the projects whose ``ProjectReference`` names it.
+
+ A reference spelled through an MSBuild property
+ (``$(LibrariesProjectRoot)Foo/src/Foo.csproj``) resolves to no file, so it
+ is matched to the projects with that file name instead.
+ """
+ by_name: dict[str, list[str]] = {}
+ for csproj in dotnet_index.projects:
+ by_name.setdefault(Path(csproj).name.lower(), []).append(str(csproj))
+
+ def targets(ref: Path) -> list[str]:
+ if ref in dotnet_index.projects:
+ return [str(ref)]
+ return by_name.get(ref.name.lower(), [])
+
+ referenced_by: dict[str, set[str]] = {}
+ for csproj, refs in dotnet_index.project_refs_by_proj.items():
+ for target in (t for ref in refs for t in targets(ref)):
+ referenced_by.setdefault(target, set()).add(str(csproj))
+ return referenced_by
+
+
+def _relative(path: Path, root: Path) -> str | None:
+ """*path* relative to *root* in posix form; both already resolved.
+
+ String slicing, not ``Path.relative_to``: this runs once per walked C#
+ file, and the pathlib form was a fifth of the pass on a 29k-file repo.
+ """
+ text, prefix = str(path), str(root)
+ if text == prefix:
+ return ""
+ prefix = prefix.rstrip("/\\") + os.sep
+ if not text.startswith(prefix):
+ return None
+ return text[len(prefix) :].replace(os.sep, "/")
+
+
+def _corpus(
+ source_map: Mapping[str, bytes], dotnet_index: Any | None, repo_root: Path | None
+) -> Iterable[tuple[str, bytes]]:
+ """Every file a C# type can be named from, as ``(repo path, bytes)``.
+
+ The source map first. Then the ``.cs`` / ``.vb`` files the .NET index
+ walked but ingestion did not read, read from disk: that is where the
+ generated ``*.Designer.cs`` files are, and they are the only place a
+ WinForms control is ever named.
+ """
+ yield from ((p, b) for p, b in source_map.items() if p.endswith(_SCANNED_SUFFIXES))
+ if dotnet_index is not None and repo_root is not None:
+ yield from _unread_project_files(source_map, dotnet_index)
+
+
+def _unread_project_files(
+ source_map: Mapping[str, bytes], dotnet_index: Any
+) -> Iterable[tuple[str, bytes]]:
+ """``.cs`` / ``.vb`` files the .NET index walked and ingestion skipped."""
+ index_root = Path(dotnet_index.repo_path)
+ for rel in (_relative(p, index_root) for p in dotnet_index.file_to_project):
+ blob = None if rel is None or rel in source_map else _read(index_root, rel)
+ if blob is not None:
+ yield rel, blob
+
+
+def _read(root: Path, rel: str) -> bytes | None:
+ try:
+ return (root / rel).read_bytes()
+ except OSError:
+ return None
+
+
+def _declared_names(graph: Any, path: str, blob: bytes | None) -> tuple[set[bytes], set[bytes]]:
+ """``(type names, extension method names)`` *path* declares."""
+ types: set[bytes] = set()
+ extensions: set[bytes] = set()
+ for data in _defined_symbols(graph, path):
+ name = (data.get("name") or "").encode("ascii", "ignore")
+ if data.get("kind") in _TYPE_KINDS:
+ types.add(name)
+ elif _is_extension_method(data):
+ extensions.add(name)
+ if blob and b"delegate" in blob:
+ types.update(m.group(1) for m in _DELEGATE_DECL.finditer(_code_only(blob)))
+ # ``[NotNullWhen(...)]`` names ``NotNullWhenAttribute``.
+ types.update(name[: -len(_ATTRIBUTE)] for name in list(types) if name.endswith(_ATTRIBUTE))
+ types.discard(b"")
+ extensions.discard(b"")
+ return types, extensions
+
+
+def _defined_symbols(graph: Any, path: str) -> Iterable[dict]:
+ for _, symbol, edge in graph.out_edges(path, data=True):
+ if edge.get("edge_type") == "defines":
+ yield graph.nodes.get(symbol, {})
+
+
+def _is_extension_method(data: dict) -> bool:
+ return data.get("kind") == "method" and bool(_THIS_PARAM.search(data.get("signature") or ""))
+
+
+def _is_assembly_level(blob: bytes | None, declares_types: bool) -> bool:
+ """Whether *blob* acts on its whole assembly, so it is never dead."""
+ if blob is None:
+ return False
+ if _ASSEMBLY_EFFECT.search(blob):
+ return True
+ return not declares_types and _ASSEMBLY_LEVEL.search(blob) is not None
+
+
+def _candidates(graph: Any) -> list[str]:
+ """Non-test ``.cs`` file nodes nothing imports: the files this pass judges."""
+ return [path for path, data in graph.nodes(data=True) if _is_candidate(graph, path, data)]
+
+
+def _is_candidate(graph: Any, path: Any, data: dict) -> bool:
+ if not (isinstance(path, str) and path.endswith(CSHARP_SUFFIX)):
+ return False
+ if data.get("node_type", "file") != "file" or data.get("is_test", False):
+ return False
+ return not has_dependency_importer(graph, path) and not never_flag_match(path)
+
+
+def build_csharp_named_files(
+ graph: Any,
+ source_map: Mapping[str, bytes],
+ *,
+ dotnet_index: Any | None = None,
+ repo_root: Path | None = None,
+) -> frozenset[str]:
+ """The C# files with no importer that something names.
+
+ One pass over the scanned corpus, collecting only the names some candidate
+ declares, so the cost is linear in source size whatever the candidate
+ count. With no .NET index the scope is the whole repository, which is the
+ wider and therefore safer rescue.
+ """
+ candidates = _candidates(graph)
+ if not source_map and dotnet_index is None:
+ # Nothing to read, so nothing was checked: unchecked is reachable, the
+ # answer ``ReachabilityRescues`` gives a caller with no source at all.
+ return frozenset(candidates)
+ names = _NameIndex(_ProjectScopes(dotnet_index))
+ for path in candidates:
+ blob = source_map.get(path)
+ if blob is None and repo_root is not None:
+ blob = _read(repo_root, path)
+ names.add_candidate(graph, path, blob)
+ if names.waiting:
+ names.declarers = _declaring_files(graph, names.types.keys())
+ for path, blob in _corpus(source_map, dotnet_index, repo_root):
+ names.scan(path, blob)
+ return frozenset(names.named)
+
+
+class _NameIndex:
+ """Candidates by the names they declare, and which of them a file names."""
+
+ def __init__(self, scopes: _ProjectScopes) -> None:
+ self.scopes = scopes
+ self.named: set[str] = set()
+ self.types: dict[bytes, list[str]] = {}
+ self.extensions: dict[bytes, list[str]] = {}
+ self.declarers: dict[bytes, set[str]] = {}
+ self._scope: dict[str, tuple[frozenset[str], frozenset[str] | None]] = {}
+
+ @property
+ def waiting(self) -> bool:
+ return bool(self.types or self.extensions)
+
+ def add_candidate(self, graph: Any, path: str, blob: bytes | None) -> None:
+ types, extensions = _declared_names(graph, path, blob)
+ if _is_assembly_level(blob, bool(types)):
+ self.named.add(path)
+ return
+ for name in types:
+ self.types.setdefault(name, []).append(path)
+ for name in extensions:
+ self.extensions.setdefault(name, []).append(path)
+ self._scope[path] = (_partner_paths(path) | {path}, self.scopes.seen_from(path))
+
+ def scan(self, path: str, blob: bytes) -> None:
+ """Mark the candidates *path* names.
+
+ Matched on the raw bytes first and only re-matched with comments
+ blanked when that would name something: blanking is the expensive
+ step, and most files name no candidate at all.
+ """
+ project = self.scopes.project_of(path)
+ found = self._claimable(path, project, blob)
+ if found and path.endswith((".cs", ".vb")):
+ found = self._claimable(path, project, _code_only(blob))
+ self.named.update(found)
+
+ def _claimable(self, path: str, project: str | None, blob: bytes) -> set[str]:
+ found: set[str] = set()
+ for token in set(_IDENT.findall(blob)) & self.types.keys():
+ # A file declaring the name is declaring it, not using it.
+ if path not in self.declarers.get(token, ()):
+ found.update(self._visible(self.types[token], path, project))
+ if self.extensions:
+ for token in set(_MEMBER.findall(blob)) & self.extensions.keys():
+ found.update(self._visible(self.extensions[token], path, project))
+ return found
+
+ def _visible(self, owners: list[str], user: str, project: str | None) -> Iterable[str]:
+ for owner in owners:
+ if owner in self.named:
+ continue
+ not_users, projects = self._scope[owner]
+ if user not in not_users and (projects is None or project in projects):
+ yield owner
+
+
+def _declaring_files(graph: Any, names: Iterable[bytes]) -> dict[bytes, set[str]]:
+ """Every file declaring a type called one of *names*, candidate or not."""
+ wanted = set(names)
+ out: dict[bytes, set[str]] = {}
+ for _, data in graph.nodes(data=True):
+ if data.get("kind") not in _TYPE_KINDS or data.get("node_type") != "symbol":
+ continue
+ name = (data.get("name") or "").encode("ascii", "ignore")
+ if name in wanted and data.get("file_path"):
+ out.setdefault(name, set()).add(data["file_path"])
+ return out
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.py
index 6adcbf31d..fb1aad46e 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
@@ -80,6 +80,8 @@ _NON_DEPENDENCY_EDGES: frozenset[str] = frozenset({"co_changes"})
_JVM_SUFFIXES: tuple[str, ...] = (".java", ".kt")
+CSHARP_SUFFIX = ".cs"
+
#: Objective-C implementation files, which no source ever imports.
_OBJC_SOURCE_SUFFIXES: tuple[str, ...] = (".m", ".mm")
@@ -151,6 +153,11 @@ class ReachabilityRescues:
bundler_alias_targets: AbstractSet[str] = frozenset()
whitelist: AbstractSet[str] = frozenset()
package_files: PackageFileMap | None = None
+ #: C# files with no importer that another file of a project able to see
+ #: them names by type (see :mod:`csharp_reachability`). Needs source text,
+ #: so ``None`` is "not checked" and, like ``package_files``, resolves a
+ #: ``.cs`` file to reachable.
+ csharp_named_files: AbstractSet[str] | None = None
#: Prefix of an :class:`repowise.core.ids.ExternalId`, matched textually rather
@@ -321,5 +328,9 @@ def is_file_reachable(
return True if packages is None else is_jvm_file_reachable(path, graph, packages.jvm)
if is_cpp_path(path):
return True if packages is None else is_cpp_file_reachable(path, graph, packages.cpp)
+ if path.endswith(CSHARP_SUFFIX) and (
+ rescues.csharp_named_files is None or path in rescues.csharp_named_files
+ ):
+ return True
return has_dependency_importer(graph, path)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
index 1b719f4bd..d738d0c8d 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
@@ -58,6 +58,11 @@ class MSBuildProject:
project_references: list[Path] = field(default_factory=list) # absolute paths to referenced .csproj
package_references: set[str] = field(default_factory=set) # NuGet package ids
project_usings: set[str] = field(default_factory=set) # <Using Include="X"/> namespaces
+ #: Explicit ``<Compile Include>`` items, ``/``-separated and unevaluated. A
+ #: file linked in from outside the project directory (``..\Shared\X.cs``,
+ #: ``$(CommonPath)X.cs``) belongs to this project too, which the directory
+ #: walk cannot see.
+ compile_includes: list[str] = field(default_factory=list)
package_id: str | None = None # <PackageId>, the id this project publishes under
#: Tri-state on purpose: None = the project says nothing, which is not the
#: same as an explicit <IsPackable>false</IsPackable>.
@@ -94,6 +99,12 @@ def _tristate(value: str | None) -> bool | None:
return False if text in ("false", "disable", "0") else None
+def _compile_items(include: str | None) -> list[str]:
+ """The ``;``-separated items of a ``<Compile Include>``, wildcards dropped."""
+ items = (item.strip().replace("\\", "/") for item in (include or "").split(";"))
+ return [item for item in items if item and "*" not in item]
+
+
def parse_csproj(csproj_path: Path) -> MSBuildProject | None:
"""Parse a single .csproj file. Returns None on parse failure."""
try:
@@ -131,6 +142,8 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:
rel = include.replace("\\", "/")
target = (project.project_dir / rel).resolve()
project.project_references.append(target)
+ elif tag == "Compile":
+ project.compile_includes.extend(_compile_items(elem.get("Include")))
elif tag == "PackageReference":
pkg = elem.get("Include")
if pkg:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index dd683cc50..aaf698cf8 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -827,6 +827,7 @@ def run_partial_analysis(
*getattr(_traversal_stats, "unknown_language_files", []),
)
],
+ dotnet_index=getattr(graph_builder, "dotnet_index", None),
)
# Repo-wide, and persisted repo-wide. The detectors were always
# repo-wide — the update path just discarded everything outside the
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 5f59dca1f..b16a10861 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -82,6 +82,7 @@ async def _run_dead_code_analysis(
source_map=source_map,
repo_root=repo_path,
unindexed_source_files=unindexed_source_files,
+ dotnet_index=getattr(graph_builder, "dotnet_index", None),
)
def _step(_stage: str) -> None:
diff --git a/tests/unit/dead_code/test_csharp_reachability.py b/tests/unit/dead_code/test_csharp_reachability.py
new file mode 100644
index 000000000..db318946b
--- /dev/null
+++ b/tests/unit/dead_code/test_csharp_reachability.py
@@ -0,0 +1,303 @@
+"""C# file reachability: a file is live when a project that can see it names a type it declares.
+
+C# leaves no file-level edge for ``new T()``, ``throw new T()``, a same-namespace
+reference, an extension-method call or a use inside a generated
+``*.Designer.cs``. Each test below is one of those shapes, plus the controls
+that keep the rescue from hiding a file nothing uses.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.analysis.dead_code.csharp_reachability import build_csharp_named_files
+from repowise.core.analysis.dead_code.file_reachability import (
+ ReachabilityRescues,
+ is_file_reachable,
+)
+from repowise.core.ingestion.resolvers.dotnet.index import build_index
+from repowise.core.ingestion.resolvers.dotnet.msbuild import parse_csproj
+
+
+def _csproj(refs: tuple[str, ...] = (), compiles: tuple[str, ...] = ()) -> str:
+ items = "".join(f'<ProjectReference Include="{r}" />' for r in refs)
+ items += "".join(f'<Compile Include="{c}" />' for c in compiles)
+ return f'<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>{items}</ItemGroup></Project>'
+
+
+class _Repo:
+ """A tiny C# repository on disk plus the graph ingestion would build for it."""
+
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ self.graph = nx.DiGraph()
+ self.source_map: dict[str, bytes] = {}
+
+ def project(self, rel: str, **kwargs: tuple[str, ...]) -> None:
+ path = self.root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(_csproj(**kwargs))
+
+ def file(self, rel: str, text: str, *, types=(), extensions=(), indexed=True) -> None:
+ path = self.root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ if not indexed: # a skipped generated file: on disk, not in the graph
+ return
+ self.source_map[rel] = text.encode()
+ self.graph.add_node(rel, node_type="file", language="csharp")
+ for name in types:
+ self._symbol(rel, name, kind="class", signature=f"class {name}")
+ for name in extensions:
+ self._symbol(rel, name, kind="method", signature=f"{name}(this int value) -> int")
+
+ def _symbol(self, rel: str, name: str, **attrs: str) -> None:
+ sym = f"{rel}::{name}"
+ self.graph.add_node(
+ sym, node_type="symbol", name=name, file_path=rel, language="csharp", **attrs
+ )
+ self.graph.add_edge(rel, sym, edge_type="defines")
+
+ def named(self) -> frozenset[str]:
+ return build_csharp_named_files(
+ self.graph, self.source_map, dotnet_index=build_index(self.root), repo_root=self.root
+ )
+
+
+def _two_projects(tmp_path: Path, *, referenced: bool) -> _Repo:
+ repo = _Repo(tmp_path)
+ repo.project("Lib/Lib.csproj")
+ repo.project("App/App.csproj", refs=(r"..\Lib\Lib.csproj",) if referenced else ())
+ repo.file("Lib/Widget.cs", "namespace Lib;\npublic class Widget {}\n", types=("Widget",))
+ return repo
+
+
+def test_new_in_a_referencing_project_names_the_type(tmp_path: Path) -> None:
+ repo = _two_projects(tmp_path, referenced=True)
+ repo.file(
+ "App/Main.cs", "using Lib;\nclass Main { object w = new Widget(); }\n", types=("Main",)
+ )
+ assert "Lib/Widget.cs" in repo.named()
+
+
+def test_a_project_that_cannot_see_the_type_does_not_name_it(tmp_path: Path) -> None:
+ """Same name, no ProjectReference: that is some other ``Widget``."""
+ repo = _two_projects(tmp_path, referenced=False)
+ repo.file("App/Main.cs", "class Main { object w = new Widget(); }\n", types=("Main",))
+ assert "Lib/Widget.cs" not in repo.named()
+
+
+def test_throw_in_the_same_project_names_the_exception(tmp_path: Path) -> None:
+ """The PowerToys shape: the ``using`` edge went to a sibling file of the namespace."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/Exceptions/NotPhysicalConsoleException.cs",
+ "namespace App.Exceptions;\nclass NotPhysicalConsoleException : System.Exception {}\n",
+ types=("NotPhysicalConsoleException",),
+ )
+ repo.file(
+ "App/SocketStuff.cs",
+ "using App.Exceptions;\nclass SocketStuff { void F() { throw new NotPhysicalConsoleException(); } }\n",
+ types=("SocketStuff",),
+ )
+ assert "App/Exceptions/NotPhysicalConsoleException.cs" in repo.named()
+
+
+def test_a_comment_mention_is_not_a_use(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/EventRaiser.cs", "class EventRaiser {}\n", types=("EventRaiser",))
+ repo.file(
+ "App/Other.cs",
+ '/// <see cref="EventRaiser"/>\nclass Other { /* EventRaiser */ } // EventRaiser\n',
+ types=("Other",),
+ )
+ assert "App/EventRaiser.cs" not in repo.named()
+
+
+def test_a_string_mention_counts(tmp_path: Path) -> None:
+ """``Type.GetType("App.Plugin")`` loads the type by name."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Plugin.cs", "class Plugin {}\n", types=("Plugin",))
+ repo.file(
+ "App/Loader.cs",
+ 'class Loader { object t = System.Type.GetType("App.Plugin"); }\n',
+ types=("Loader",),
+ )
+ assert "App/Plugin.cs" in repo.named()
+
+
+def test_a_declaration_of_the_same_name_is_not_a_use(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/A/Helper.cs", "namespace A; class Helper {}\n", types=("Helper",))
+ repo.file("App/B/Helper.cs", "namespace B; class Helper {}\n", types=("Helper",))
+ assert repo.named() == frozenset()
+
+
+def test_extension_method_call_names_its_holder(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/SizeExtensions.cs",
+ "static class SizeExtensions { public static int Fit(this int v) => v; }\n",
+ types=("SizeExtensions",),
+ extensions=("Fit",),
+ )
+ repo.file(
+ "App/MainWindow.cs",
+ "class MainWindow { int F(int s) => s.Fit(); }\n",
+ types=("MainWindow",),
+ )
+ assert "App/SizeExtensions.cs" in repo.named()
+
+
+def test_extension_name_without_member_access_is_not_a_call(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/SizeExtensions.cs",
+ "static class SizeExtensions { public static int Fit(this int v) => v; }\n",
+ types=("SizeExtensions",),
+ extensions=("Fit",),
+ )
+ repo.file("App/MainWindow.cs", "class MainWindow { int Fit = 1; }\n", types=("MainWindow",))
+ assert "App/SizeExtensions.cs" not in repo.named()
+
+
+def test_a_skipped_designer_file_names_a_control(tmp_path: Path) -> None:
+ """WinForms controls are only ever written in generated ``*.Designer.cs``."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/ImageButton.cs", "class ImageButton {}\n", types=("ImageButton",))
+ repo.file("App/Form1.cs", "partial class Form1 {}\n", types=("Form1",))
+ repo.file(
+ "App/Form1.Designer.cs",
+ "partial class Form1 { void Init() { var b = new ImageButton(); } }\n",
+ indexed=False,
+ )
+ assert "App/ImageButton.cs" in repo.named()
+
+
+def test_a_files_own_designer_half_is_not_a_user(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Form1.cs", "partial class Form1 {}\n", types=("Form1",))
+ repo.file("App/Form1.Designer.cs", "partial class Form1 { Form1 self; }\n", indexed=False)
+ assert "App/Form1.cs" not in repo.named()
+
+
+def test_a_file_linked_into_another_project_is_seen_from_it(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("Shared/Shared.csproj")
+ repo.project("App/App.csproj", compiles=(r"..\Shared\Strings.cs",))
+ repo.file("Shared/Strings.cs", "static class Strings {}\n", types=("Strings",))
+ repo.file("App/Main.cs", "class Main { object s = Strings.Empty; }\n", types=("Main",))
+ assert "Shared/Strings.cs" in repo.named()
+
+
+def test_assembly_level_file_is_never_dead(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Properties/AssemblyInfo.cs", '[assembly: InternalsVisibleTo("App.Tests")]\n')
+ repo.file("App/GlobalSuppressions.cs", '[assembly: SuppressMessage("Style", "IDE0001")]\n')
+ assert repo.named() == {"App/Properties/AssemblyInfo.cs", "App/GlobalSuppressions.cs"}
+
+
+def test_a_suppression_above_a_class_does_not_keep_it(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/MyKnownBitmap.cs",
+ '[module: SuppressMessage("Design", "CA1031")]\nclass MyKnownBitmap {}\n',
+ types=("MyKnownBitmap",),
+ )
+ assert repo.named() == frozenset()
+
+
+def test_a_delegate_is_a_declared_type(tmp_path: Path) -> None:
+ """The parser emits no symbol for a delegate, so the source is read for it."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/GalleryFeedUrlProvider.cs", "public delegate string? GalleryFeedUrlProvider();\n"
+ )
+ repo.file("App/Service.cs", "class Service { GalleryFeedUrlProvider p; }\n", types=("Service",))
+ assert "App/GalleryFeedUrlProvider.cs" in repo.named()
+
+
+def test_no_source_and_no_index_is_unchecked() -> None:
+ g = nx.DiGraph()
+ g.add_node("src/Lonely.cs", node_type="file", language="csharp")
+ assert build_csharp_named_files(g, {}) == {"src/Lonely.cs"}
+ assert is_file_reachable("src/Lonely.cs", g, ReachabilityRescues()) is True
+
+
+def test_analyzer_reports_only_the_unnamed_file(tmp_path: Path) -> None:
+ """End to end: the named file is spared, the unnamed one is still reported."""
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file("App/Used.cs", "class Used {}\n", types=("Used",))
+ repo.file("App/Unused.cs", "class Unused {}\n", types=("Unused",))
+ repo.file("App/Program.cs", "class Program { object u = new Used(); }\n", types=("Program",))
+ analyzer = DeadCodeAnalyzer(
+ repo.graph,
+ source_map=repo.source_map,
+ repo_root=tmp_path,
+ dotnet_index=build_index(tmp_path),
+ )
+ flagged = {f.file_path for f in analyzer._detect_unreachable_files(set())}
+ assert "App/Unused.cs" in flagged
+ assert "App/Used.cs" not in flagged
+
+
+def test_csproj_records_compile_includes(tmp_path: Path) -> None:
+ path = tmp_path / "App.csproj"
+ path.write_text(_csproj(compiles=(r"$(CommonPath)System\Text\X.cs;..\Y.cs", r"**\*.cs")))
+ project = parse_csproj(path)
+ assert project is not None
+ assert project.compile_includes == ["$(CommonPath)System/Text/X.cs", "../Y.cs"]
+
+
+def test_an_attribute_is_named_without_its_suffix(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/NotNullWhenAttribute.cs",
+ "class NotNullWhenAttribute {}\n",
+ types=("NotNullWhenAttribute",),
+ )
+ repo.file(
+ "App/Use.cs",
+ "class Use { bool F([NotNullWhen(true)] object o) => true; }\n",
+ types=("Use",),
+ )
+ assert "App/NotNullWhenAttribute.cs" in repo.named()
+
+
+def test_a_wrapped_extension_signature_is_still_an_extension(tmp_path: Path) -> None:
+ repo = _Repo(tmp_path)
+ repo.project("App/App.csproj")
+ repo.file(
+ "App/FallbackExtensions.cs",
+ "static class FallbackExtensions {}\n",
+ types=("FallbackExtensions",),
+ )
+ sym = "App/FallbackExtensions.cs::AddFallback"
+ repo.graph.add_node(
+ sym,
+ node_type="symbol",
+ name="AddFallback",
+ kind="method",
+ signature="AddFallback(\r\n this Builder builder) -> Builder",
+ )
+ repo.graph.add_edge("App/FallbackExtensions.cs", sym, edge_type="defines")
+ repo.file(
+ "App/Main.cs", "class Main { void F(Builder b) => b.AddFallback(); }\n", types=("Main",)
+ )
+ assert "App/FallbackExtensions.cs" in repo.named()