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(ingestion): read C# 14 extension block members as extension methods (#3920)
Yunus Ozen5cb59f77164e
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.pyindex 59ecce921..d48f39821 100644--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py@@ -26,6 +26,7 @@ from typing import TYPE_CHECKINGfrom ...models import FileInfo, Symbolfrom .cpp_macros import cpp_macro_synthetic_symbols+from .csharp_extension_blocks import csharp_extension_block_symbolsfrom .csharp_mvvm import csharp_synthetic_symbolsfrom .java_records import java_record_synthetic_symbolsfrom .jvm_codegen import jvm_codegen_synthetic_symbols@@ -43,7 +44,7 @@ if TYPE_CHECKING:_Provider = Callable[["Node", str, FileInfo], list[Symbol]]_SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {- "csharp": [csharp_synthetic_symbols],+ "csharp": [csharp_synthetic_symbols, csharp_extension_block_symbols],"java": [lombok_synthetic_symbols,java_record_synthetic_symbols,diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/csharp_extension_blocks.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/csharp_extension_blocks.pynew file mode 100644index 000000000..5a72099c8--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/csharp_extension_blocks.py@@ -0,0 +1,133 @@+"""C# 14 extension blocks, which the bundled C# grammar predates.++Inside a static class, the grammar parses ``extension(string value) { ... }``+as a ``constructor_declaration`` named ``extension`` and the members of the+block as ``local_function_statement`` nodes in its body, without an error:++ - the symbol pass emits one bogus method named ``extension``;+ - the members never become symbols, so nothing sees them.++A static class cannot declare an instance constructor, so the shape never+matches real code. Each member becomes a method of the holder class, written+like the classic extension method the compiler lowers it to:++ - ``public bool IsBlank()`` → ``IsBlank(this string value) -> bool``+ - ``public static string Create(int n)`` → ``Create(int n) -> string``++``drop_extension_block_symbols`` removes the bogus ``extension`` method.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from ...models import FileInfo, Symbol+from ..helpers import node_text+from ._helpers import build_synthetic_symbol++if TYPE_CHECKING:+ from collections.abc import Iterator++ from tree_sitter import Node+++_EXTENSION = "extension"+_ACCESS = ("public", "internal", "protected", "private")+++def _modifiers(node: Node, src: str) -> list[str]:+ return [node_text(c, src).strip() for c in node.children if c.type == "modifier"]+++def _extension_blocks(root: Node, src: str) -> Iterator[tuple[Node, str]]:+ """``(block, holder class name)`` for each extension block in the file."""+ stack: list[Node] = [root]+ while stack:+ node = stack.pop()+ if node.type == "class_declaration":+ name_node = node.child_by_field_name("name")+ holder = node_text(name_node, src).strip() if name_node is not None else ""+ body = node.child_by_field_name("body")+ if holder and holder != _EXTENSION and "static" in _modifiers(node, src) and body:+ for member in body.children:+ if member.type != "constructor_declaration":+ continue+ member_name = member.child_by_field_name("name")+ # A block that does not parse cleanly (extension properties,+ # a generic ``extension<T>``) keeps its current handling.+ if (+ member_name is not None+ and node_text(member_name, src) == _EXTENSION+ and not member.has_error+ ):+ yield member, holder+ stack.extend(node.children)+++def _member_symbol(+ member: Node, receiver: str, holder: str, src: str, file_info: FileInfo+) -> Symbol | None:+ name_node = member.child_by_field_name("name")+ params_node = member.child_by_field_name("parameters")+ if name_node is None or params_node is None:+ return None+ name = node_text(name_node, src).strip()+ params = node_text(params_node, src).strip()+ modifiers = _modifiers(member, src)+ is_static = "static" in modifiers+ if not is_static:+ rest = params[1:-1].strip()+ params = f"(this {receiver}{', ' + rest if rest else ''})"+ type_node = member.child_by_field_name("type")+ returns = f" -> {node_text(type_node, src).strip()}" if type_node is not None else ""+ symbol = build_synthetic_symbol(+ name=name,+ kind="method",+ signature=f"{name}{params}{returns}",+ start_line=member.start_point[0] + 1,+ end_line=member.end_point[0] + 1,+ file_info=file_info,+ parent_name=holder,+ visibility=next((m for m in modifiers if m in _ACCESS), "private"),+ )+ # Every extension member compiles to a static method of the holder.+ symbol.modifiers = tuple(modifiers) if is_static else (*modifiers, "static")+ return symbol+++def csharp_extension_block_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:+ """Emit each member of an extension block as a method of its holder class."""+ out: list[Symbol] = []+ for block, holder in _extension_blocks(root, src):+ params_node = block.child_by_field_name("parameters")+ body = block.child_by_field_name("body")+ if params_node is None or body is None:+ continue+ receiver = node_text(params_node, src).strip()[1:-1].strip()+ if not receiver:+ continue+ for member in body.children:+ if member.type == "local_function_statement":+ symbol = _member_symbol(member, receiver, holder, src, file_info)+ if symbol is not None:+ out.append(symbol)+ return out+++def drop_extension_block_symbols(symbols: list[Symbol], root: Node, src: str) -> list[Symbol]:+ """Remove the ``extension`` method the symbol pass makes of each block."""+ blocks = {(holder, block.start_point[0] + 1) for block, holder in _extension_blocks(root, src)}+ if not blocks:+ return symbols+ return [+ s+ for s in symbols+ if not (+ s.name == _EXTENSION+ and s.kind == "method"+ and any(+ holder == s.parent_name and s.start_line <= line <= s.end_line+ for holder, line in blocks+ )+ )+ ]diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 83fa7ef70..d3fd09821 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -65,6 +65,7 @@ from .extractors.bindings.ts_js import (dynamic_import_bindings,)from .extractors.synthetic_symbols import extract_synthetic_symbols+from .extractors.synthetic_symbols.csharp_extension_blocks import drop_extension_block_symbolsfrom .extractors.visibility import (py_module_all_names,refine_cpp_visibility,@@ -1630,6 +1631,10 @@ class ASTParser:# another arity. A language without one dedupes on the id alone.existing = {(s.id, symbol_discriminator(s)) for s in symbols}symbols.extend(s for s in synthetic if (s.id, symbol_discriminator(s)) not in existing)+ if lang == "csharp":+ # The grammar reads a C# 14 extension block as a constructor+ # named ``extension``; its members were added above instead.+ symbols = drop_extension_block_symbols(symbols, root, src)# Before calls and references are extracted, so both attribute to the# final ids. Anonymous members go last, once the overloads holding them# carry their discriminators.diff --git a/tests/unit/dead_code/test_csharp_reachability.py b/tests/unit/dead_code/test_csharp_reachability.pyindex ab10790c5..cee2e7b49 100644--- a/tests/unit/dead_code/test_csharp_reachability.py+++ b/tests/unit/dead_code/test_csharp_reachability.py@@ -398,3 +398,56 @@ def test_an_export_used_only_in_its_own_file_is_demoted_not_dropped(tmp_path: Pa(finding,) = [f for f in report.findings if f.symbol_name == "CreateRequest"]assert finding.confidence < 0.4assert "Used in its own file at App/Create.cs:2" in finding.evidence[-1]+++def _extension_block_findings(tmp_path: Path, main_body: str) -> set[tuple[str, str | None]]:+ """Dead-code findings for a C# 14 extension-block holder, parsed end to end."""+ from repowise.core.pipeline.incremental import build_repo_graph++ files = {+ "App/App.csproj": _csproj(),+ "App/Extensions/StringExtensions.cs": (+ "namespace App.Extensions;\n\n"+ "public static class StringExtensions\n{\n"+ " extension(string value)\n {\n"+ " public bool IsBlank()\n {\n"+ " return string.IsNullOrWhiteSpace(value);\n }\n"+ " }\n}\n"+ ),+ "App/Program.cs": (+ "using System;\nusing App.Extensions;\n\nnamespace App;\n\n"+ "public static class Program\n{\n"+ " public static void Main(string[] args)\n {\n"+ ' var name = args.Length > 0 ? args[0] : "";\n'+ f" {main_body}\n"+ " }\n}\n"+ ),+ }+ for rel, text in files.items():+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text)+ _, sources, builder, _, _ = build_repo_graph(+ tmp_path, [], collect_sources=True, log=lambda *a, **k: None, read_only=True+ )+ report = DeadCodeAnalyzer(+ builder.graph(),+ {},+ parsed_files=builder._parsed_files,+ source_map=sources,+ repo_root=tmp_path,+ ).analyze({"min_confidence": 0.0})+ return {+ (f.kind.value, f.symbol_name)+ for f in report.findings+ if f.file_path == "App/Extensions/StringExtensions.cs"+ }+++def test_a_called_extension_block_keeps_its_holder(tmp_path: Path) -> None:+ assert _extension_block_findings(tmp_path, "Console.WriteLine(name.IsBlank());") == set()+++def test_an_extension_block_nobody_calls_is_still_reported(tmp_path: Path) -> None:+ findings = _extension_block_findings(tmp_path, "Console.WriteLine(name);")+ assert ("unused_export", "StringExtensions") in findingsdiff --git a/tests/unit/ingestion/test_csharp_synthetic_symbols.py b/tests/unit/ingestion/test_csharp_synthetic_symbols.pyindex 5b584ae86..982e073ce 100644--- a/tests/unit/ingestion/test_csharp_synthetic_symbols.py+++ b/tests/unit/ingestion/test_csharp_synthetic_symbols.py@@ -112,3 +112,88 @@ public partial class Vm {result = parser.parse_file(fi, b"def Save(): pass\n")# Nothing should have been added beyond the real ``Save``.assert [s.name for s in result.symbols] == ["Save"]+++class TestExtensionBlocks:+ """C# 14 ``extension(...)`` blocks, which the grammar reads as a constructor."""++ _SRC = b"""\+public static class StringExtensions+{+ extension(string value)+ {+ public bool IsBlank()+ {+ return string.IsNullOrWhiteSpace(value);+ }++ public bool StartsWithAny(char first, char second) => value.Length > 0;++ public static string Create(int count)+ {+ return new string('x', count);+ }+ }+}+"""++ def _methods(self, parser: ASTParser, src: bytes) -> dict[str, object]:+ result = parser.parse_file(_file("StringExtensions.cs"), src)+ return {s.name: s for s in result.symbols if s.kind == "method"}++ def test_block_members_become_extension_methods_of_the_holder(+ self, parser: ASTParser+ ) -> None:+ methods = self._methods(parser, self._SRC)+ assert "extension" not in methods+ blank = methods["IsBlank"]+ assert blank.parent_name == "StringExtensions"+ assert blank.signature == "IsBlank(this string value) -> bool"+ assert blank.visibility == "public"+ assert "static" in blank.modifiers+ assert methods["StartsWithAny"].signature == (+ "StartsWithAny(this string value, char first, char second) -> bool"+ )++ def test_static_block_member_has_no_receiver(self, parser: ASTParser) -> None:+ create = self._methods(parser, self._SRC)["Create"]+ assert create.parent_name == "StringExtensions"+ assert create.signature == "Create(int count) -> string"+ assert "static" in create.modifiers++ def test_classic_extension_method_is_unchanged(self, parser: ASTParser) -> None:+ src = b"""\+public static class ClassicExtensions+{+ public static bool IsShort(this string value) { return value.Length < 3; }+}+"""+ methods = self._methods(parser, src)+ assert set(methods) == {"IsShort"}+ assert methods["IsShort"].signature == "IsShort(this string value) -> bool"++ def test_a_block_that_does_not_parse_is_left_alone(self, parser: ASTParser) -> None:+ # The grammar cannot read an extension property, so the block is left+ # as the symbol pass found it.+ src = b"""\+public static class StringExtensions+{+ extension(string value)+ {+ public bool IsEmpty => value.Length == 0;+ }+}+"""+ assert set(self._methods(parser, src)) == {"extension"}++ def test_a_real_constructor_is_kept(self, parser: ASTParser) -> None:+ # Not a static class, so ``extension(...)`` here is a real constructor+ # of a class named ``extension``.+ src = b"""\+public class extension+{+ public extension(int size) { }+}+"""+ result = parser.parse_file(_file("Extension.cs"), src)+ assert any(s.name == "extension" and s.kind == "method" for s in result.symbols)