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): root C# cmdlets, source generators and benchmarks (#3926)
Yunus Ozen59810bcfe6d5
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_roots.py b/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_roots.pyindex 0bc3e8091..b38800e5d 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_roots.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/dotnet_roots.py@@ -1,15 +1,17 @@"""C# files the compiler or a build tool consumes without a source reference.-Three kinds of file have no caller in source and are used all the same:+Four kinds of file have no caller in source and are used all the same:* a polyfill the compiler looks up by name (``IsExternalInit`` is what an``init`` accessor or a ``record`` compiles against on an older framework);* a marker a source generator reads from the compilation (Vogen's``[EfCoreConverter<T>]`` class is the generator's input);+* a class a host loads by reflection: a PowerShell ``[Cmdlet]``, a Roslyn+ ``[Generator]``, or a BenchmarkDotNet class with a ``[Benchmark]`` method;* a file-based app, started by ``dotnet run <file>``: it opens with ``#:``directives (``#:sdk``, ``#:package``), as Polly's Cake script ``cake.cs`` does.-The first two mark a file a reachability root when every top-level type in+The first three mark a file a reachability root when every top-level type init is one of these. A file that also declares an ordinary type is left to theusual checks, so a dead sibling still reports."""@@ -19,6 +21,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, Any+from ..decorator_names import decorator_basefrom ..type_names import bare_type_namefrom .base import DetectionContext, FrameworkHandler, read_text@@ -51,6 +54,17 @@ _GENERATOR_MARKER_ATTRIBUTES: dict[str, frozenset[str]] = {_LANGUAGE: frozenset({"EfCoreConverter"})}+#: Attributes whose class a host finds by reflection: PowerShell creates a+#: ``[Cmdlet]`` class when its verb-noun runs, and the compiler loads a Roslyn+#: ``[Generator]`` (an ``ISourceGenerator`` or ``IIncrementalGenerator``).+#: Matched by bare name, with or without the ``Attribute`` suffix.+_REFLECTION_LOADED_ATTRIBUTES: dict[str, frozenset[str]] = {+ _LANGUAGE: frozenset({"Cmdlet", "Generator"})+}++#: BenchmarkDotNet runs every class that has a method carrying one of these.+_BENCHMARK_METHOD_ATTRIBUTES: dict[str, frozenset[str]] = {_LANGUAGE: frozenset({"Benchmark"})}+# A ``partial class Name;`` has no body, so the parser reports no symbol for# it and the marker has to be read from the text._MARKER_ATTRIBUTE_RE = re.compile(r"\[\s*(?:[\w.]+\.)?(\w+)\s*<")@@ -87,12 +101,40 @@ def _namespace_of(sym: Any, modules: dict[str, Any]) -> str:return ".".join(reversed(parts))-def _is_consumed(sym: Any, modules: dict[str, Any]) -> bool:+def _attribute_name(decorator: str) -> str:+ """``[System.Foo.CmdletAttribute(...)]`` → ``Cmdlet``."""+ name = bare_type_name(decorator_base(decorator))+ return name.removesuffix("Attribute") or name+++def _has_benchmark_method(sym: Any, symbols: list[Any]) -> bool:+ """Whether a method of *sym* carries ``[Benchmark]``.++ ``parent_name`` is the bare class name, so the method must also lie within+ the class's lines: two same-named classes in different namespaces of one+ file are told apart.+ """+ markers = _BENCHMARK_METHOD_ATTRIBUTES[_LANGUAGE]+ return any(+ s.kind == "method"+ and s.parent_name == sym.name+ and sym.start_line <= s.start_line <= sym.end_line+ and any(_attribute_name(d) in markers for d in s.decorators)+ for s in symbols+ )+++def _is_consumed(sym: Any, modules: dict[str, Any], symbols: list[Any]) -> bool:namespace = _namespace_of(sym, modules)if f"{namespace}.{sym.name}" in _COMPILER_CONSUMED_TYPES[_LANGUAGE]:return Truemarkers = _GENERATOR_MARKER_ATTRIBUTES[_LANGUAGE]- return any(bare_type_name(d) in markers for d in sym.decorators)+ if any(bare_type_name(d) in markers for d in sym.decorators):+ return True+ loaded = _REFLECTION_LOADED_ATTRIBUTES[_LANGUAGE]+ if any(_attribute_name(d) in loaded for d in sym.decorators):+ return True+ return _has_benchmark_method(sym, symbols)def _is_generator_input(parsed: Any) -> bool:@@ -119,7 +161,7 @@ def _is_consumed_file(parsed: Any) -> bool:]if not types:return _is_generator_input(parsed)- return all(_is_consumed(s, modules) for s in types)+ return all(_is_consumed(s, modules, parsed.symbols) for s in types)def consumed_files(parsed_files: dict[str, Any]) -> list[str]:diff --git a/tests/unit/ingestion/test_dotnet_roots.py b/tests/unit/ingestion/test_dotnet_roots.pyindex 7e8c51b88..e7e4906bb 100644--- a/tests/unit/ingestion/test_dotnet_roots.py+++ b/tests/unit/ingestion/test_dotnet_roots.py@@ -91,3 +91,57 @@ def test_directives_after_a_leading_comment_still_count(tmp_path: Path) -> None:def test_preprocessor_lines_are_not_app_directives(tmp_path: Path) -> None:text = "#pragma warning disable CS1591\n#region R\nSystem.Console.WriteLine(1);\n#endregion\n"assert _roots(tmp_path, {"A.cs": text}) == set()+++ "text",+ [+ "using System.Management.Automation;\nnamespace App;\n"+ '[Cmdlet(VerbsCommon.Get, "Thing")]\npublic class GetThing : PSCmdlet { }\n',+ "using Microsoft.CodeAnalysis;\nnamespace App;\n"+ "[Generator]\npublic class Gen : IIncrementalGenerator { }\n",+ "using Microsoft.CodeAnalysis;\nnamespace App;\n"+ "[GeneratorAttribute(LanguageNames.CSharp)]\npublic class Gen : ISourceGenerator { }\n",+ "namespace App;\n"+ '[System.Management.Automation.CmdletAttribute("Get", "Thing")]\n'+ "public class GetThing { }\n",+ "using BenchmarkDotNet.Attributes;\nnamespace App;\n[MemoryDiagnoser]\n"+ "public class SortBench\n{\n [Benchmark(Baseline = true)]\n"+ " public void Sort() { }\n}\n",+ ],+ ids=["cmdlet", "generator", "generator-attribute", "qualified-cmdlet", "benchmark"],+)+def test_class_a_host_loads_by_reflection_is_a_root(tmp_path: Path, text: str) -> None:+ assert _roots(tmp_path, {"A.cs": text}) == {"A.cs"}+++def test_benchmark_attributes_without_a_benchmark_method_are_not_a_root(+ tmp_path: Path,+) -> None:+ text = (+ "using BenchmarkDotNet.Attributes;\nnamespace App;\n[MemoryDiagnoser]\n"+ "public class NotABench\n{\n public void Sort() { }\n}\n"+ )+ assert _roots(tmp_path, {"A.cs": text}) == set()+++def test_cmdlet_next_to_an_unused_class_keeps_the_file_judged(tmp_path: Path) -> None:+ text = (+ "using System.Management.Automation;\nnamespace App;\n"+ '[Cmdlet(VerbsCommon.Get, "Thing")]\npublic class GetThing : PSCmdlet { }\n'+ "public class DeadSibling { }\n"+ )+ assert _roots(tmp_path, {"A.cs": text}) == set()+++def test_benchmark_in_a_same_named_class_of_another_namespace_does_not_count(+ tmp_path: Path,+) -> None:+ text = (+ "using BenchmarkDotNet.Attributes;\n"+ "namespace A\n{\n public class Bench\n {\n"+ " [Benchmark]\n public void Sort() { }\n }\n}\n"+ "namespace B\n{\n public class Bench\n {\n"+ " public void Sort() { }\n }\n}\n"+ )+ assert _roots(tmp_path, {"A.cs": text}) == set()