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(csharp): type each link of a chained call from the one before (#2833)

Raghav Chamadiyab6959cf6fb53
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 7ac9caa45..c56192f74 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -42,6 +42,7 @@ from .call_receiver_typing import (
)
from .language_data import (
get_builtin_methods,
+ get_builtin_types,
get_external_receiver_types,
get_external_return_types,
)
@@ -136,7 +137,7 @@ def _is_property_accessor(sym: Any) -> bool:
# Languages admitted to the full return-type chain lane; each is admitted
# explicitly, once measured.
-PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset({"cpp", "go"})
+PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset({"cpp", "csharp", "go"})
# Chain lanes that need a file or import/re-export identity for the head type:
# a repository-global simple type name is not a language binding.
@@ -350,6 +351,11 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
self._init_receiver_typing_caches()
self._repo_rebound_names: dict[str, frozenset[str]] = {}
+ # {file: {(line, receiver, target): the call it is chained onto}}, and
+ # the chain links being typed right now, which a cycle would revisit.
+ self._chained_sites: dict[str, dict[tuple[int, str | None, str], CallReceiver]] = {}
+ self._chain_links_in_flight: set[tuple[str, int, str | None, str]] = set()
+ self._unindexed_extensions: frozenset[str] | None = None
# Barrel re-export origins: {barrel_file: {name: origin_file}}
self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)
@@ -959,6 +965,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return False, None
found = self._typed_receiver_target(file_path, call, caller_id, type_name)
+ if found is None and language == "csharp":
+ return self._csharp_chain_member(file_path, call, caller_id, type_name)
if language == "cpp" and not _admitted_cpp_chain(type_name, call.target_name):
# C++ admits only ``future.get()``; broader return-name matching
# is not admitted.
@@ -985,6 +993,93 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return False
return type_name in self._known_type_names
+ def _csharp_chain_member(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ type_name: str,
+ ) -> tuple[bool, ResolvedCall | None]:
+ """The member a C# chain reaches on a head type that does not declare it.
+
+ C# binds an instance method, an inherited one included, before an
+ extension, and an extension on a base type serves every type deriving
+ from it. Ancestors on two branches answering is ambiguous, and refused.
+
+ With no answer the bare-name fallback is disproved for a known type,
+ unless an extension the index leaves out carries the name: one on a
+ type parameter (``this TBuilder b``) or an external type may be it.
+ """
+ type_id = self._csharp_type_id(type_name)
+ if type_id is not None:
+ inherited = self._ancestor_method(type_id, call.target_name, caller_id)
+ if inherited is not None:
+ same_file = self._symbol_paths_by_id.get(inherited) == file_path
+ tier = "same_file" if same_file else "import"
+ return True, self._return_typed_call(caller_id, inherited, tier, call.line)
+
+ own = self._typed_extension_call(file_path, call, caller_id, type_name, "csharp")
+ if own is not None:
+ return True, own
+ ancestor_names = [
+ symbol.name
+ for ancestor in (self._ancestors_of(type_id) if type_id is not None else ())
+ if (symbol := self._symbols_by_id.get(ancestor)) is not None
+ ]
+ hits = {}
+ for name in ancestor_names:
+ hit = self._typed_extension_call(file_path, call, caller_id, name, "csharp")
+ if hit is not None:
+ hits[hit.callee_id] = hit
+ if hits:
+ return True, next(iter(hits.values())) if len(hits) == 1 else None
+ # Proven only for a type whose members were all asked: one whose every
+ # base is a repository type, or a builtin. A name the repository does
+ # not declare may be a type parameter (``TBuilder``), whose members are
+ # its constraint's.
+ known = (
+ self._lineage_is_in_repo(type_id)
+ if type_id is not None
+ else id_segment_name(type_name) in get_builtin_types("csharp")
+ )
+ return known and call.target_name not in self._unindexed_extension_names(), None
+
+ def _lineage_is_in_repo(self, class_id: str) -> bool:
+ """Does every base of *class_id* and of its ancestors resolve to a repository type?"""
+ for type_id in (class_id, *self._ancestors_of(class_id)):
+ bases = self._declared_bases(type_id)
+ if bases is None or any(base.startswith(_EXTERNAL_PREFIX) for base in bases):
+ return False
+ return True
+
+ def _csharp_type_id(self, type_name: str) -> str | None:
+ """The one C# type *type_name* (``IFoo`1`` or ``IFoo``) names repo-wide, or None."""
+ bare, _, arity = type_name.partition("`")
+ candidates = [
+ symbol
+ for sym_id in self._global_symbols.get(bare, ())
+ if (symbol := self._symbols_by_id[sym_id]).kind in _TYPE_KINDS
+ and symbol.language == "csharp"
+ and (symbol.type_parameter_count or 0) == int(arity or 0)
+ ]
+ return candidates[0].id if len(candidates) == 1 else None
+
+ def _unindexed_extension_names(self) -> frozenset[str]:
+ """Names of C# extension methods the extension index leaves out; built once.
+
+ Those extend a type parameter or an external type, so no typed lookup
+ can reach them and only the bare name still can.
+ """
+ if self._unindexed_extensions is None:
+ self._unindexed_extensions = frozenset(
+ sym.name
+ for sym in self._symbols_by_id.values()
+ if sym.language == "csharp"
+ and csharp_extension_receiver(sym.signature)
+ and self._csharp_extended_type(sym) is None
+ )
+ return self._unindexed_extensions
+
def _external_chain_return_type(
self,
file_path: str,
@@ -1027,17 +1122,53 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Admitted by its table alone; inferring from repository return
# types is not admitted for this language.
return None
+ link = (file_path, call.line, inner.receiver_name, inner.target_name)
+ if link in self._chain_links_in_flight:
+ return None
inner_call = CallSite(
target_name=inner.target_name,
receiver_name=inner.receiver_name,
caller_symbol_id=caller_id,
line=call.line,
argument_count=inner.argument_count,
+ receiver_call=self._nested_receiver_call(file_path, call.line, inner, language),
)
- resolved_inner = self._resolve_one(file_path, inner_call)
+ self._chain_links_in_flight.add(link)
+ try:
+ resolved_inner = self._resolve_one(file_path, inner_call)
+ finally:
+ self._chain_links_in_flight.discard(link)
if resolved_inner is None:
return None
- return self._callee_return_type(resolved_inner.callee_id, inner.argument_count, language)
+ # The overload the inner call's arguments select is the one whose type it returns.
+ callee_id = resolved_inner.callee_id
+ rep = self._overload_rep.get(callee_id)
+ if rep is not None:
+ callee_id = self._pick_overload(rep, inner.argument_count) or callee_id
+ return self._callee_return_type(callee_id, inner.argument_count, language)
+
+ def _nested_receiver_call(
+ self, file_path: str, line: int, inner: CallReceiver, language: str
+ ) -> CallReceiver | None:
+ """The call *inner* is itself chained onto: ``a()`` under ``a().b().c()``.
+
+ A receiver records one hop, but the parser keeps every link of a chain
+ as its own site on the chain's first line, so the hop below is read
+ off the site *inner* names. Only C# reads it; elsewhere an inner call
+ is still typed as if nothing were chained under it.
+ """
+ if language != "csharp":
+ return None
+ sites = self._chained_sites.get(file_path)
+ if sites is None:
+ parsed = self._parsed_files.get(file_path)
+ sites = {
+ (c.line, c.receiver_name, c.target_name): c.receiver_call
+ for c in (parsed.calls if parsed else ())
+ if c.receiver_call is not None
+ }
+ _store_capped(self._chained_sites, file_path, sites, _SOURCE_CACHE_FILES)
+ return sites.get((line, inner.receiver_name, inner.target_name))
def _callee_return_type(
self, callee_id: str, argument_count: int | None, language: str
@@ -1054,14 +1185,12 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
symbol_path = self._symbol_paths_by_id.get(callee_id)
if symbol_path is None:
return None
- overload_key = (
- symbol_path,
- symbol.parent_name,
- symbol.name,
- argument_count,
- )
- if len(self._overload_return_types.get(overload_key, ())) > 1:
- return None
+ # Overloads the arguments may mean, and declarations sharing this id
+ # (an extension is called one argument short of its parameters).
+ for count in {argument_count, signature_parameter_count(symbol.signature or "")}:
+ key = (symbol_path, symbol.parent_name, symbol.name, count)
+ if len(self._overload_return_types.get(key, ())) > 1:
+ return None
return type_name
def _return_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:
@@ -1671,6 +1800,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# recursion; an ancestor's declaration of the name is not the target.
if self._declares(class_id, method_name) is not None:
return None
+ return self._ancestor_method(class_id, method_name, caller_id)
+
+ def _ancestor_method(self, class_id: str, method_name: str, caller_id: str) -> str | None:
+ """The one method of this name *class_id*'s ancestors declare, never the caller."""
hits = set()
for ancestor in self._ancestors_of(class_id):
sym_id = self._declares(ancestor, method_name)
diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.py
index 031c992da..127ee4773 100644
--- a/packages/core/src/repowise/core/ingestion/return_types.py
+++ b/packages/core/src/repowise/core/ingestion/return_types.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
-from .type_names import bare_type_name
+from .type_names import bare_type_name, type_argument_count
_NULLISH_UNION = re.compile(r"\s*\|\s*(?:null|undefined)\b")
_CPP_PREFIX = re.compile(r"^(?:(?:const|volatile|typename|class|struct)\s+)+")
@@ -116,7 +116,8 @@ def normalize_return_type(raw: str, language: str) -> str | None:
Generic arguments are intentionally not unwrapped: ``future<T>.get()`` is
a method on ``future``, not on ``T``. Language-specific punctuation is
- removed here, at the boundary where signatures enter resolution.
+ removed here, at the boundary where signatures enter resolution. A C#
+ generic keeps its arity, ``IFoo`1``, as a declared receiver type does.
"""
value = raw.strip()
@@ -134,4 +135,8 @@ def normalize_return_type(raw: str, language: str) -> str | None:
value = _CPP_SUFFIX.sub("", value)
name = bare_type_name(value).strip()
- return name if name.isidentifier() else None
+ if not name.isidentifier():
+ return None
+ if language == "csharp" and (arity := type_argument_count(value)):
+ return f"{name}`{arity}"
+ return name
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index 6884494bd..f5006b4df 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -215,7 +215,7 @@ def test_unbound_global_return_type_preserves_legacy_fallback(
def test_only_audited_lanes_are_enabled_by_default() -> None:
- assert frozenset({"cpp", "go"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
+ assert frozenset({"cpp", "csharp", "go"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
def test_module_level_chain_keeps_structural_receiver(tmp_path: Path) -> None:
@@ -461,3 +461,189 @@ def test_go_external_return_type_does_not_bind_a_same_named_repo_type(tmp_path:
).resolve_file("cmd/run.go", [call])
assert resolved == []
+
+
+# A fluent C# API: every link returns an interface, and most links are
+# extension methods on it or on an interface it extends.
+_FLUENT_SYNTAX = (
+ "public interface IValidator {}\n"
+ "public interface IRuleBuilder<T, out TProperty> {\n"
+ " IRuleBuilderOptions<T, TProperty> SetValidator(IValidator validator);\n}\n"
+ "public interface IRuleBuilderInitial<T, out TProperty> : IRuleBuilder<T, TProperty> {}\n"
+ "public interface IRuleBuilderOptions<T, out TProperty> : IRuleBuilder<T, TProperty> {}\n"
+)
+_FLUENT_EXTENSIONS = (
+ "public static class Rules {\n"
+ " public static IRuleBuilderOptions<T, P> Must<T, P>"
+ "(this IRuleBuilder<T, P> rule, Func<P, bool> check) { return null; }\n"
+ " public static IRuleBuilderOptions<T, P> WithMessage<T, P>"
+ "(this IRuleBuilderOptions<T, P> rule, string text) { return rule; }\n"
+ " public static IRuleBuilderOptions<T, P> WithMessage<T, P>"
+ "(this IRuleBuilderOptions<T, P> rule, string text, int code, bool log) { return rule; }\n"
+ " public static IRuleBuilderOptions<T, P> When<T, P>"
+ "(this IRuleBuilderOptions<T, P> rule, Func<T, bool> check) { return rule; }\n"
+ "}\n"
+)
+_FLUENT_BASE = (
+ "public abstract class AbstractValidator<T> {\n"
+ " public IRuleBuilderInitial<T, P> RuleFor<P>(Func<T, P> pick) { return null; }\n"
+ " public void When(Func<T, bool> check, Action body) {}\n"
+ " public void WithMessage(string text) {}\n}\n"
+)
+_FLUENT_HERITAGE = {
+ "Syntax.cs::IRuleBuilderInitial": {"Syntax.cs::IRuleBuilder"},
+ "Syntax.cs::IRuleBuilderOptions": {"Syntax.cs::IRuleBuilder"},
+ "Validator.cs::ModelValidator": {"Base.cs::AbstractValidator"},
+}
+
+
+def _csharp_chain_edges(
+ tmp_path: Path, body: str, extra: dict[str, str] | None = None
+) -> dict[tuple[str, int | None], tuple[str, str]]:
+ """``{(method, argument count): (callee id, origin)}`` for a validator body."""
+ files = {
+ "Syntax.cs": _FLUENT_SYNTAX,
+ "Rules.cs": _FLUENT_EXTENSIONS,
+ "Base.cs": _FLUENT_BASE,
+ "Validator.cs": (
+ "public class ModelValidator : AbstractValidator<Model> {\n"
+ " public ModelValidator() { " + body + " }\n}\n"
+ ),
+ **(extra or {}),
+ }
+ parsed: dict[str, ParsedFile] = {}
+ for path, source in files.items():
+ parsed.update(_parse(tmp_path, path, "csharp", source))
+ resolver = CallResolver(parsed, {}, repo_path=str(tmp_path), heritage_parents=_FLUENT_HERITAGE)
+ edges = {}
+ for call in parsed["Validator.cs"].calls:
+ for edge in resolver.resolve_file("Validator.cs", [call]):
+ edges[(call.target_name, call.argument_count)] = (edge.callee_id, edge.origin)
+ return edges
+
+
+def test_csharp_chain_binds_the_extensions_its_links_return(tmp_path: Path) -> None:
+ """`RuleFor(..).Must(..).WithMessage(..).When(..)` is extension after extension.
+
+ `When` used to bind to the validator's own inherited `When`, as if the call
+ had no receiver. `Must` extends the interface `RuleFor`'s result inherits,
+ and `When` is typed from `WithMessage`'s result: read with no receiver,
+ that link would be the validator's own void `WithMessage`.
+ """
+ edges = _csharp_chain_edges(
+ tmp_path, 'RuleFor(x => x.Text).Must(t => t != null).WithMessage("m").When(m => true);'
+ )
+
+ assert edges[("Must", 1)][0] == "Rules.cs::Rules::Must"
+ assert edges[("WithMessage", 1)][0] == "Rules.cs::Rules::WithMessage#2"
+ assert edges[("When", 1)] == ("Rules.cs::Rules::When", "receiver_extension_global")
+
+
+def test_csharp_chain_binds_an_inherited_interface_member(tmp_path: Path) -> None:
+ edges = _csharp_chain_edges(tmp_path, "RuleFor(x => x.Child).SetValidator(null);")
+
+ assert edges[("SetValidator", 1)] == (
+ "Syntax.cs::IRuleBuilder::SetValidator",
+ "return_type_import",
+ )
+
+
+def test_csharp_chain_narrows_to_the_overload_its_arguments_select(tmp_path: Path) -> None:
+ edges = _csharp_chain_edges(
+ tmp_path, 'RuleFor(x => x.Text).Must(t => true).WithMessage("m", 7, true);'
+ )
+
+ assert edges[("WithMessage", 3)][0] == "Rules.cs::Rules::WithMessage#4"
+
+
+def test_csharp_chain_on_a_repository_type_without_the_member_refuses(tmp_path: Path) -> None:
+ """A known head type with no such member is not a call on `this`."""
+ edges = _csharp_chain_edges(
+ tmp_path,
+ "Plain.Make().When(m => true, null);",
+ {"Plain.cs": "public class Plain { public static Plain Make() { return null; } }\n"},
+ )
+
+ assert ("When", 2) not in edges
+
+
+def test_csharp_chain_on_a_type_with_an_external_base_keeps_the_fallback(tmp_path: Path) -> None:
+ """The external base may declare the member, so nothing is proven."""
+ edges = _csharp_chain_edges(
+ tmp_path,
+ "Plain.Make().Flush();",
+ {
+ "Plain.cs": (
+ "public class Plain : Stream { public static Plain Make() { return null; } }\n"
+ "public class Sink { public void Flush() {} }\n"
+ )
+ },
+ )
+
+ assert edges[("Flush", 0)][0] == "Plain.cs::Sink::Flush"
+
+
+def test_csharp_chain_on_a_builtin_type_refuses(tmp_path: Path) -> None:
+ edges = _csharp_chain_edges(
+ tmp_path,
+ "Store.Load().ConfigureAwait(false);",
+ {
+ "Store.cs": (
+ "public class Store { public static Task<int> Load() { return null; }\n"
+ " public void ConfigureAwait(bool flag) {} }\n"
+ )
+ },
+ )
+
+ assert ("ConfigureAwait", 1) not in edges
+
+
+def test_csharp_chain_on_a_type_parameter_keeps_the_fallback(tmp_path: Path) -> None:
+ """`TBuilder` is no type the repository declares; its members are its constraint's.
+
+ Nothing proves the bare-name answer wrong, so the fallback still runs.
+ """
+ edges = _csharp_chain_edges(
+ tmp_path,
+ "Builder.Create().Add().Build();",
+ {
+ "Builder.cs": (
+ "public class Builder { public static Builder Create() { return null; }\n"
+ " public object Build() { return null; } }\n"
+ "public static class BuilderExtensions {\n"
+ " public static TBuilder Add<TBuilder>(this TBuilder builder) { return builder; }\n}\n"
+ )
+ },
+ )
+
+ assert edges[("Build", 0)][0] == "Builder.cs::Builder::Build"
+
+
+def test_csharp_chain_links_that_name_each_other_end_unresolved(tmp_path: Path) -> None:
+ """Two chains on one line whose links key onto each other cannot recurse."""
+ edges = _csharp_chain_edges(tmp_path, "var a = First().Second(); var b = Second().First();")
+
+ assert edges == {}
+
+
+def test_csharp_chain_link_whose_declarations_disagree_has_no_type(tmp_path: Path) -> None:
+ """Two same-arity `Then` overloads share one id but return different types.
+
+ Neither return type is the link's, so the next link is not refused on
+ whichever declaration the id happened to keep.
+ """
+ edges = _csharp_chain_edges(
+ tmp_path,
+ 'RuleFor(x => x.Text).Must(t => true).Then(1).WithMessage("m");',
+ {
+ "Steps.cs": (
+ "public static class Steps {\n"
+ " public static IRuleBuilderOptions<T, P> Then<T, P>"
+ "(this IRuleBuilderOptions<T, P> rule, int n) { return rule; }\n"
+ " public static IRuleBuilderInitial<T, P> Then<T, P>"
+ "(this IRuleBuilderInitial<T, P> rule, int n) { return rule; }\n}\n"
+ )
+ },
+ )
+
+ assert ("WithMessage", 1) in edges
diff --git a/tests/unit/ingestion/test_return_types.py b/tests/unit/ingestion/test_return_types.py
index 961a4ae55..d83c2bc58 100644
--- a/tests/unit/ingestion/test_return_types.py
+++ b/tests/unit/ingestion/test_return_types.py
@@ -33,7 +33,8 @@ def test_signature_parameter_count(signature: str, expected: int | None) -> None
("Result", "java", "Result"),
("java.util.Optional<Result>", "java", "Optional"),
("const seastar::future<Result>&", "cpp", "future"),
- ("global::System.Threading.Tasks.Task<Result>?", "csharp", "Task"),
+ ("global::System.Threading.Tasks.Task<Result>?", "csharp", "Task`1"),
+ ("IRuleBuilderOptions<T, TProperty>", "csharp", "IRuleBuilderOptions`2"),
("Promise<Result> | null", "typescript", "Promise"),
("*Event", "go", "Event"),
("*zerolog.Event", "go", "Event"),