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(graph): give same-shape C# overloads their own nodes and choose them by what each argument can convert to (#4818)
Swati Ahuja5849a47cc53f
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.pyindex c8779aeae..d53093033 100644--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py@@ -7,6 +7,7 @@ member by argument count, then by the typed arguments (Java's most-specific rulefrom __future__ import annotationsfrom collections import defaultdict+from collections.abc import Callablefrom dataclasses import replacefrom functools import cache@@ -15,8 +16,15 @@ from .language_data import get_builtin_typesfrom .languages.receiver_types import external_type_namefrom .models import CallSite, ParsedFile, Symbolfrom .resolved_call import ResolvedCall-from .return_types import signature_parameter_range-from .symbol_identity import erased_parameter_types, erased_type, pair_overloads, split_symbol_id+from .return_types import signature_parameter_range, signature_parameters+from .symbol_identity import (+ clr_parameter_type,+ erased_parameter_types,+ erased_type,+ pair_overloads,+ parameter_type_arity,+ split_symbol_id,+)def _overload_phase(admitted: tuple[int, int | None], argument_count: int) -> int | None:@@ -309,6 +317,78 @@ def _takes(symbol: Symbol, argument_count: int) -> bool:return admitted is None or _overload_phase(admitted, argument_count) is not None+# C# types no lambda, and no repository class or interface, converts to: the+# keyword types and the framework structs a signature most often spells.+_CSHARP_CLOSED_TYPES = frozenset(+ {"bool", "byte", "sbyte", "char", "decimal", "double", "float", "int", "uint", "long",+ "ulong", "short", "ushort", "nint", "nuint", "string", "TimeSpan", "DateTime",+ "DateTimeOffset", "Guid", "CancellationToken"}+)++# How many parameters a lambda converting to ``Func`N`` / ``Action`N`` declares, past N.+_CSHARP_LAMBDA_PARAMETERS = {"Func": -1, "Action": 0}++# Delegate types no repository class or interface converts to.+_CSHARP_DELEGATES = frozenset({*_CSHARP_LAMBDA_PARAMETERS, "Predicate", "Expression"})+++def _csharp_may_take(parameter: str, argument: str, shape_of: Callable[[str], str | None]) -> bool:+ """Could C# *parameter* take an argument of shape or type *argument*?++ *argument* is a lambda (``=>1``), a method group (``group`1``), a+ construction (``new Foo``) or a named value's declared type, a framework+ delegate's with its arity (``Func`2``). Refused only on proof: a lambda+ or a method group reaches a delegate taking its parameter count, and a+ delegate value its own type, never a builtin or a repository type; a+ repository class or interface reaches neither a framework delegate nor a+ builtin, unless the class declares a conversion (C# allows none on an+ interface). An array (``params``) or any other type takes it.+ *shape_of* answers for a repository type, so a repository ``Expression``+ or ``Action`` is never read as the framework's.+ """+ erased = erased_type(parameter)+ if erased.endswith("[]"):+ return True+ head = erased.rstrip("?")+ framework = shape_of(head) is None+ if argument.startswith("=>") or "`" in argument:+ return framework and _csharp_delegate_fits(parameter, head, argument)+ written = argument.removeprefix("new ")+ if written == head or shape_of(written) not in ("interface", "value"):+ return True+ return not framework or (head not in _CSHARP_CLOSED_TYPES and head not in _CSHARP_DELEGATES)+++def _csharp_delegate_fits(parameter: str, head: str, argument: str) -> bool:+ """A lambda, method group or delegate value against a parameter of framework type *head*."""+ if head in _CSHARP_CLOSED_TYPES:+ return False+ arity = parameter_type_arity(parameter)+ kind, _, written_arity = argument.partition("`")+ if kind in _CSHARP_LAMBDA_PARAMETERS:+ return head not in _CSHARP_DELEGATES or (head, arity) == (kind, int(written_arity))+ count = argument[2:] if argument.startswith("=>") else written_arity+ return not count or _csharp_count_fits(head, arity, int(count))+++def _csharp_count_fits(head: str, arity: int, count: int) -> bool:+ """Does a framework delegate *head* of *arity* type arguments take *count* parameters?"""+ if head == "Predicate":+ return count == 1+ offset = _CSHARP_LAMBDA_PARAMETERS.get(head)+ if offset is None or (head == "Func" and not arity):+ return True+ return count == arity + offset+++def _csharp_parameter_named(signature: str, name: str) -> str | None:+ """The parameter of *signature* that declares *name*, as written, or None."""+ for parameter in signature_parameters(signature) or []:+ if parameter.partition("=")[0].split()[-1:] == [name]:+ return parameter+ return None++class OverloadSelectionMixin:"""Overload-set indexing and member selection."""@@ -546,6 +626,8 @@ class OverloadSelectionMixin:"""*found* narrowed to the one member its typed arguments fit closest, if one does."""if len(found) < 2 or not argument_types:return found+ if self._symbols_by_id[found[0]].language == "csharp":+ return self._csharp_takers(found, argument_types)typed = [(m, erased_parameter_types(self._symbols_by_id[m])) for m in found]if self._symbols_by_id[found[0]].language == "apex":closest = _exact_apex_fit(typed, argument_types, self._folded_type_names())@@ -553,6 +635,107 @@ class OverloadSelectionMixin:closest = _closest_fit(typed, argument_types, expanded)return found if closest is None else [closest]+ def _csharp_takers(self, found: list[str], argument_types: tuple[str | None, ...]) -> list[str]:+ """*found* narrowed to the C# members no argument's shape or type refuses.++ *argument_types* leads with the call's receiver and its type+ (``_csharp_arguments``). Every member refusing leaves *found* as it+ was: the evidence is then about a call this set may not hold.+ """+ receiver, receiver_type, *arguments = argument_types+ takers = [+ member+ for member in found+ if all(+ argument is None or _csharp_may_take(parameter, argument, self._csharp_shape)+ for parameter, argument in zip(+ self._csharp_parameters(member, receiver), arguments, strict=False+ )+ )+ ]+ return self._csharp_exact_this(takers, receiver_type) or found++ def _csharp_exact_this(self, members: list[str], receiver_type: str | None) -> list[str]:+ """*members* narrowed to the extensions whose ``this`` is the receiver's own type.++ Only among members that differ in nothing else, where the identity+ conversion is the better one (``When(this IRuleOptions r, ..)`` over+ ``When(this IRuleConditions r, ..)`` for an ``IRuleOptions`` receiver).+ """+ if len(members) < 2 or not receiver_type:+ return members+ parameters = {+ member: signature_parameters(self._symbols_by_id[member].signature or "") or []+ for member in members+ }+ rest = {tuple(clr_parameter_type(p) for p in found[1:]) for found in parameters.values()}+ if len(rest) != 1:+ return members+ exact = [+ member+ for member, found in parameters.items()+ if found[:1] and found[0].split()[:1] == ["this"] and erased_type(found[0]) == receiver_type+ ]+ return exact or members++ def _csharp_parameters(self, member: str, receiver: str | None) -> list[str]:+ """*member*'s parameters as a call on *receiver* fills them.++ An extension method called on a value (``x.Ext(a)``) takes the value+ as its ``this`` parameter, so the arguments start at the next one;+ called through its class (``Exts.Ext(x, a)``) or bare, they do not.+ """+ symbol = self._symbols_by_id[member]+ parameters = signature_parameters(symbol.signature or "") or []+ # A call's C# receiver is a bare name: a dotted one mints no site.+ on_value = receiver is not None and receiver != symbol.parent_name+ if on_value and parameters and parameters[0].split()[:1] == ["this"]:+ return parameters[1:]+ return parameters++ def _csharp_shape(self, name: str) -> str | None:+ """``"interface"``, ``"value"`` or ``"converts"`` for the repository's C# type *name*.++ None for a name the repository does not declare as a type, declares+ as both an interface and a class, or also declares as a delegate. A+ class whose file, or a repository base class's, declares an+ ``operator`` is ``"converts"``: it may reach a builtin. Files are read+ on first ask only.+ """+ if self._csharp_type_shapes is None:+ found: dict[str, set[str]] = defaultdict(set)+ delegates: set[str] = set()+ for symbol_id, symbol in self._symbols_by_id.items():+ if symbol.language != "csharp":+ continue+ if symbol.kind in _TYPE_KINDS:+ found[symbol.name].add(symbol_id)+ elif symbol.kind == "function" and symbol.name != symbol.parent_name:+ # A delegate; a constructor shares its class's name.+ delegates.add(symbol.name)+ self._csharp_type_shapes = {n: ids for n, ids in found.items() if n not in delegates}+ if name not in self._csharp_shape_answers:+ self._csharp_shape_answers[name] = self._csharp_shape_of(+ self._csharp_type_shapes.get(name, set())+ )+ return self._csharp_shape_answers[name]++ def _csharp_shape_of(self, type_ids: set[str]) -> str | None:+ """The shape the C# types *type_ids*, all of one name, share; see ``_csharp_shape``."""+ interfaces = {self._symbols_by_id[t].kind == "interface" for t in type_ids}+ if len(interfaces) != 1:+ return None+ if interfaces == {True}:+ return "interface"+ classes = {+ ancestor+ for type_id in type_ids+ for ancestor in (type_id, *self._ancestors_of(type_id))+ if getattr(self._symbols_by_id.get(ancestor), "kind", "interface") != "interface"+ }+ paths = {self._symbol_paths_by_id[c] for c in classes}+ return "converts" if any("operator" in self._text_of(p) for p in paths) else "value"+def _folded_type_names(self) -> frozenset[str]:"""The repository's Apex type names, lowercased, built once."""if self._folded_types is None:@@ -569,8 +752,12 @@ class OverloadSelectionMixin:So ``f(start, n)`` is judged as ``f(1L, 2)`` is. Asked only of a callto a name an overload set carries."""+ if call.target_name not in self._overloaded_names:+ return call+ if self._language_of(file_path) == "csharp":+ return replace(call, argument_types=self._csharp_arguments(file_path, call))names = call.argument_names- if not names or call.target_name not in self._overloaded_names:+ if not names:return callcaller_id = call.caller_symbol_id or ""literals = call.argument_types or (None,) * len(names)@@ -580,6 +767,29 @@ class OverloadSelectionMixin:)return replace(call, argument_types=types if any(types) else None)+ def _csharp_arguments(self, file_path: str, call: CallSite) -> tuple[str | None, ...] | None:+ """The receiver (``""`` when chained, None when bare), its type, then each argument's shape or type.++ None when no argument says anything.+ """+ names = call.argument_names or (None,) * len(call.argument_types or ())+ literals = call.argument_types or (None,) * len(names)+ caller_id = call.caller_symbol_id or ""+ types = tuple(+ literal or (self._argument_type(file_path, caller_id, name) if name else None)+ for literal, name in zip(literals, names, strict=True)+ )+ if not any(types):+ return None+ return (*self._csharp_receiver(file_path, call), *types)++ def _csharp_receiver(self, file_path: str, call: CallSite) -> tuple[str | None, str | None]:+ """A C# call's receiver (``""`` when chained, None when bare) and its declared type."""+ receiver = call.receiver_name or ("" if call.receiver_call is not None else None)+ if not receiver or not receiver.isidentifier():+ return receiver, None+ return receiver, self._argument_type(file_path, call.caller_symbol_id or "", receiver)+def _argument_type(self, file_path: str, caller_id: str, name: str) -> str | None:"""Argument *name*'s declared type, spelled as an overload id spells a parameter.@@ -598,10 +808,47 @@ class OverloadSelectionMixin:)if scope == "field" and self._declares_name(file_path, caller_id, name):return None+ if type_name is None and language == "csharp":+ return self._csharp_delegate_argument(file_path, caller_id, name)if type_name is None or "::" in type_name:return Nonereturn erased_type(external_type_name(type_name) or type_name)+ def _csharp_delegate_argument(self, file_path: str, caller_id: str, name: str) -> str | None:+ """``Func`2`` when argument *name* is a ``Func<A, B>``, ``group`1`` for a method group; else None.++ The declaration scan types no builtin, so a forwarded delegate is read+ off the caller's own parameters, and a name the body neither binds+ nor declares may be a method of the caller's class: one member, no+ overload set and no ``params``, whose parameter count a delegate+ conversion matches. Ceiling: a lambda parameter shadowing a caller+ parameter (C# 8) reads as the parameter, and a method a base class+ overloads as the caller class's one member.+ """+ caller = self._symbols_by_id.get(caller_id)+ parameter = _csharp_parameter_named(caller.signature or "", name) if caller else None+ if parameter is not None:+ head = erased_type(parameter)+ if head not in _CSHARP_LAMBDA_PARAMETERS:+ return None+ return f"{head}`{parameter_type_arity(parameter)}"+ if name in self._bound_names_in(file_path, caller_id, "csharp") or self._declares_name(+ file_path, caller_id, name+ ):+ return None+ return self._csharp_method_group(caller_id, name)++ def _csharp_method_group(self, caller_id: str, name: str) -> str | None:+ """``group`N`` when *name* is the caller class's one method of that name, of N fixed parameters."""+ method_id = self._declares(self._caller_class_id(caller_id), name)+ method = self._symbols_by_id.get(method_id) if method_id else None+ if method is None or method.kind != "method" or method_id in self._overload_rep:+ return None+ parameters = signature_parameters(method.signature or "")+ if parameters is None or (parameters and parameters[-1].split()[:1] == ["params"]):+ return None+ return f"group`{len(parameters)}"+def _overload_sibling_call(self, call: CallSite) -> ResolvedCall | None:"""An overload calling another member of its own set, ``f(a)`` inside ``f(a, b)``.diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex e9a9c67d2..4f82259b0 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -388,6 +388,9 @@ class CallResolver(symbol.name for symbol in self._symbols_by_id.values() if symbol.kind in _TYPE_KINDS)self._folded_types: frozenset[str] | None = None+ # {C# type name: the type symbols declaring it}, then each name's shape.+ self._csharp_type_shapes: dict[str, set[str]] | None = None+ self._csharp_shape_answers: dict[str, str | None] = {}# Narrowed to C# for the extension index: the set above is a bare# cross-language name match, so a type of that name in any language# would admit an extension on the BCL type it shadows.diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex ba8392dc6..bef6f1a03 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -381,9 +381,10 @@ class CallSite:# COBOL ``CALL`` / ``LINK`` / ``XCTL``: names a PROGRAM-ID, never a paragraph.program_call: bool = False# Java: each argument's type where it is a literal (``"String"``, ``"int"``,- # ``"null"``), else None; None overall when no argument is one.+ # ``"null"``), else None; None overall when no argument is one. C# writes a+ # lambda's or a construction's shape here (``"=>2"``, ``"new Foo"``).argument_types: tuple[str | None, ...] | None = None- # Java: each argument that is a bare name (``start``), else None; None overall+ # Java and C#: each argument that is a bare name (``start``), else None; None overall# when no argument is one. The resolver reads its declared type.argument_names: tuple[str | None, ...] | None = Nonediff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex 357f1db20..77643eda1 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -458,12 +458,18 @@ def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:Read from the argument list already in hand, the way ``_count_arguments``counts it."""- if language not in ("java", "apex") or not arg_nodes:+ if language not in ("java", "apex", "csharp") or not arg_nodes:return []skip_types = frozenset({"(", ")", ","})- return [+ arguments = [c for c in arg_nodes[0].children if c.type not in skip_types and "comment" not in c.type]+ if language == "csharp":+ # A named argument (``onRetry: f``) binds by name, so no position is known.+ if any(a.child_by_field_name("name") is not None for a in arguments):+ return []+ return [a.named_children[-1] if a.named_children else a for a in arguments]+ return argumentsdef _argument_literal_types(@@ -471,13 +477,35 @@ def _argument_literal_types() -> tuple[str | None, ...] | None:"""The type of each literal argument, None where an argument is no literal.- None overall when no argument is a literal.+ None overall when no argument is a literal. C# reports a lambda's and a+ construction's shape instead (``_csharp_argument_shape``)."""- literal_type = _apex_literal_type if language == "apex" else _java_literal_type+ literal_type = {"apex": _apex_literal_type, "csharp": _csharp_argument_shape}.get(+ language, _java_literal_type+ )types = tuple(literal_type(argument, src) for argument in arguments)return types if any(types) else None+def _csharp_argument_shape(node: Node, src: str) -> str | None:+ """``=>2`` for a two-parameter lambda (``=>`` when unwritten), ``new Foo`` for a construction."""+ if node.type == "lambda_expression":+ parameters = node.child_by_field_name("parameters")+ if parameters is not None and parameters.type == "implicit_parameter":+ return "=>1"+ return f"=>{len(parameters.named_children)}" if parameters is not None else "=>"+ if node.type == "anonymous_method_expression":+ parameters = next((c for c in node.named_children if c.type == "parameter_list"), None)+ return "=>" if parameters is None else f"=>{len(parameters.named_children)}"+ if node.type == "object_creation_expression":+ created = node.child_by_field_name("type")+ if created is not None and created.type == "generic_name":+ created = created.named_children[0] if created.named_children else None+ if created is not None and created.type == "identifier":+ return f"new {node_text(created, src)}"+ return None++def _argument_names(arguments: list[Node], src: str) -> tuple[str | None, ...] | None:"""Each argument that is a bare name (a local, parameter or field), else None.diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.pyindex c03816604..360ab698c 100644--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py@@ -10,8 +10,10 @@ gains a discriminator:narrows to the member whose parameters admit its argument count. Membersthat share a count also carry their erased parameter types,``StringUtil.java::StringUtil::append#1(String)``, so an inserted overload- never renames its siblings. A Kotlin extension's receiver leads its types,- as it leads the JVM signature it compiles to: ``Byte.toHexString()`` is+ never renames its siblings. C# members those types still join spell each+ generic type with its arity, ``When#2(Func`2)`` beside ``When#2(Func`3)``.+ A Kotlin extension's receiver leads its types, as it leads the JVM+ signature it compiles to: ``Byte.toHexString()`` is``Util.kt::toHexString#0(Byte)``, beside ``toHexString#0(Int)``.- ``#<tag>(<predicate>)`` on the last segment: one build variant of a symboldeclared once per configuration, ``lib.rs::f#cfg(not(unix))``. A call may@@ -28,12 +30,12 @@ below, so a language without an entry is untouched by construction.from __future__ import annotationsimport re-from collections import defaultdict+from collections import Counter, defaultdictfrom collections.abc import Callable, Iterablefrom .models import Symbolfrom .return_types import signature_parameter_count, signature_parameters-from .type_names import strip_type_arguments+from .type_names import strip_type_arguments, type_argument_count# The payload after ``#``: a parameter count with optional parameter types, or# a build-variant predicate.@@ -353,19 +355,63 @@ def disambiguate_colliding_ids(symbols: list[Symbol], language: str) -> None:def _split_same_counts(keyed: list[tuple[Symbol, str | None]]) -> list[tuple[Symbol, str | None]]:- """Append parameter types to every count two members share, when they differ."""+ """Append parameter types to every count two members share, when they differ.++ A C# pair the erased types still join (``Func<T, bool>`` and ``Func<T,+ Ctx<T>, bool>``) is told apart by each type's generic arity instead.+ """typed: dict[str, dict[int, str]] = defaultdict(dict)for index, (symbol, key) in enumerate(keyed):if key is not None:typed[key][index] = f"{key}{_parameter_types(symbol)}"out = list(keyed)- for by_index in typed.values():+ for count, by_index in typed.items():+ if keyed[next(iter(by_index))][0].language == "csharp":+ by_index = _split_by_generic_arity(keyed, count, by_index)if len(set(by_index.values())) > 1:for index, key in by_index.items():out[index] = (keyed[index][0], key)return out+def _split_by_generic_arity(+ keyed: list[tuple[Symbol, str | None]], count: str, by_index: dict[int, str]+) -> dict[int, str]:+ """*by_index* with each key two members share respelled with CLR arities.++ Only the members that collide change; a sibling that does not keeps its id.+ """+ seen = Counter(by_index.values())+ return {+ index: f"{count}{_clr_parameter_types(keyed[index][0])}" if seen[key] > 1 else key+ for index, key in by_index.items()+ }+++# The array, pointer and nullable marks that may follow an erased type's name.+_ERASED_MARKS = "[]*&?"+++def _clr_parameter_types(symbol: Symbol) -> str:+ """``(Func`2,int)``: each erased type with its type argument count, as the CLR names it."""+ parameters = signature_parameters(symbol.signature or "") or []+ return "(" + ",".join(clr_parameter_type(p) for p in parameters) + ")"+++def clr_parameter_type(parameter: str) -> str:+ """``Func<A, B> f`` -> ``Func`2``: the erased type with its type argument count."""+ arity = parameter_type_arity(parameter)+ erased = erased_type(parameter)+ name = erased.rstrip(_ERASED_MARKS)+ return f"{name}`{arity}{erased[len(name):]}" if arity else erased+++def parameter_type_arity(parameter: str) -> int:+ """How many type arguments a C# parameter's type is given: ``Func<A, B> f`` -> 2."""+ written = parameter.partition("=")[0].split()+ return type_argument_count(" ".join(written[:-1]) or parameter)++def pair_overloads(declared: list[Symbol], defined: list[Symbol]) -> dict[str, str]:"""``{declared id: defined id}``: by count and erased types, then by count.@@ -437,6 +483,7 @@ def _reparent_members(symbols: list[Symbol], owner: Symbol, segment: str) -> Non__all__ = ["base_symbol_id",+ "clr_parameter_type","disambiguate_colliding_ids","has_overload_identity","id_segment_name",@@ -444,6 +491,7 @@ __all__ = ["outer_scope","overload_sets","pair_overloads",+ "parameter_type_arity","split_symbol_id","symbol_discriminator","symbol_id_arity",diff --git a/tests/unit/ingestion/parser/golden/csharp.json b/tests/unit/ingestion/parser/golden/csharp.jsonindex 3e0feb8d5..3568dcbad 100644--- a/tests/unit/ingestion/parser/golden/csharp.json+++ b/tests/unit/ingestion/parser/golden/csharp.json@@ -398,7 +398,9 @@"spawned": false,"program_call": false,"argument_types": null,- "argument_names": null+ "argument_names": [+ "u"+ ]},{"target_name": "SaveChangesAsync",@@ -430,7 +432,9 @@"spawned": false,"program_call": false,"argument_types": null,- "argument_names": null+ "argument_names": [+ "p"+ ]},{"target_name": "Wait",@@ -890,7 +894,10 @@"spawned": false,"program_call": false,"argument_types": null,- "argument_names": null+ "argument_names": [+ "x",+ null+ ]}],"heritage": [],diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.pyindex dcb6be454..8ef2afb6f 100644--- a/tests/unit/ingestion/test_overload_identity.py+++ b/tests/unit/ingestion/test_overload_identity.py@@ -434,6 +434,39 @@ class TestCSharpGenericSiblings:ids = set(_ids(_parse("P.cs", "csharp", text)))assert {"P.cs::P::P#1(string)", "P.cs::P::P#1(TimeSpan?)", "P.cs::P::P#1(int[])", "P.cs::P::P#0"} <= ids+ def test_csharp_overloads_one_erasure_joins_split_by_generic_arity(self) -> None:+ """``Func<T, bool>`` and ``Func<T, Ctx, bool>`` are two CLR types; only the colliding pair is respelled."""+ text = (+ "namespace App;\npublic static class R {\n"+ " public static void When(this IRule<T> r, Func<T, bool> p) { }\n"+ " public static void When(this IRule<T> r, Func<T, Ctx, bool> p) { }\n"+ " public static void When(this IRule<T> r, Action<T>[]? p) { }\n"+ " public static void When(this IRule<T> r, Action<T, Ctx>[]? p) { }\n"+ " public static void When(this IRule<T> r, string p) { }\n"+ "}\n"+ )+ assert _ids(_parse("R.cs", "csharp", text))[-5:] == [+ "R.cs::R::When#2(IRule`1,Func`2)",+ "R.cs::R::When#2(IRule`1,Func`3)",+ "R.cs::R::When#2(IRule`1,Action`1[]?)",+ "R.cs::R::When#2(IRule`1,Action`2[]?)",+ "R.cs::R::When#2(IRule,string)",+ ]++ def test_csharp_calls_inside_each_split_overload_keep_their_caller(self, tmp_path: Path) -> None:+ text = (+ "namespace App;\npublic class R {\n"+ " public void A() { }\n"+ " public void B() { }\n"+ " public void When(Func<int, bool> p) { A(); }\n"+ " public void When(Func<int, string, bool> p) { B(); }\n"+ "}\n"+ )+ assert _edges(tmp_path, {"R.cs": ("csharp", text)}) >= {+ ("R.cs::R::When#1(Func`2)", "R.cs::R::A"),+ ("R.cs::R::When#1(Func`3)", "R.cs::R::B"),+ }+SHAPES_H = """namespace geo {class Shape {@@ -812,6 +845,147 @@ def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:assert checked > 500+_CS_TIMEOUT = (+ "namespace App;\npublic interface IKey { }\npublic class Ttl : IKey { public Ttl() { } }\n"+ "public static class P {\n"+ " public static void T(int seconds, Action<int, int> on) { }\n"+ " public static void T(Func<int> provider, Action<int, int> on) { }\n"+ " public static void T(Func<int, int> provider, Action<int, int> on) { }\n"+ " public static void T(Func<int, int> provider, Action<int, int, string> on) { }\n"+ " public static void K(TimeSpan ttl, Func<int, string> key) { }\n"+ " public static void K(IKey ttl, Func<int, string> key) { }\n"+ " public static void K(IKey ttl, IKey key) { }\n"+ "}\n"+)+++class TestCSharpArgumentShapes:+ """Same-count C# overloads chosen by what a lambda, a construction or a typed name can reach."""++ def _callee(self, tmp_path: Path, body: str, members: str = "") -> set[str]:+ caller = "namespace App;\npublic class C {\n" + members + " public void Run() { " + body + " }\n}\n"+ edges = _edges(tmp_path, {"P.cs": ("csharp", _CS_TIMEOUT), "C.cs": ("csharp", caller)})+ return {callee.removeprefix("P.cs::P::") for caller_id, callee in edges if caller_id == "C.cs::C::Run"}++ def test_a_lambda_takes_the_delegate_of_its_parameter_count(self, tmp_path: Path) -> None:+ assert self._callee(tmp_path, "P.T(_ => 1, (a, b) => { });") == {"T#2(Func`2,Action`2)"}+ assert self._callee(tmp_path, "P.T(() => 1, (a, b) => { });") == {"T#2(Func`1,Action`2)"}++ def test_a_forwarded_delegate_and_a_method_group_take_their_own_arity(self, tmp_path: Path) -> None:+ members = (+ " void On(int a, int b, string c) { }\n"+ " public void Fwd(Action<int, int, string> on) { P.T(_ => 1, on); }\n"+ )+ assert self._callee(tmp_path, "P.T(_ => 1, On);", members) == {"T#2(Func`2,Action`3)"}+ edges = _edges(tmp_path, {"P.cs": ("csharp", _CS_TIMEOUT), "C.cs": (+ "csharp", "namespace App;\npublic class C {\n" + members + "}\n")})+ assert ("C.cs::C::Fwd", "P.cs::P::T#2(Func`2,Action`3)") in edges++ def test_a_repository_class_or_interface_reaches_no_builtin_or_delegate(self, tmp_path: Path) -> None:+ members = " IKey key;\n"+ callees = self._callee(tmp_path, "P.K(new Ttl(), key);", members)+ assert {c for c in callees if c.startswith("K#")} == {"K#2(IKey,IKey)"}++ def test_a_user_conversion_keeps_the_builtin_member(self, tmp_path: Path) -> None:+ holder = (+ "namespace App;\npublic class Span { public static implicit operator int(Span s) => 0; }\n"+ "public static class Q {\n"+ " public static void M(int a) { }\n"+ " public static void M(Func<int> a) { }\n"+ "}\n"+ )+ caller = "namespace App;\npublic class C {\n public void Run() { Q.M(new Span()); }\n}\n"+ edges = _edges(tmp_path, {"Q.cs": ("csharp", holder), "C.cs": ("csharp", caller)})+ # The conversion leaves both admissible, so the tie keeps the first member.+ assert ("C.cs::C::Run", "Q.cs::Q::M#1(int)") in edges++ def test_an_extension_called_on_a_value_skips_its_this_parameter(self, tmp_path: Path) -> None:+ holder = (+ "namespace App;\npublic class Foo { public Foo(int n) { } }\npublic interface IFoo { }\n"+ "public static class Ext {\n"+ " public static void E(this IFoo f, string a, Foo b) { }\n"+ " public static void E(this IFoo f, Foo a, string b) { }\n"+ "}\n"+ )+ caller = (+ "namespace App;\npublic class C {\n"+ " public void Run(IFoo f, string s) { f.E(s, new Foo(1)); }\n"+ " public void Static(IFoo f, string s) { Ext.E(f, new Foo(1), s); }\n"+ "}\n"+ )+ edges = _edges(tmp_path, {"Ext.cs": ("csharp", holder), "C.cs": ("csharp", caller)})+ assert ("C.cs::C::Run", "Ext.cs::Ext::E#3(IFoo,string,Foo)") in edges+ assert ("C.cs::C::Static", "Ext.cs::Ext::E#3(IFoo,Foo,string)") in edges++ def test_an_extension_on_the_receivers_own_type_wins_an_otherwise_equal_tie(+ self, tmp_path: Path+ ) -> None:+ holder = (+ "namespace App;\npublic interface IOpts { }\npublic interface IConds : IOpts { }\n"+ "public static class W {\n"+ " public static void When(this IOpts r, Func<int, bool> p) { }\n"+ " public static void When(this IConds r, Func<int, bool> p) { }\n"+ " public static void When(this IOpts r, Func<int, string, bool> p) { }\n"+ " public static void When(this IConds r, Func<int, string, bool> p) { }\n"+ "}\n"+ )+ caller = (+ "namespace App;\npublic class C {\n"+ " public void Run(IConds rule) { rule.When((x, ctx) => true); }\n}\n"+ )+ edges = _edges(tmp_path, {"W.cs": ("csharp", holder), "C.cs": ("csharp", caller)})+ assert ("C.cs::C::Run", "W.cs::W::When#2(IConds,Func`3)") in edges++ def test_a_repository_type_named_like_a_framework_delegate_is_a_class(self, tmp_path: Path) -> None:+ holder = (+ "namespace App;\npublic abstract class Expression { }\n"+ "public class Binary : Expression { public Binary(int n) { } }\npublic class Statement { }\n"+ "public static class V {\n"+ " public static void Visit(Expression e) { }\n"+ " public static void Visit(Statement s) { }\n"+ "}\n"+ )+ caller = "namespace App;\npublic class C {\n public void Run() { V.Visit(new Binary(1)); }\n}\n"+ edges = _edges(tmp_path, {"V.cs": ("csharp", holder), "C.cs": ("csharp", caller)})+ assert ("C.cs::C::Run", "V.cs::V::Visit#1(Expression)") in edges++ def test_a_method_group_reaches_any_delegate_of_its_parameter_count(self, tmp_path: Path) -> None:+ holder = (+ "namespace App;\npublic static class F {\n"+ " public static void Where(int n) { }\n"+ " public static void Where(Predicate<int> p) { }\n"+ "}\n"+ )+ caller = (+ "namespace App;\npublic class C {\n"+ " bool IsOk(int x) => true;\n public void Run() { F.Where(IsOk); }\n}\n"+ )+ edges = _edges(tmp_path, {"F.cs": ("csharp", holder), "C.cs": ("csharp", caller)})+ assert ("C.cs::C::Run", "F.cs::F::Where#1(Predicate)") in edges++ def test_a_base_class_conversion_keeps_the_builtin_member(self, tmp_path: Path) -> None:+ holder = (+ "namespace App;\npublic static class Q {\n"+ " public static void M(int a) { }\n"+ " public static void M(Func<int> a) { }\n"+ "}\n"+ )+ base = "namespace App;\npublic class Base { public static implicit operator int(Base b) => 0; }\n"+ derived = "namespace App;\npublic class Derived : Base { public Derived() { } }\n"+ caller = "namespace App;\npublic class C {\n public void Run() { Q.M(new Derived()); }\n}\n"+ edges = _edges(tmp_path, {+ "Q.cs": ("csharp", holder), "B.cs": ("csharp", base),+ "D.cs": ("csharp", derived), "C.cs": ("csharp", caller),+ })+ assert ("C.cs::C::Run", "Q.cs::Q::M#1(int)") in edges++ def test_a_named_argument_reads_no_position(self) -> None:+ parsed = _parse("C.cs", "csharp", "class C { void R() { F(on: x => 1, 2); G(x => 1, new Ttl()); } }")+ shapes = {c.target_name: c.argument_types for c in parsed.calls}+ assert shapes["F"] is None+ assert shapes["G"] == ("=>1", "new Ttl")++class TestNarrowingShapes:"""Call shapes the narrowing step must read by argument count alone."""