fix(csharp): record extension-method facts and primitive receiver types (#4828)

A call to a classic `this`-parameter extension method produced no `calls`
edge: the member-call resolver looks the method up on the receiver's declared
type, while an extension is declared on a static class. Two facts were missing
before any resolver could join them.

The extractor now persists, on the extension method's node:

  extension: true
  extended_type: <simple name of the `this` parameter's type>
  extended_type_arity: <generic arity of that type>
  extended_is_type_param: true for `this T`

`_csharp_method_signature` already detected the `this` modifier, but only used
it to compute `min_arity`; the extended type is the join key a call site needs
and is recorded where the declaration is still at hand. The type is the same
simple name a receiver is stamped with (`_read_csharp_type_name` strips the
namespace qualifier and generic arguments), so qualified `this App.Widget` and
generic `this Box<int>` are comparable with `receiver_type`.

`_csharp_receiver_type_name` no longer drops every lowercase type: predefined
primitives are not declared in the corpus, but `this string` dispatches on
exactly that name, so filtering them made those calls untypeable before the
extension pass could ever see them. The parking path is guarded in exchange:
`_park_if_absent` does not park a well-known BCL receiver name as a cross-repo
candidate, so `x.ToString()` on an `int` no longer stamps an `unresolved_calls`
payload on the caller.

AST cache schema 29 -> 30: cached `.cs` extractions lack the new facts.

Refs #4828

(cherry picked from commit 6a15bfefab)
This commit is contained in:
Deepjyoti-Sarmah authored and safishamsi committed 2026-11-09 16:46:28 +00:00
1 parent 7b1d14489f
commit 5bfb4241d8
3 files changed
+280 -9

No files matched your search

+19
View File
@@ -6445,6 +6445,18 @@ def _resolve_cpp_member_calls(
})
# C# predefined/BCL type names that are never declared in the scanned corpus.
# A receiver of one of these types can still be the target of an extension method
# (`this string`), so the extractor now stamps the type name (#4828) — but the
# type is not a cross-repo candidate, so a failed instance lookup must not park it
# as one (#3152).
_CSHARP_WELL_KNOWN_TYPES = frozenset({
"bool", "byte", "char", "decimal", "double", "dynamic", "float", "int",
"long", "nint", "nuint", "object", "sbyte", "short", "string", "uint",
"ulong", "ushort", "void",
})
def _csharp_overload_index(nodes: list[dict], edges: list[dict]) -> dict:
"""Method nodes by id and their owning type, for C# methods with an arity."""
node_by_id = {n.get("id"): n for n in nodes}
@@ -6652,8 +6664,15 @@ def _resolve_csharp_member_calls(
``_resolve_type_name_nid`` collapses "absent", "ambiguous" and "scoping was
decisive" into one ``None``, and only the first is a cross-repo candidate,
so re-check the bare-name index instead of trusting the ``None``.
A well-known BCL name is NOT a cross-repo candidate: ``string``/``int``
receivers are typed now that extension methods need their declared type
(#4828), and parking every ``x.ToString()`` would stamp a useless
``unresolved_calls`` payload on most caller nodes in a .NET corpus.
"""
if type_name and not type_def_nids.get(_key(type_name)):
if str(type_name).lower() in _CSHARP_WELL_KNOWN_TYPES:
return
_park_unresolved_member_call(
caller_node, rc.get("callee"), type_name, "csharp", rc,
)
+50 -9
View File
@@ -207,10 +207,22 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
variadic = extension = False
# A primary constructor's parameter list is an unnamed child of its type
# declaration, so the caller hands it over; the type's own type parameters
# are not the constructor's.
# are not the constructor's (#5054).
primary = params is not None
if params is None:
params = node.child_by_field_name("parameters")
# The method's own type parameters, so `this T` can be told apart from a
# method on a real class that happens to be named T (#4828).
type_param_nodes = [
p for c in node.children if c.type == "type_parameter_list"
for p in c.children if p.type in ("type_parameter", "identifier")
]
type_param_names = {
"".join(_read_text(p, source).split()) for p in type_param_nodes
}
extended_type: str | None = None
extended_arity = 0
extended_is_type_param = False
children = params.children if params is not None else []
for i, c in enumerate(children):
if c.type == "parameter":
@@ -223,6 +235,23 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
arity += 1
if "this" in mods and arity == 1:
extension = True
# The extended type is the join key an extension call site
# needs; record it here, where the declaration is still at
# hand, instead of re-reading the parameter text downstream
# (#4828). `_read_csharp_type_name` already strips the
# namespace qualifier and the generic arguments, so this is
# the same simple name a receiver is stamped with.
ext_info = _read_csharp_type_name(type_node, source)
if ext_info and ext_info[0]:
extended_type = ext_info[0]
extended_arity = sum(
1 for ch in (type_node.children if type_node is not None else [])
if ch.type == "type_argument_list"
for a in ch.children if a.is_named
)
extended_is_type_param = bool(
extended_type and extended_type in type_param_names
)
if not any(x.type == "=" for x in c.children):
required += 1
elif c.type == "params":
@@ -230,10 +259,9 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
parts.append("params " + ("".join(_read_text(type_node, source).split()) if type_node is not None else ""))
arity += 1
variadic = True
type_params = 0 if primary else sum(
1 for c in node.children if c.type == "type_parameter_list"
for _p in c.children if _p.type in ("type_parameter", "identifier")
)
# A primary constructor contributes no type parameters of its own (#5054);
# otherwise count the method's own type parameters (#4828).
type_params = 0 if primary else len(type_param_nodes)
signature = ",".join(parts)
if type_params:
signature = f"`{type_params}:{signature}"
@@ -244,6 +272,16 @@ def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dic
meta["min_arity"] = min_arity
if variadic:
meta["variadic"] = True
if extension:
# Call-side facts: a member-call resolver can index declarations by
# `extended_type` and bind `recv.M(args)` against `[min_arity, arity]`
# (#4828). Persisted on the node so a merged/sharded build keeps them.
meta["extension"] = True
if extended_type:
meta["extended_type"] = extended_type
meta["extended_type_arity"] = extended_arity
if extended_is_type_param:
meta["extended_is_type_param"] = True
return signature, meta
@@ -3470,15 +3508,18 @@ def _swift_local_var_types(body_node, source: bytes, table: dict[str, str],
def _csharp_receiver_type_name(type_node, source: bytes) -> str | None:
"""Resolve a C# declared type to a receiver-typable class name, or None.
A genuine C# class name is Pascal-cased; predefined primitives
(int/bool/string) and ``dynamic`` never own a resolvable method definition
here, and ``var`` (``implicit_type``) carries no name at all.
Predefined primitives (``int``/``bool``/``string``) and ``dynamic`` own no
definition *inside this corpus*, so an instance lookup on them never binds.
They are still returned: an extension method (``this string``) dispatches on
exactly that type name, and dropping the name made every such call
untypeable before it reached the extension pass (#4828). ``var``
(``implicit_type``) still carries no name at all.
"""
info = _read_csharp_type_name(type_node, source)
if not info:
return None
name = info[0]
return name if name and name[:1].isupper() else None
return name or None
_CSHARP_LOOP_SEQUENCES = frozenset({
+211
View File
@@ -0,0 +1,211 @@
"""C# extension-method declaration facts and primitive receiver typing (#4828).
The member-call resolvers can only bind a call to an extension method if the
declaration carries the join key: which type the `this` parameter extends. These
tests pin that the extractor records it (and keeps recording it in a way the
resolver can consume), and that a primitive receiver type is stamped so
`this string` can ever match.
"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
from graphify.extract import extract, extract_csharp
def _extract(tmp_path, files: dict[str, str]):
for name, body in files.items():
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body)
old = os.getcwd()
try:
os.chdir(tmp_path)
result = extract([Path(n) for n in files], cache_root=Path(tempfile.mkdtemp()))
per_file = {n: extract_csharp(Path(n)) for n in files}
finally:
os.chdir(old)
return result, per_file
def _line_of(text: str, marker: str) -> str:
hits = [i for i, line in enumerate(text.splitlines(), start=1) if marker in line]
assert len(hits) == 1, (marker, hits)
return f"L{hits[0]}"
def _meta_by_line(result, source_file: str, text: str, marker: str) -> dict:
line = _line_of(text, marker)
hits = [
n for n in result["nodes"]
if n.get("source_file") == source_file and n.get("source_location") == line
]
assert len(hits) == 1, (source_file, line, [n.get("label") for n in hits])
return hits[0].get("metadata") or {}
def _call(per_file, callee: str, source_file: str, line: str) -> dict:
hits = [
rc for rc in per_file[source_file].get("raw_calls", [])
if rc.get("callee") == callee and rc.get("source_location") == line
]
assert len(hits) == 1, (callee, source_file, line, hits)
return hits[0]
def test_this_parameter_records_the_extended_type(tmp_path):
ext = (
"namespace Ext {\n"
" public static class StringExtensions {\n"
" public static string Mask(this string s, char m = '*') { return s; } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Ext.cs": ext})
meta = _meta_by_line(result, "Ext.cs", ext, "// D1")
assert meta["extension"] is True
assert meta["extended_type"] == "string"
assert meta["extended_type_arity"] == 0
assert "extended_is_type_param" not in meta
# Parameter arity keeps its #4584 meaning; the extension call is one short.
assert meta["arity"] == 2
assert meta["min_arity"] == 0
def test_generic_extended_type_keeps_name_and_arity(tmp_path):
src = (
"namespace App {\n"
" public class Box<T> { }\n"
" public static class BoxExt {\n"
" public static void Fill(this Box<int> b) { } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Box.cs": src})
meta = _meta_by_line(result, "Box.cs", src, "// D1")
assert meta["extended_type"] == "Box"
assert meta["extended_type_arity"] == 1
def test_qualified_this_parameter_keeps_only_the_simple_name(tmp_path):
src = (
"namespace App {\n"
" public class Widget { }\n"
" public static class WExt {\n"
" public static void Paint(this App.Widget w) { } // D1\n"
" }\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"W.cs": src})
meta = _meta_by_line(result, "W.cs", src, "// D1")
assert meta["extended_type"] == "Widget"
def test_open_generic_extension_is_marked_as_a_type_parameter(tmp_path):
src = (
"public class T { }\n"
"public static class TExt {\n"
" public static void Go(this T t) { } // D1\n"
"}\n"
"public static class GenExt {\n"
" public static void Go<T>(this T t) { } // D2\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"Gen.cs": src})
concrete = _meta_by_line(result, "Gen.cs", src, "// D1")
generic = _meta_by_line(result, "Gen.cs", src, "// D2")
# Both carry the same name, so only this flag can tell them apart.
assert concrete["extended_type"] == "T"
assert "extended_is_type_param" not in concrete
assert generic["extended_type"] == "T"
assert generic["extended_is_type_param"] is True
def test_object_extension_is_recorded_as_the_wildcard_type(tmp_path):
src = (
"public static class ObjExt {\n"
" public static object GetValue(this object o) { return o; } // D1\n"
"}\n"
)
result, _per_file = _extract(tmp_path, {"O.cs": src})
meta = _meta_by_line(result, "O.cs", src, "// D1")
assert meta["extended_type"] == "object"
assert "extended_is_type_param" not in meta
def test_ordinary_method_has_no_extension_facts(tmp_path):
src = "public class C {\n public void M(int a) { } // D1\n}\n"
result, _per_file = _extract(tmp_path, {"C.cs": src})
meta = _meta_by_line(result, "C.cs", src, "// D1")
assert "extension" not in meta
assert "extended_type" not in meta
def test_primitive_receiver_types_are_stamped(tmp_path):
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string A(string s) { return s.Mask(); } // E1\n"
" public string B(long v) { return v.ToString(); } // E2\n"
"}\n"
)
_result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
mask = _call(per_file, "Mask", "Svc.cs", _line_of(svc, "// E1"))
assert mask["receiver"] == "s"
assert mask["receiver_type"] == "string"
tostring = _call(per_file, "ToString", "Svc.cs", _line_of(svc, "// E2"))
assert tostring["receiver_type"] == "long"
def test_primitive_receiver_is_not_parked_as_cross_repo(tmp_path):
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string A(string s) { return s.Mask(); }\n"
"}\n"
)
result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
caller_nid = per_file["Svc.cs"]["raw_calls"][0]["caller_nid"]
caller = next(n for n in result["nodes"] if n["id"] == caller_nid)
assert "unresolved_calls" not in (caller.get("metadata") or {}), (
"a `string` receiver has no cross-repo declaration to wait for"
)
def test_chained_receiver_is_still_untyped(tmp_path):
"""The remaining gap, pinned so a future chained-receiver fix is deliberate."""
ext = (
"namespace Ext {\n"
" public static class Exts {\n"
" public static string Mask(this string s) { return s; }\n"
" }\n"
"}\n"
)
svc = (
"using Ext;\n"
"public class Svc {\n"
" public string B(long v) { return v.ToString().Mask(); } // E1\n"
"}\n"
)
_result, per_file = _extract(tmp_path, {"Ext.cs": ext, "Svc.cs": svc})
chained = _call(per_file, "Mask", "Svc.cs", _line_of(svc, "// E1"))
assert chained.get("receiver") is None
assert chained.get("receiver_type") is None
assert chained.get("receiver_chain") is None
assert chained.get("receiver_call") is None