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): type C# PascalCase property and field receivers from the enclosing class (#4823)

Swati Ahujab51e5d871c6c
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index ff84a75c0..35cc94cd8 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -52,7 +52,8 @@ class _LanguageCallStrategies:
call chained on another call (``a.b().c()``) alone, which is resolved by
its inner call's return type or not at all. ``inherited_typed_receiver`` lets a typed
receiver whose type lacks the method answer with the one ancestor that
- declares it.
+ declares it; ``inherited_fields`` lets a receiver be typed from a field an
+ ancestor declares.
"""
free: tuple[str, ...] = ()
@@ -63,6 +64,7 @@ class _LanguageCallStrategies:
member_bare_fallback: bool = True
chain_bare_fallback: bool = True
inherited_typed_receiver: bool = False
+ inherited_fields: bool = False
_NO_LANGUAGE_STRATEGIES = _LanguageCallStrategies()
@@ -144,6 +146,7 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
member_fallback=_TYPED_RECEIVER,
member_bare_fallback=False,
inherited_typed_receiver=True,
+ inherited_fields=True,
),
# A chained call keeps no bare-name fallback: ``.send()`` on a result the
# return type does not type is not the repo's ``send``.
@@ -151,7 +154,9 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER, chain_bare_fallback=False
),
"csharp": _LanguageCallStrategies(
- free_fallback=("_resolve_csharp_constructed_type",), member_fallback=_TYPED_RECEIVER
+ free_fallback=("_resolve_csharp_constructed_type",),
+ member_fallback=_TYPED_RECEIVER,
+ inherited_fields=True,
),
"python": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
# Swift and Dart register the fallback: neither has a package tier of its
@@ -180,6 +185,7 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
member_fallback=_TYPED_RECEIVER,
member_bare_fallback=False,
inherited_typed_receiver=True,
+ inherited_fields=True,
),
}
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
index 9b889e62d..ed7671387 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
@@ -325,16 +325,18 @@ class ReceiverTypingMixin(
declaration shapes, and a method name no class in the repo declares.
"""
receiver_name = call.receiver_name or ""
- # A capitalised receiver already names a type and every tier above has
- # tried it. An underscore one cannot be anything but a name.
- head = receiver_name[:1]
- if not (head.islower() or head == "_") or receiver_name in ("self", "this"):
+ if receiver_name in ("self", "this"):
return None
-
parsed = self._parsed_files.get(file_path)
language = parsed.file_info.language if parsed else ""
if language not in RECEIVER_TYPE_LANGUAGES:
return None
+ # A capitalised receiver already names a type and every tier above has
+ # tried it, so only a C# one is read further: C# spells its properties
+ # and many fields that way. An underscore one cannot be anything but a name.
+ head = receiver_name[:1]
+ if not (head.islower() or head == "_" or language == "csharp"):
+ return None
# Refuse before reading the file: nothing resolves unless some class
# declares a method of this name or an extension carries it, which a
@@ -585,7 +587,7 @@ class ReceiverTypingMixin(
A name the body binds with no readable type is a local and refuses both.
"""
- if not builtin_local and name in self._bound_names_in(file_path, caller_id, language):
+ if not builtin_local and self._body_binds(file_path, caller_id, language, name):
return None
class_file, class_id = self._field_owner(file_path, caller_id, language)
fields = self._field_types_in(class_file, language).get(class_id, {})
@@ -644,18 +646,28 @@ class ReceiverTypingMixin(
for d in self._declarations_for(class_file, language)
)
+ def _body_binds(self, file_path: str, caller_id: str, language: str, name: str) -> bool:
+ """Does the calling body bind *name*, with or without a readable type?
+
+ The binding scan reads lowercase names, so a capitalised one (a C#
+ ``Foo Rules`` parameter) is asked of the caller's declarations too.
+ """
+ if name in self._bound_names_in(file_path, caller_id, language):
+ return True
+ return name[:1].isupper() and self._declares_name(file_path, caller_id, name)
+
def _inherited_field(
self, file_path: str, caller_id: str, class_id: str, name: str, language: str
) -> tuple[str, str | None] | None:
"""``(declaring file, type)`` of the field *name* the nearest superclass declares.
- Only where a typed receiver may reach an ancestor (Java). The
+ Only where a language reads ancestors' fields (Java, Apex, C#). The
declaration scan skips a type it cannot read (``b.Reader x``,
``int[] x``), so the caller, its class and each superclass passed are
also asked whether they declare the name at all: one that does hides
the rest, and refuses.
"""
- if not self._strategies_for(file_path).inherited_typed_receiver:
+ if not self._strategies_for(file_path).inherited_fields:
return None
if self._declares_name(file_path, caller_id, name) or self._declares_name(
file_path, class_id, name
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index 862f5ff38..7374e5bbc 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -54,6 +54,23 @@ _INFERRED_FROM_NEW = re.compile(
r"(?<![\w.])var\s+(?P<name>[a-z_]\w*)\s*=\s*new\s+(?P<type>[A-Z]\w*(?:\.\w+)*)"
)
+# A C# property (``Foo Name { get; }``, ``Foo Name => _foo;``) or PascalCase
+# field (``Foo Name;``), which ``_TYPED_DECLARATION``'s lowercase name never
+# reads. Anchored to the start of a line, past attributes and modifiers, so
+# title-case words in a string or a switch arm (``Circle C => ..``) are no
+# member. The ``{`` closer must open accessors, or ``Foo Bar {`` could be a
+# type. Ceiling: a builtin-typed one (``string Name { get; }``) and a second
+# declarator (``Foo A, B;``) are not read.
+_CS_MODIFIERS = (
+ r"public|private|protected|internal|static|readonly|virtual|override|abstract|"
+ r"sealed|new|required|volatile|event|unsafe|extern|partial"
+)
+_CS_MEMBER = re.compile(
+ rf"(?m)^[ \t]*(?:\[[^\]\n]*\][ \t]*)*(?:(?:{_CS_MODIFIERS})[ \t]+)*"
+ rf"(?P<type>{_TYPE})\??[ \t]+(?P<name>[A-Z]\w*)[ \t]*(?=(?P<closer>[;=](?!=)|"
+ r"\{(?=\s*(?:(?:private|protected|internal)\s+)*(?:get|set|init)\b)))"
+)
+
# Truncating at ``//`` also cuts a URL in a string: it can only lose a
# declaration, never invent one.
_LINE_COMMENT = re.compile(r"//.*")
@@ -350,7 +367,7 @@ _LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
# Apex declares Java's way (``Foo foo``) and has no ``var``.
"apex": (_TYPED_DECLARATION,),
"cpp": (_CPP_DECLARATION,),
- "csharp": _C_FAMILY,
+ "csharp": (*_C_FAMILY, _CS_MEMBER),
"dart": _DART_FAMILY,
"go": _GO_FAMILY,
"java": (
@@ -937,8 +954,9 @@ _FIELD_CLOSERS = frozenset({";", "="})
# semicolon-free TypeScript ``x: T`` are fields too. Kotlin and Swift keep a
# closer only on a `val`/`var`/`let` match, so no parameter reaches here: a
# Kotlin constructor property (`class R @Inject constructor(private val api:
-# Api)`) closes on `,` or `)`, a Swift computed property on `{`.
+# Api)`) closes on `,` or `)`, a Swift computed property on `{`, as a C# one does.
_LANGUAGE_FIELD_CLOSERS: dict[str, frozenset[str]] = {
+ "csharp": frozenset({";", "=", "{"}),
"kotlin": frozenset({"=", "\n", ",", ")"}),
"python": frozenset({"=", "\n"}),
"swift": frozenset({"=", "\n", "{"}),
@@ -1010,23 +1028,28 @@ def _inside_parentheses(cleaned: str) -> Callable[[int], bool]:
return inside
-# Kotlin and Swift run code at class scope that is not a function: an ``init``
-# block, a lambda or closure a property holds. A declaration there is a local
-# of that block, so only one directly in a type's body may be a field.
-_TYPE_BODY_SCOPED_LANGUAGES = frozenset({"kotlin", "swift"})
+# Kotlin, Swift and C# run code at class scope that is not a function: an
+# ``init`` block, a lambda or closure a property holds, a property accessor. A
+# declaration there is a local of that block, so only one directly in a type's
+# body may be a field. C# has its own keywords: ``object`` is a type there.
_BRACE = re.compile(r"[{};]")
# A function, accessor or initialiser declared after a bodiless type.
_CODE_HEADER = re.compile(r"\b(?:fun|func|init|get|set)\b")
_TYPE_HEADER = re.compile(r"\b(?:class|object|interface|struct|enum|extension|protocol|actor)\b")
+_TYPE_HEADERS: dict[str, re.Pattern[str]] = {
+ "csharp": re.compile(r"\b(?:class|interface|struct|enum|record)\b"),
+ "kotlin": _TYPE_HEADER,
+ "swift": _TYPE_HEADER,
+}
-def _opens_type_body(header: str) -> bool:
+def _opens_type_body(header: str, type_header: re.Pattern[str]) -> bool:
"""Does a ``{`` after *header* open a type's body?
The last type keyword decides, unless an expression leads into it:
``val f = object : T {`` is an anonymous object, not a declared type.
"""
- keywords = list(_TYPE_HEADER.finditer(header))
+ keywords = list(type_header.finditer(header))
if not keywords:
return False
before = header[: keywords[-1].start()].rstrip()
@@ -1034,7 +1057,7 @@ def _opens_type_body(header: str) -> bool:
return not before.endswith(("=", "(", ",", "return")) and not _CODE_HEADER.search(after)
-def _in_type_body(cleaned: str) -> Callable[[int], bool]:
+def _in_type_body(cleaned: str, type_header: re.Pattern[str]) -> Callable[[int], bool]:
"""Is the innermost ``{`` open at an offset of *cleaned* a type's body (or none)?
None counts: a primary constructor's ``val`` parameters sit before any brace.
@@ -1050,7 +1073,7 @@ def _in_type_body(cleaned: str) -> Callable[[int], bool]:
for match in _BRACE.finditer(cleaned):
char = match.group()
if char == "{":
- stack.append(_opens_type_body(cleaned[segment_start : match.start()]))
+ stack.append(_opens_type_body(cleaned[segment_start : match.start()], type_header))
elif char == "}" and stack:
stack.pop()
segment_start = match.end()
@@ -1080,7 +1103,8 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
resolved: dict[str, tuple[str | None, bool]] = {}
found: list[Declaration] = []
inside = _inside_parentheses(cleaned) if language in _PARAMETERS_AT_CLASS_SCOPE else None
- in_type_body = _in_type_body(cleaned) if language in _TYPE_BODY_SCOPED_LANGUAGES else None
+ type_header = _TYPE_HEADERS.get(language)
+ in_type_body = _in_type_body(cleaned, type_header) if type_header else None
for pattern in patterns:
for match in pattern.finditer(cleaned):
if pattern is _KT_CONSTRUCTED_LAMBDA and not _ends_statement(
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index d4e74261a..c2c70435c 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -455,6 +455,140 @@ class TestFieldTypedReceiver:
)
assert not [e for e in _edges(parsed, tmp_path) if e[3].startswith("receiver_field_")]
+ @pytest.mark.parametrize(
+ "member",
+ [
+ "public Box Rules { get; } = new Box();",
+ "public Box Rules => _box;",
+ "private readonly Box Rules;",
+ ],
+ )
+ def test_a_csharp_pascal_case_member_types_its_receiver(
+ self, tmp_path: Path, member: str
+ ) -> None:
+ """``Rules.Add(1)``: no type is named ``Rules``, so the property is the receiver."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": (
+ "csharp",
+ f"class V\n{{\n {member}\n void Run() {{ Rules.Add(1); }}\n}}\n",
+ ),
+ "Box.cs": ("csharp", "public class Box\n{\n public void Add(int x) { }\n}\n"),
+ },
+ )
+ assert ("V.cs::V::Run", "Box.cs::Box::Add", 0.75, "receiver_field_global") in _edges(
+ parsed, tmp_path
+ )
+
+ def test_a_csharp_type_of_the_receiver_s_name_still_wins(self, tmp_path: Path) -> None:
+ """A static ``Rules.Add`` the repo declares is read before the property."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": (
+ "csharp",
+ "class V\n{\n public Box Rules { get; }\n"
+ " void Run() { Rules.Add(1); }\n}\n",
+ ),
+ "Box.cs": ("csharp", "public class Box\n{\n public void Add(int x) { }\n}\n"),
+ "Rules.cs": (
+ "csharp",
+ "public static class Rules\n{\n public static void Add(int x) { }\n}\n",
+ ),
+ },
+ )
+ callees = {e[1] for e in _edges(parsed, tmp_path) if e[0] == "V.cs::V::Run"}
+ assert callees == {"Rules.cs::Rules::Add"}
+
+ def test_a_csharp_property_an_ancestor_declares(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": ("csharp", "class V : Base\n{\n void Run() { Rules.Add(1); }\n}\n"),
+ "Base.cs": (
+ "csharp",
+ "abstract class Base\n{\n protected Box Rules { get; set; }\n}\n",
+ ),
+ "Box.cs": ("csharp", "public class Box\n{\n public void Add(int x) { }\n}\n"),
+ },
+ )
+ resolver = CallResolver(
+ parsed,
+ {p: set() for p in parsed},
+ repo_path=str(tmp_path),
+ heritage_parents={"V.cs::V": {"Base.cs::Base"}},
+ )
+ edges = [
+ (rc.callee_id, rc.origin) for rc in resolver.resolve_file("V.cs", parsed["V.cs"].calls)
+ ]
+ assert edges == [("Box.cs::Box::Add", "receiver_field_global")]
+
+ def test_a_capitalised_receiver_no_member_names_gets_no_edge(self, tmp_path: Path) -> None:
+ """``Console.WriteLine`` is the BCL's, whatever repo class has a ``WriteLine``."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": ("csharp", "class V\n{\n void Run() { Console.WriteLine(1); }\n}\n"),
+ "Box.cs": ("csharp", "public class Box\n{\n public void WriteLine(int x) { }\n}\n"),
+ },
+ )
+ assert not [e for e in _edges(parsed, tmp_path) if e[0] == "V.cs::V::Run"]
+
+ @pytest.mark.parametrize(
+ "holder",
+ [
+ "void Run()\n {\n Result Check = Compute();\n }",
+ "public int P\n {\n get\n {\n Result Check = Compute();\n"
+ " return 1;\n }\n }",
+ "Action A = () =>\n {\n Result Check = Compute();\n };",
+ ],
+ ids=["method", "accessor", "lambda"],
+ )
+ def test_a_csharp_body_local_types_no_receiver_elsewhere(
+ self, tmp_path: Path, holder: str
+ ) -> None:
+ """``Result Check = ..`` inside a body is that body's local, not a field."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": ("csharp", f"class V\n{{\n {holder}\n void Other() {{ Check.Go(); }}\n}}\n"),
+ "Result.cs": ("csharp", "public class Result\n{\n public void Go() { }\n}\n"),
+ },
+ )
+ assert not [e for e in _edges(parsed, tmp_path) if e[1] == "Result.cs::Result::Go"]
+
+ def test_a_csharp_field_beside_an_accessor_local_still_types(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": (
+ "csharp",
+ "namespace N\n{\n record V\n {\n Result Check = Compute();\n"
+ " public int P { get { Other Check = null; return 1; } }\n"
+ " void Run() { Check.Go(); }\n }\n}\n",
+ ),
+ "Result.cs": ("csharp", "public class Result\n{\n public void Go() { }\n}\n"),
+ },
+ )
+ assert [e[0] for e in _edges(parsed, tmp_path) if e[1] == "Result.cs::Result::Go"] == [
+ "V.cs::V::Run"
+ ]
+
+ def test_a_capitalised_parameter_shadows_the_property(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "V.cs": (
+ "csharp",
+ "class V\n{\n public Box Rules { get; }\n"
+ " void Run(Other Rules) { Rules.Add(1); }\n}\n",
+ ),
+ "Box.cs": ("csharp", "public class Box\n{\n public void Add(int x) { }\n}\n"),
+ },
+ )
+ assert not [e for e in _edges(parsed, tmp_path) if e[1] == "Box.cs::Box::Add"]
+
def test_a_kotlin_constructor_property_types_its_receiver(self, tmp_path: Path) -> None:
"""Hilt's `@Inject constructor(private val api: Api)`, read bare and through `this`."""
parsed = _parse_all(
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index a1ce04385..15ccfecd1 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -103,6 +103,42 @@ class TestCsharpShapes:
body = "public void Go() { if (thing is Placeholder p) { p.Name(); } }"
assert declared_types(body, "csharp")["p"] == "Placeholder"
+ def test_pascal_case_properties_and_fields_are_class_scope(self) -> None:
+ source = (
+ "class V {\n"
+ " public TrackingCollection<Rule> Rules { get; } = new();\n"
+ " protected Box? Current { private set; get; }\n"
+ " public Box Shown => _box;\n"
+ " internal readonly ICircuitController<int> BreakerController;\n"
+ " void Run() { }\n"
+ "}"
+ )
+ assert fields(source, "csharp", [(6, 6)]) == {
+ "Rules": "TrackingCollection`1",
+ "Current": "Box",
+ "Shown": "Box",
+ "BreakerController": "ICircuitController`1",
+ }
+
+ def test_a_type_or_method_header_declares_no_member(self) -> None:
+ source = (
+ "class V : Base {\n"
+ " public Box Make(int n) => new Box();\n"
+ " public Result Check { get { return Ok; } }\n"
+ " bool Same(Box a) => a == Other;\n"
+ "}"
+ )
+ assert fields(source, "csharp", []) == {"Check": "Result"}
+
+ def test_title_case_words_mid_line_declare_no_member(self) -> None:
+ source = (
+ "class V {\n"
+ ' private const string Label = "Order Items;";\n'
+ " int Area(Shape s) => s switch { Circle C => 1, _ => 0 };\n"
+ "}"
+ )
+ assert fields(source, "csharp", []) == {}
+
class TestPythonShapes:
"""Python annotates after the name and constructs without a keyword.