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(graph): record the visibility a C# declaration actually has (#1644)

Raghav Chamadiya0714fd971877
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 3d7cddbc8..ef02a374c 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -1,12 +1,13 @@
"""Per-language visibility determination functions.
Most languages can determine visibility from a symbol's name + modifier
-text alone (the ``visibility_fn`` shape). C/C++ is the exception: its
-visibility comes from surrounding AST context — ``public:`` / ``private:``
-access specifier siblings inside a class body, ``static`` storage class
-at file scope, or ``__declspec(dllexport)`` / GCC visibility attributes.
-``refine_cpp_visibility`` handles that node-aware refinement; the
-parser calls it after the generic ``visibility_fn`` for C/C++ files.
+text alone (the ``visibility_fn`` shape). Some cannot, because the answer
+depends on surrounding AST context — C/C++ ``public:`` / ``private:``
+access specifier siblings, ``static`` storage class at file scope and
+``__declspec(dllexport)`` attributes; C#'s no-modifier default, which
+differs by enclosing declaration; TS/JS export position. Each has a
+``refine_*_visibility`` the parser calls after the generic
+``visibility_fn``.
"""
from __future__ import annotations
@@ -78,7 +79,13 @@ def kotlin_visibility(_name: str, modifier_texts: list[str]) -> str:
def csharp_visibility(_name: str, modifier_texts: list[str]) -> str:
- """C# visibility — public/private/protected/internal, default internal."""
+ """C# visibility — public/private/protected/internal.
+
+ The no-modifier default returned here is the *top-level type* one;
+ every other declaration site has a different default that depends on
+ what encloses it, which this signature cannot see.
+ ``refine_csharp_visibility`` corrects it from the AST.
+ """
combined = " ".join(modifier_texts).lower()
if "private" in combined:
return "private"
@@ -88,7 +95,7 @@ def csharp_visibility(_name: str, modifier_texts: list[str]) -> str:
return "internal"
if "public" in combined:
return "public"
- return "internal" # C# default is internal
+ return "internal"
def swift_visibility(_name: str, modifier_texts: list[str]) -> str:
@@ -203,6 +210,84 @@ def refine_ts_visibility(
return "private"
+# ---------------------------------------------------------------------------
+# C# node-aware visibility refinement
+# ---------------------------------------------------------------------------
+
+_CS_ACCESS_KEYWORDS = frozenset({"public", "private", "protected", "internal"})
+
+# What a declaration with no accessibility modifier defaults to, keyed by the
+# declaration that encloses it. Anything not listed (a namespace, or the
+# compilation unit) leaves the top-level-type default of ``internal`` standing.
+# ``record struct`` is a ``record_declaration`` carrying a ``struct`` token,
+# not a node type of its own, so it needs no entry.
+_CS_DEFAULT_BY_ENCLOSING: dict[str, str] = {
+ "interface_declaration": "public",
+ "class_declaration": "private",
+ "struct_declaration": "private",
+ "record_declaration": "private",
+ "enum_declaration": "public",
+}
+
+
+def _csharp_declared_access(def_node: Node) -> str | None:
+ """The accessibility the declaration writes, or ``None`` if it writes none.
+
+ Read from the AST rather than from the captured modifier texts. The
+ queries capture a single ``(modifier)`` child and the parser's dedup keeps
+ the first match, so ``static internal void M()`` arrives at the
+ ``visibility_fn`` as ``["static"]`` with the accessibility dropped —
+ every declaration that writes a non-accessibility modifier first is
+ invisible to text alone.
+
+ The keyword is the ``modifier`` node's own child type, so this never
+ slices the source: ``src`` is decoded text and node offsets are byte
+ offsets, which diverge after any multi-byte character (a leading UTF-8
+ BOM is enough).
+ """
+ written = {
+ keyword.type for c in def_node.children if c.type == "modifier" for keyword in c.children
+ } & _CS_ACCESS_KEYWORDS
+ if not written:
+ return None
+ # Same precedence the modifier-text fn uses, so a pair reads identically
+ # whichever half the capture happened to keep: ``private protected`` is
+ # recorded private, ``protected internal`` protected.
+ for keyword in ("private", "protected", "internal", "public"):
+ if keyword in written:
+ return keyword
+ return None
+
+
+def refine_csharp_visibility(def_node: Node, current_visibility: str) -> str:
+ """Give a C# declaration the accessibility it writes, else its scope's default.
+
+ ``csharp_visibility`` sees modifier text only, and that text is both
+ truncated (see ``_csharp_declared_access``) and defaulted to the
+ top-level-type answer. The real default is ``private`` inside a
+ class/struct/record and ``public`` inside an interface or enum — a
+ two-bucket error that puts most C# members in the wrong dead-code pool.
+ """
+ declared = _csharp_declared_access(def_node)
+ if declared is not None:
+ return declared
+ # An explicit interface implementation (``void IFoo.Bar() { }``) forbids
+ # modifiers and is unreachable through the class, only through the
+ # interface. Calling it private would put a member with a live caller
+ # into the narrow dead-code pool.
+ if any(c.type == "explicit_interface_specifier" for c in def_node.children):
+ return "public"
+ node = def_node.parent
+ while node is not None:
+ default = _CS_DEFAULT_BY_ENCLOSING.get(node.type)
+ if default is not None:
+ return default
+ if node.type in ("namespace_declaration", "file_scoped_namespace_declaration"):
+ break
+ node = node.parent
+ return current_visibility
+
+
# ---------------------------------------------------------------------------
# C / C++ node-aware visibility refinement
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 70a46a784..c12db4770 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -51,6 +51,7 @@ from .extractors.bindings.ts_js import (
from .extractors.synthetic_symbols import extract_synthetic_symbols
from .extractors.visibility import (
refine_cpp_visibility,
+ refine_csharp_visibility,
refine_ts_visibility,
ts_deferred_export_names,
)
@@ -698,6 +699,10 @@ class ASTParser:
# modifier text. Refine after the generic fn ran.
if file_info.language in ("cpp", "c"):
visibility, is_exported_symbol = refine_cpp_visibility(def_node, visibility, src)
+ # C#: an unmodified declaration's default depends on what encloses
+ # it, which the modifier-text fn cannot see.
+ elif file_info.language == "csharp":
+ visibility = refine_csharp_visibility(def_node, visibility)
# TS/JS: a top-level declaration is only public when exported —
# inline, via ``export { x }`` lists, or ``export default x``.
elif file_info.language in _TS_JS_LANGUAGES:
diff --git a/tests/unit/ingestion/test_csharp_visibility_defaults.py b/tests/unit/ingestion/test_csharp_visibility_defaults.py
new file mode 100644
index 000000000..ad76f7d4e
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_visibility_defaults.py
@@ -0,0 +1,268 @@
+"""A C# declaration with no accessibility modifier takes its enclosing scope's default.
+
+``csharp_visibility`` sees modifier text only, so it can return one default for
+every declaration site. That default is the top-level-type one, ``internal``.
+The real default is ``private`` inside a class/struct/record and ``public``
+inside an interface or an enum, so unmodified members used to land in the wrong
+dead-code pool. ``refine_csharp_visibility`` supplies the enclosing scope.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _visibility(src: str, path: str = "src/Thing.cs") -> dict[str, str]:
+ info = FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="csharp",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = _PARSER.parse_file(info, src.encode("utf-8"))
+ return {s.name: s.visibility for s in parsed.symbols}
+
+
+def test_unmodified_class_members_are_private() -> None:
+ src = """
+namespace N
+{
+ class Service
+ {
+ void Run() { }
+ int _count;
+ string Name { get; set; }
+ Service() { }
+ delegate int Handler(int x);
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Run"] == "private"
+ assert vis["_count"] == "private"
+ assert vis["Name"] == "private"
+ assert vis["Service"] == "private" # the constructor shadows the class name
+ assert vis["Handler"] == "private"
+
+
+def test_unmodified_struct_and_record_members_are_private() -> None:
+ src = """
+namespace N
+{
+ struct Point { void Shift() { } }
+ record Order { void Total() { } }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Shift"] == "private"
+ assert vis["Total"] == "private"
+
+
+def test_interface_members_are_public() -> None:
+ src = """
+namespace N
+{
+ interface IRepository
+ {
+ void Save();
+ int Count { get; }
+ event System.Action Changed;
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Save"] == "public"
+ assert vis["Count"] == "public"
+ assert vis["Changed"] == "public"
+
+
+def test_enum_members_are_public() -> None:
+ src = """
+namespace N
+{
+ enum Mode { Fast, Slow }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Fast"] == "public"
+ assert vis["Slow"] == "public"
+
+
+def test_nested_types_are_private_and_top_level_types_stay_internal() -> None:
+ src = """
+namespace N
+{
+ class Outer
+ {
+ class Inner { }
+ enum Kind { A }
+ }
+ class TopLevel { }
+ interface ITop { }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Inner"] == "private"
+ assert vis["Kind"] == "private"
+ assert vis["TopLevel"] == "internal"
+ assert vis["ITop"] == "internal"
+
+
+def test_top_level_type_outside_any_namespace_stays_internal() -> None:
+ vis = _visibility("class Loose { void M() { } }")
+ assert vis["Loose"] == "internal"
+ assert vis["M"] == "private"
+
+
+def test_explicit_modifiers_win_everywhere() -> None:
+ src = """
+namespace N
+{
+ public class Service
+ {
+ public void Open() { }
+ private void Close() { }
+ protected void Reset() { }
+ internal void Sync() { }
+ }
+ interface IThing
+ {
+ internal void Hidden();
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Service"] == "public"
+ assert vis["Open"] == "public"
+ assert vis["Close"] == "private"
+ assert vis["Reset"] == "protected"
+ assert vis["Sync"] == "internal"
+ assert vis["Hidden"] == "internal"
+
+
+def test_accessibility_written_after_another_modifier_still_wins() -> None:
+ """The queries capture one ``(modifier)`` and the parser keeps the first
+ match, so ``static internal`` reaches the refinement as ``["static"]``.
+ Reading the modifiers off the node is what keeps these correct."""
+ src = """
+namespace N
+{
+ class Service
+ {
+ static internal void Sync() { }
+ abstract public void Open();
+ static public int Count;
+ new public void Reset() { }
+ override public string ToString() => "";
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Sync"] == "internal"
+ assert vis["Open"] == "public"
+ assert vis["Count"] == "public"
+ assert vis["Reset"] == "public"
+ assert vis["ToString"] == "public"
+
+
+def test_paired_accessibility_keywords_keep_one_precedence() -> None:
+ """Whichever half of the pair the capture kept, the recorded answer is the
+ same — the refinement reads both keywords off the node."""
+ src = """
+namespace N
+{
+ class Service
+ {
+ protected internal void A() { }
+ internal protected void B() { }
+ private protected void C() { }
+ protected private void D() { }
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["A"] == vis["B"] == "protected"
+ assert vis["C"] == vis["D"] == "private"
+
+
+def test_explicit_interface_implementation_is_public() -> None:
+ """It carries no modifier and is reachable only through the interface, so
+ ``private`` would drop a member with a live caller into the narrow pool."""
+ vis = _visibility("namespace N { class Handler : IHandler { void IHandler.Handle() { } } }")
+ assert vis["Handle"] == "public"
+
+
+def test_record_struct_members_are_private() -> None:
+ vis = _visibility("namespace N { record struct Point { void Shift() { } } }")
+ assert vis["Shift"] == "private"
+
+
+def test_non_accessibility_modifiers_do_not_block_the_default() -> None:
+ src = """
+namespace N
+{
+ class Service
+ {
+ static void Boot() { }
+ async void Tick() { }
+ }
+}
+"""
+ vis = _visibility(src)
+ assert vis["Boot"] == "private"
+ assert vis["Tick"] == "private"
+
+
+def test_a_leading_byte_order_mark_does_not_shift_the_modifiers() -> None:
+ """Node offsets are byte offsets and the parser's source is decoded text,
+ so anything that reads modifiers by slicing the source loses them after
+ the first multi-byte character. Visual Studio writes the BOM by default,
+ which makes this the common case on C# repos, not the corner one."""
+ info = FileInfo(
+ path="src/Constants.cs",
+ abs_path="/repo/src/Constants.cs",
+ language="csharp",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ src = b"\xef\xbb\xbfnamespace N;\n\npublic static class Outer\n{\n public static class Roles { }\n static internal void Sync() { }\n void Hidden() { }\n}\n"
+ vis = {s.name: s.visibility for s in _PARSER.parse_file(info, src).symbols}
+ assert vis["Outer"] == "public"
+ assert vis["Roles"] == "public"
+ assert vis["Sync"] == "internal"
+ assert vis["Hidden"] == "private"
+
+
+def test_swift_default_is_unchanged() -> None:
+ info = FileInfo(
+ path="src/Thing.swift",
+ abs_path="/repo/src/Thing.swift",
+ language="swift",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ parsed = _PARSER.parse_file(info, b"class Service {\n func run() { }\n}\n")
+ vis = {s.name: s.visibility for s in parsed.symbols}
+ assert vis["Service"] == "internal"
+ assert vis["run"] == "internal"