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
This commit is contained in:
Deepjyoti-Sarmah committed 2026-11-01 22:45:13 +05:30
1 parent 32e5efe935
commit 6a15bfefab
4 files changed
+278 -9

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ except Exception:
_EXTRACTOR_VERSION = "unknown"
# Bump when AST cache-key semantics change independently of the package version.
_AST_CACHE_SCHEMA = 34 # A bare call inside a Python method no longer self-binds to a same-named method, so it resolves to the imported/module function instead (#4933); a Go method value reached through a receiver field is linked as an indirect_call (#4931); and a Go package-level `var` initialiser references the types it names (#4932), so cached Python and Go extractions re-run; prior (33): A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a package-level `var` initialiser (and its closures) to the file node (#4867); a Go method value passed as an argument is linked as an `indirect_call` (#4868); a Go receiver's field whose struct is declared in a sibling file of the same package is typed so its member calls resolve (#4866); and a Python dispatch table's `module.func` values resolve to the referenced functions as `indirect_call`s (#4773), so cached Go and Python extractions re-run; prior (30): File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4848); a Go `var x = T{}`/`var x = &T{}` types `x` as `T` for receiver resolution like `x := T{}` (#4843); a PowerShell `using module`/`using assembly` name drops its file extension (#4847); a Solidity free-function `using {a, b} for T` set emits `uses` edges (#4846); a CommonLisp forward-referenced superclass binds to its local node instead of a sourceless stub (#4845); and Pascal `inherited`/`inline` form component blocks are recognised so later `object` blocks keep their parent (#4844), so cached extractions across those languages re-run; prior (29): OCaml `and`-chained module/class bindings are all walked (only the first was, so later bindings were silently dropped, #4822), and a SystemVerilog class `task` method is modeled like a `function` one with its own node and parameter refs while its task-locals no longer leak as class fields (#4774), so cached OCaml and Verilog/SystemVerilog extractions re-run; prior (28): Markdown ATX headings parse per CommonMark (closing `#` runs dropped, 0-3 space indent, hash-only lines mint no node, #4790) and fenced code blocks are tracked by CommonMark rules so headings inside fences stop leaking (#4787); YAML keys carry their written spelling and real line and `on`/`off`/`yes`/`no` keys no longer fold to booleans (#4784); rationale labels redact more credential shapes before caching (#4647); Razor `@implements` interface edges are extracted (#4820); aliased Terraform providers get their own node and `provider =` refs resolve (#4819); COBOL paragraphs after a nested `END PROGRAM` reattach to the enclosing program (#4824); Blade `wire:click` binds the bare method name (#4823); a Pascal record is a type with its own methods (#4825); VB.NET operator declarations are extracted as members with their bodies walked (#4821); and a Fortran call resolves to the subroutine it names (#4795), so cached Markdown/YAML/rationale/Razor/Terraform/COBOL/Blade/Pascal/VB.NET/Fortran extractions re-run; prior (27): VB.NET external namespace/type stubs now carry a `source_file` sentinel (#4725); Python member calls resolve through injected fields and method-result types (#4726); a Rust `use` is scoped to the crate it names (#4699), so cached VB.NET/Python/Rust extractions re-run; prior (26): Zig no longer crosses a call between a method and a same-named free function (#4755), and a Dart unnamed `extension on T` is detected (#4741), so cached Zig and Dart extractions re-run; prior (25): Python/Go/C++/Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs (#4578/#4579/#4580/#4581); each C# method overload gets its own node bound by arity (#4584); a package.json dependency's manifest entry links to its ref node (#4569), so cached extractions re-run; prior (24): Objective-C `NS_CLOSED_ENUM` declarations are extracted as enums like `NS_ENUM` (#4705), and a `CREATE TABLE` whose column default the SQL grammar rejects (MySQL `DEFAULT current_timestamp()`) is recovered from its ERRORLine truncated
_AST_CACHE_SCHEMA = 35 # C# extension methods record their extended type (`extended_type`/`extended_type_arity`/`extended_is_type_param`) and a primitive receiver is typed (`this string`), so cached `.cs` extractions re-run (#4828); prior (34): A bare call inside a Python method no longer self-binds to a same-named method, so it resolves to the imported/module function instead (#4933); a Go method value reached through a receiver field is linked as an indirect_call (#4931); and a Go package-level `var` initialiser references the types it names (#4932), so cached Python and Go extractions re-run; prior (33): A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a package-level `var` initialiser (and its closures) to the file node (#4867); a Go method value passed as an argument is linked as an `indirect_call` (#4868); a Go receiver's field whose struct is declared in a sibling file of the same package is typed so its member calls resolve (#4866); and a Python dispatch table's `module.func` values resolve to the referenced functions as `indirect_call`s (#4773), so cached Go and Python extractions re-run; prior (30): File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4848); a Go `var x = T{}`/`var x = &T{}` types `x` as `T` for receiver resolution like `x := T{}` (#4843); a PowerShell `using module`/`using assembly` name drops its file extension (#4847); a Solidity free-function `using {a, b} for T` set emits `uses` edges (#4846); a CommonLisp forward-referenced superclass binds to its local node instead of a sourceless stub (#4845); and Pascal `inherited`/`inline` form component blocks are recognised so later `object` blocks keep their parent (#4844), so cached extractions across those languages re-run; prior (29): OCaml `and`-chained module/class bindings are all walked (only the first was, so later bindings were silently dropped, #4822), and a SystemVerilog class `task` method is modeled like a `function` one with its own node and parameter refs while its task-locals no longer leak as class fields (#4774), so cached OCaml and Verilog/SystemVerilog extractions re-run; prior (28): Markdown ATX headings parse per CommonMark (closing `#` runs dropped, 0-3 space indent, hash-only lines mint no node, #4790) and fenced code blocks are tracked by CommonMark rules so headings inside fences stop leaking (#4787); YAML keys carry their written spelling and real line and `on`/`off`/`yes`/`no` keys no longer fold to booleans (#4784); rationale labels redact more credential shapes before caching (#4647); Razor `@implements` interface edges are extracted (#4820); aliased Terraform providers get their own node and `provider =` refs resolve (#4819); COBOL paragraphs after a nested `END PROGRAM` reattach to the enclosing program (#4824); Blade `wire:click` binds the bare method name (#4823); a Pascal record is a type with its own methods (#4825); VB.NET operator declarations are extracted as members with their bodies walked (#4821); and a Fortran call resolves to the subroutine it names (#4795), so cached Markdown/YAML/rationale/Razor/Terraform/COBOL/Blade/Pascal/VB.NET/Fortran extractions re-run; prior (27): VB.NET external namespace/type stubs now carry a `source_file` sentinel (#4725); Python member calls resolve through injected fields and method-result types (#4726); a Rust `use` is scoped to the crate it names (#4699), so cached VB.NET/Python/Rust extractions re-run; prior (26): Zig no longer crosses a call between a method and a same-named free function (#4755), and a Dart unnamed `extension on T` is detected (#4741), so cached Zig and Dart extractions re-run; prior (25): Python/Go/C++/Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs (#4578/#4579/#4580/#4581); each C# method overload gets its own node bound by arity (#4584); a package.json dependency's manifest entry links to its ref node (#4569), so cached extractions re-run; prior (24): Line truncated
# Per-process memo: distributions() scans site-packages metadata, which is
+19
View File
@@ -5807,6 +5807,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}
@@ -6002,8 +6014,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,
)
+47 -8
View File
@@ -201,6 +201,18 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
parts: list[str] = []
arity = required = 0
variadic = extension = False
# 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
params = node.child_by_field_name("parameters")
children = params.children if params is not None else []
for i, c in enumerate(children):
@@ -214,6 +226,23 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
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":
@@ -221,10 +250,7 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
parts.append("params " + ("".join(_read_text(type_node, source).split()) if type_node is not None else ""))
arity += 1
variadic = True
type_params = 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")
)
type_params = len(type_param_nodes)
signature = ",".join(parts)
if type_params:
signature = f"`{type_params}:{signature}"
@@ -235,6 +261,16 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
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
@@ -3163,15 +3199,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