fix(csharp): credit calls in accessors, indexers and operators to that member
A C# property's accessor bodies, an indexer and a user-defined operator
or conversion were never walked, so every call made inside them was lost.
On Dapper, AutoMapper and Newtonsoft.Json (Roslyn answer key) that is 144
call links made from property/indexer accessors and 186 from conversion
operators, none found.
- A property's `get`/`set` bodies and an expression body (`int P =>
F();`) are walked with the existing property node as the caller. An
auto-accessor has no body and an initializer runs in the constructor,
so neither adds calls. Only the declaration that owns the property
node is walked: when the id is already another member's (an explicit
`IFoo.Name` property spelled like a method `Name()`), its calls are
dropped instead of being credited to that member.
- An indexer is a `this[]` node beside the properties (`defines`,
context `field`), id `_make_id(type_id, "this")`, salted per
signature (including an explicit interface) and away from a member
spelled `This`.
- An operator or conversion is a `.operator +()` / `.operator int()`
node owned through `method`; its id always carries a hash of the
signature, since several conversions share one parameter list.
- A property/indexer counts as owned by its type for caller lookups
(in-file unqualified calls, `this.`/`base.` member calls, the
partial-type own-type preference), like a method. It is never a call
target by name, and `operator` is kept out of the member-call index.
- No existing node id moves (checked on all three projects).
- AST cache schema 40.
Calls TO properties, indexers and operators are not linked: in these
projects they are about 3,500 property get/set links (more than half
to auto-properties), 27 indexer and 60 conversion links, against 0
user-defined binary operator calls. Linking them needs member-access
typing and a decision on the relation, so it is left out.
Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 0e6806a93b)
This commit is contained in:
1 parent
c3b6cfbd9f
commit
85ad8daa1e
4 files changed
+299
-3
No files matched your search
@@ -211,6 +211,16 @@ an unresolved base or an unbound type give no constructor edge. Constructors
|
||||
stay out of every name-keyed call index. AST cache schema 40 retires C# entries
|
||||
without them.
|
||||
|
||||
C# property and indexer accessor bodies (and expression bodies) are walked
|
||||
with the member as the caller, and the member counts as owned by its type for
|
||||
unqualified, `this.`/`base.` and partial-type lookups, like a method. It is never
|
||||
a call target by name. An indexer is a `this[]` node (`defines`, context
|
||||
`field`) with id `_make_id(type_id, "this")`, salted per signature and away
|
||||
from a member spelled `This`. A user-defined operator or conversion is a
|
||||
`.operator +()` / `.operator int()` node owned through `method`, with id
|
||||
`_make_id(type_id, "operator", sha1(signature)[:6])`, since several conversions
|
||||
share one parameter list. Existing ids do not move. AST cache schema 40.
|
||||
|
||||
R extraction preserves symbol-only bindings such as `%||%` as separate nodes.
|
||||
When normal ID normalization removes an entire binding name, its UTF-8 bytes
|
||||
provide a deterministic operator suffix within the same lexical owner. Its double
|
||||
|
||||
+19
-1
@@ -6407,6 +6407,13 @@ def _resolve_csharp_member_calls(
|
||||
method_peers: dict[tuple[str, str], list[dict]] = {}
|
||||
enclosing_type: dict[str, str] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") == "defines" and e.get("context") == "field":
|
||||
# A property/indexer whose accessors make calls is a caller in
|
||||
# its type, like a method; it is never a method_index target.
|
||||
owner, member = e.get("source"), e.get("target")
|
||||
if _is_cs_file(e.get("source_file")) and isinstance(owner, str) and isinstance(member, str):
|
||||
enclosing_type.setdefault(member, owner)
|
||||
continue
|
||||
if e.get("relation") != "method":
|
||||
continue
|
||||
src, tgt = e.get("source"), e.get("target")
|
||||
@@ -6416,6 +6423,8 @@ def _resolve_csharp_member_calls(
|
||||
enclosing_type.setdefault(tgt, src)
|
||||
if is_csharp_constructor_node(tnode):
|
||||
continue # owns its calls (enclosing_type), but is never `x.Name()`
|
||||
if (tnode.get("metadata") or {}).get("kind") == "operator":
|
||||
continue # `operator +` is never written as a call name
|
||||
# Overloads share a key: the first declared one stands for the name,
|
||||
# and the call's argument count picks among them below (#4584).
|
||||
method_key = (src, _key(tnode.get("label", "")))
|
||||
@@ -11814,6 +11823,7 @@ def extract(
|
||||
)
|
||||
_csharp_stub_resolver: CsharpNameResolver | None = None # built on first use
|
||||
_csharp_method_owner: dict[str, str] | None = None # method nid -> type nid, built on first use
|
||||
_csharp_member_owner: dict[str, str] | None = None # property/indexer nid -> type nid, ditto
|
||||
_csharp_outer_type: dict[str, str] | None = None # nested type nid -> outer type label, built on first use
|
||||
_csharp_overload_cache: dict = {} # filled on first use (#4584)
|
||||
_jvm_index = None # built on first Kotlin/Java bare call (#4935)
|
||||
@@ -12057,7 +12067,15 @@ def extract(
|
||||
e["target"]: e["source"] for e in all_edges
|
||||
if e.get("relation") == "method"
|
||||
}
|
||||
caller_owner = _csharp_method_owner.get(rc.get("caller_nid", ""))
|
||||
if _csharp_member_owner is None:
|
||||
# A property/indexer accessor's call: its type is the owner.
|
||||
_csharp_member_owner = {
|
||||
e["target"]: e["source"] for e in all_edges
|
||||
if e.get("relation") == "defines" and e.get("context") == "field"
|
||||
}
|
||||
caller_owner = _csharp_method_owner.get(
|
||||
rc.get("caller_nid", ""), _csharp_member_owner.get(rc.get("caller_nid", ""))
|
||||
)
|
||||
if caller_owner is not None:
|
||||
own_type_matches = [
|
||||
c for c in candidates if _csharp_method_owner.get(c) == caller_owner
|
||||
|
||||
@@ -305,8 +305,9 @@ def _csharp_pre_scan_name_collisions(
|
||||
|
||||
Returns ``(type_groups, member_groups, member_ids)``: the first two are
|
||||
``{plain_nid: {raw names}}`` for the ids two or more distinct names would
|
||||
share; ``member_ids`` is every member's plain id, which a constructor's id
|
||||
must not take (a C# method may be spelled like its type in another case). Types are keyed the way
|
||||
share; ``member_ids`` is every member's plain id, which a constructor's or
|
||||
indexer's id must not take (a C# method may be spelled like its type in
|
||||
another case, and a member may be spelled `This`). Types are keyed the way
|
||||
the walk mints them (``_make_id(stem, namespace, name_for_id)``), members
|
||||
(methods, properties, enum members) by ``_make_id(type_nid, name)`` where
|
||||
``type_nid`` is the type's FINAL id, already salted when the type itself
|
||||
@@ -6590,6 +6591,8 @@ def _extract_generic(
|
||||
csharp_member_ids: set[str] = set()
|
||||
# plain constructor nid -> {signature: node}, like csharp_overloads.
|
||||
csharp_ctor_overloads: dict[str, dict[str, dict]] = {}
|
||||
# plain indexer nid -> {signature: node}, like csharp_overloads.
|
||||
csharp_indexer_overloads: dict[str, dict[str, dict]] = {}
|
||||
if config.ts_module == "tree_sitter_c_sharp":
|
||||
csharp_interface_names = _csharp_pre_scan_interfaces(root, source)
|
||||
csharp_type_groups, csharp_member_groups, csharp_member_ids = (
|
||||
@@ -6762,6 +6765,30 @@ def _extract_generic(
|
||||
add_edge(type_nid, ctor_nid, "method", line)
|
||||
return ctor_nid
|
||||
|
||||
def csharp_queue_member_bodies(member_nid: str, decl, class_nid: str) -> None:
|
||||
"""Walk a C# property's or indexer's accessor bodies as its calls.
|
||||
|
||||
`get { ... }` / `set => ...` and an expression body (`int P => F();`)
|
||||
run code just like a method, so their calls belong to the member. An
|
||||
auto-accessor (`get;`) and an initializer (`= F();`, which runs in the
|
||||
constructor) have no body here. The declaration is the scope, so an
|
||||
indexer's parameters type receivers in every accessor.
|
||||
"""
|
||||
bodies = []
|
||||
accessors = decl.child_by_field_name("accessors")
|
||||
if accessors is not None:
|
||||
for accessor in accessors.children:
|
||||
if accessor.type == "accessor_declaration":
|
||||
body = accessor.child_by_field_name("body")
|
||||
if body is not None:
|
||||
bodies.append(body)
|
||||
value = decl.child_by_field_name("value")
|
||||
if value is not None and value.type == "arrow_expression_clause":
|
||||
bodies.append(value)
|
||||
for body in bodies:
|
||||
csharp_method_scopes[id(body)] = (decl, class_nid)
|
||||
function_bodies.append((member_nid, body))
|
||||
|
||||
def walk(node, parent_class_nid: str | None = None) -> None:
|
||||
nonlocal ruby_singleton_context_depth
|
||||
t = node.type
|
||||
@@ -7808,6 +7835,70 @@ def _extract_generic(
|
||||
csharp_method_scopes[id(ctor_body)] = (node, parent_class_nid)
|
||||
function_bodies.append((ctor_nid, ctor_body))
|
||||
|
||||
if (config.ts_module == "tree_sitter_c_sharp"
|
||||
and t == "indexer_declaration"
|
||||
and parent_class_nid):
|
||||
# `this[int i]` is a property with parameters: a `this[]` node
|
||||
# beside the properties, so its accessors' calls have a caller.
|
||||
# Overloads (`this[int]`, `this[string]`) are salted by signature
|
||||
# like methods (#4584); a member spelled `This` keeps its id.
|
||||
signature, meta = _csharp_method_signature(node, source)
|
||||
explicit = next((c for c in node.children
|
||||
if c.type == "explicit_interface_specifier"), None)
|
||||
if explicit is not None:
|
||||
# `IList<T>.this[int]` and `IList.this[int]` are two indexers.
|
||||
signature = "".join(_read_text(explicit, source).split()) + signature
|
||||
indexer_line = node.start_point[0] + 1
|
||||
indexer_nid = _make_id(parent_class_nid, "this")
|
||||
if indexer_nid in csharp_member_ids:
|
||||
indexer_nid = _make_id(indexer_nid, hashlib.sha1(
|
||||
b"this[]", usedforsecurity=False).hexdigest()[:6])
|
||||
group = csharp_indexer_overloads.setdefault(indexer_nid, {})
|
||||
if group and signature not in group:
|
||||
indexer_nid = _make_id(indexer_nid, hashlib.sha1(
|
||||
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
|
||||
add_node(indexer_nid, "this[]", indexer_line,
|
||||
metadata={**meta, "signature": signature, "kind": "indexer"})
|
||||
if signature not in group and nodes and nodes[-1]["id"] == indexer_nid:
|
||||
group[signature] = nodes[-1]
|
||||
add_edge(parent_class_nid, indexer_nid, "defines", indexer_line, context="field")
|
||||
csharp_queue_member_bodies(indexer_nid, node, parent_class_nid)
|
||||
return
|
||||
|
||||
if (config.ts_module == "tree_sitter_c_sharp"
|
||||
and t in ("operator_declaration", "conversion_operator_declaration")
|
||||
and parent_class_nid):
|
||||
# A user-defined operator or conversion is a static method with a
|
||||
# body, so it is a member node and its calls are its own. Its name
|
||||
# is spelled the way C# writes it (`operator +`, `operator int`)
|
||||
# and is never a call name, so the id always carries the
|
||||
# signature: several conversions share one parameter list.
|
||||
if t == "operator_declaration":
|
||||
op = node.child_by_field_name("operator")
|
||||
op_name = "operator " + (_read_text(op, source) if op is not None else "")
|
||||
op_key = op_name
|
||||
else:
|
||||
to_type = node.child_by_field_name("type")
|
||||
op_name = "operator " + (
|
||||
"".join(_read_text(to_type, source).split()) if to_type is not None else ""
|
||||
)
|
||||
direction = next((c.type for c in node.children
|
||||
if c.type in ("implicit", "explicit")), "")
|
||||
op_key = f"{direction} {op_name}"
|
||||
signature, meta = _csharp_method_signature(node, source)
|
||||
signature = f"{op_key}:{signature}"
|
||||
op_line = node.start_point[0] + 1
|
||||
op_nid = _make_id(parent_class_nid, "operator", hashlib.sha1(
|
||||
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
|
||||
add_node(op_nid, f".{op_name}()", op_line,
|
||||
metadata={**meta, "signature": signature, "kind": "operator"})
|
||||
add_edge(parent_class_nid, op_nid, "method", op_line)
|
||||
op_body = node.child_by_field_name("body")
|
||||
if op_body is not None:
|
||||
csharp_method_scopes[id(op_body)] = (node, parent_class_nid)
|
||||
function_bodies.append((op_nid, op_body))
|
||||
return
|
||||
|
||||
if (config.ts_module == "tree_sitter_c_sharp"
|
||||
and t == "field_declaration"
|
||||
and parent_class_nid):
|
||||
@@ -7908,6 +7999,11 @@ def _extract_generic(
|
||||
add_node(property_nid, property_name, property_line)
|
||||
add_edge(parent_class_nid, property_nid, "defines",
|
||||
property_line, context="field")
|
||||
# Only the declaration that owns the node: an id
|
||||
# another member already took (a method spelled
|
||||
# like an explicit `IFoo.Name` property) must not
|
||||
# be credited with this property's calls.
|
||||
csharp_queue_member_bodies(property_nid, node, parent_class_nid)
|
||||
type_node = node.child_by_field_name("type")
|
||||
if type_node is not None:
|
||||
# Record the property's declared type for the method-scoped
|
||||
@@ -9367,6 +9463,15 @@ def _extract_generic(
|
||||
if config.ts_module in _SELF_CALL_LANGUAGES or lexical_calls:
|
||||
label_by_nid = {n["id"]: n["label"] for n in nodes}
|
||||
for e in edges:
|
||||
if (
|
||||
config.ts_module == "tree_sitter_c_sharp"
|
||||
and e["relation"] == "defines"
|
||||
and e.get("context") == "field"
|
||||
):
|
||||
# A property/indexer whose accessors make calls: an
|
||||
# unqualified call in them looks in its type first, like a
|
||||
# method's. Owner only: it is never a call target by name.
|
||||
method_owner.setdefault(e["target"], e["source"])
|
||||
if e["relation"] == "method":
|
||||
method_owner[e["target"]] = e["source"]
|
||||
name = label_by_nid.get(e["target"], "").strip("()").lstrip(".")
|
||||
|
||||
@@ -158,3 +158,166 @@ def test_case_only_sibling_properties_do_not_duplicate_an_edge(tmp_path):
|
||||
odd = _find(r, "Odd")
|
||||
assert defines == {(odd, _find(r, "Count")), (odd, _find(r, "count"))}
|
||||
assert _find(r, "Count") != _find(r, "count")
|
||||
|
||||
|
||||
# The calls a property, indexer or operator makes belong to that member: its
|
||||
# accessor and operator bodies run code just like a method's.
|
||||
|
||||
def _calls(r):
|
||||
return {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
|
||||
|
||||
|
||||
def _kind(r, kind):
|
||||
return [n for n in r["nodes"] if (n.get("metadata") or {}).get("kind") == kind]
|
||||
|
||||
|
||||
def test_property_accessor_bodies_call_from_the_property(tmp_path):
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public class Svc {\n"
|
||||
" int _v;\n"
|
||||
" public int Block { get { return Load(); } set { Save(value); } }\n"
|
||||
" public int Arrow { get => Load(); }\n"
|
||||
" public int Body => Compute();\n"
|
||||
" public int Auto { get; set; } = Seed();\n"
|
||||
" int Load() { return _v; }\n"
|
||||
" void Save(int v) { _v = v; }\n"
|
||||
" int Compute() { return 1; }\n"
|
||||
" static int Seed() { return 0; }\n"
|
||||
"}\n"
|
||||
)})
|
||||
calls = _calls(r)
|
||||
load, save = _find(r, ".Load()"), _find(r, ".Save()")
|
||||
assert {(_find(r, "Block"), load), (_find(r, "Block"), save)} <= calls
|
||||
assert (_find(r, "Arrow"), load) in calls
|
||||
assert (_find(r, "Body"), _find(r, ".Compute()")) in calls
|
||||
# An initializer runs in the constructor, not in the property.
|
||||
assert (_find(r, "Auto"), _find(r, ".Seed()")) not in calls
|
||||
|
||||
|
||||
def test_accessor_call_prefers_its_own_type_like_a_method(tmp_path):
|
||||
# Other comes last, so a file-wide name lookup would pick its Load().
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public class Svc {\n"
|
||||
" public int Value => Load();\n"
|
||||
" int Load() { return 1; }\n"
|
||||
"}\n"
|
||||
"public class Other { public int Load() { return 2; } }\n"
|
||||
)})
|
||||
own = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "svc" in n["id"])
|
||||
other = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "other" in n["id"])
|
||||
assert (_find(r, "Value"), own) in _calls(r)
|
||||
assert (_find(r, "Value"), other) not in _calls(r)
|
||||
|
||||
|
||||
def test_accessor_call_through_a_typed_receiver_resolves_cross_file(tmp_path):
|
||||
_, r = _extract(tmp_path, {
|
||||
"Repo.cs": "namespace Demo { public class Repo { public int Count() { return 0; } } }\n",
|
||||
"Svc.cs": (
|
||||
"namespace Demo { public class Svc {\n"
|
||||
" private Repo _repo;\n"
|
||||
" public int Total => _repo.Count();\n"
|
||||
"} }\n"
|
||||
),
|
||||
})
|
||||
assert (_find(r, "Total"), _find(r, ".Count()")) in _calls(r)
|
||||
|
||||
|
||||
def test_indexer_is_a_node_and_owns_its_accessor_calls(tmp_path):
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public class Bag {\n"
|
||||
" public int This { get; set; }\n"
|
||||
" public int this[int i] { get { return Get(i); } }\n"
|
||||
" public int this[string k] => Find(k);\n"
|
||||
" int Get(int i) { return i; }\n"
|
||||
" int Find(string k) { return 0; }\n"
|
||||
"}\n"
|
||||
)})
|
||||
indexers = {n["metadata"]["signature"]: n["id"] for n in _kind(r, "indexer")}
|
||||
assert set(indexers) == {"int", "string"}
|
||||
assert indexers["int"] != indexers["string"]
|
||||
# The `This` property keeps the id it had before indexers were nodes.
|
||||
assert _find(r, "This") == _find(r, "Bag") + "_this"
|
||||
assert _find(r, "This") not in indexers.values()
|
||||
calls = _calls(r)
|
||||
assert (indexers["int"], _find(r, ".Get()")) in calls
|
||||
assert (indexers["string"], _find(r, ".Find()")) in calls
|
||||
|
||||
|
||||
def test_operators_and_conversions_are_nodes_that_own_their_calls(tmp_path):
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public class Money {\n"
|
||||
" public static Money operator +(Money a, Money b) => Add(a, b);\n"
|
||||
" public static explicit operator int(Money m) { return ToInt(m); }\n"
|
||||
" public static explicit operator long(Money m) { return ToLong(m); }\n"
|
||||
" static Money Add(Money a, Money b) { return a; }\n"
|
||||
" static int ToInt(Money m) { return 0; }\n"
|
||||
" static long ToLong(Money m) { return 0; }\n"
|
||||
"}\n"
|
||||
)})
|
||||
ops = {n["label"]: n["id"] for n in _kind(r, "operator")}
|
||||
assert set(ops) == {".operator +()", ".operator int()", ".operator long()"}
|
||||
calls = _calls(r)
|
||||
assert (ops[".operator +()"], _find(r, ".Add()")) in calls
|
||||
assert (ops[".operator int()"], _find(r, ".ToInt()")) in calls
|
||||
assert (ops[".operator long()"], _find(r, ".ToLong()")) in calls
|
||||
assert (ops[".operator int()"], _find(r, ".ToLong()")) not in calls
|
||||
|
||||
|
||||
def test_accessor_base_call_resolves_to_the_base_in_another_file(tmp_path):
|
||||
_, r = _extract(tmp_path, {
|
||||
"Base.cs": "namespace Demo { public class Base { public int Compute() { return 0; } } }\n",
|
||||
"Svc.cs": (
|
||||
"namespace Demo { public class Svc : Base {\n"
|
||||
" public int Total => base.Compute();\n"
|
||||
"} }\n"
|
||||
),
|
||||
})
|
||||
assert (_find(r, "Total"), _find(r, ".Compute()")) in _calls(r)
|
||||
|
||||
|
||||
def test_accessor_call_binds_the_other_partial_half_over_a_same_named_method(tmp_path):
|
||||
_, r = _extract(tmp_path, {
|
||||
"SvcA.cs": "namespace Demo { public partial class Svc { public int Value => Load(); } }\n",
|
||||
"SvcB.cs": "namespace Demo { public partial class Svc { int Load() { return 1; } } }\n",
|
||||
"Other.cs": "namespace Demo { public class Other { public int Load() { return 2; } } }\n",
|
||||
})
|
||||
own = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "svc" in n["id"])
|
||||
other = next(n["id"] for n in r["nodes"] if n["label"] == ".Load()" and "other" in n["id"])
|
||||
assert (_find(r, "Value"), own) in _calls(r)
|
||||
assert (_find(r, "Value"), other) not in _calls(r)
|
||||
|
||||
|
||||
def test_explicit_interface_indexers_keep_their_own_calls(tmp_path):
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public interface IA { int this[int i] { get; } }\n"
|
||||
"public interface IB { int this[int i] { get; } }\n"
|
||||
"public class C : IA, IB {\n"
|
||||
" int IA.this[int i] => A();\n"
|
||||
" int IB.this[int i] => B();\n"
|
||||
" int A() { return 1; }\n"
|
||||
" int B() { return 2; }\n"
|
||||
"}\n"
|
||||
)})
|
||||
by_line = {n["source_location"]: n["id"] for n in _kind(r, "indexer")
|
||||
if "_c_" in n["id"]}
|
||||
assert len(by_line) == 2
|
||||
calls = _calls(r)
|
||||
assert (by_line["L4"], _find(r, ".A()")) in calls
|
||||
assert (by_line["L5"], _find(r, ".B()")) in calls
|
||||
assert (by_line["L4"], _find(r, ".B()")) not in calls
|
||||
|
||||
|
||||
def test_property_sharing_a_methods_id_does_not_lend_it_its_calls(tmp_path):
|
||||
# `IRun.Next` and `Next()` normalize to one id, which the method owns; the
|
||||
# property's call must not be credited to the method (a self-loop here).
|
||||
_, r = _extract(tmp_path, {"S.cs": (
|
||||
"public interface IRun { int Next { get; } }\n"
|
||||
"public class Run : IRun {\n"
|
||||
" int Next() { return Other(); }\n"
|
||||
" int IRun.Next => Next();\n"
|
||||
" int Other() { return 0; }\n"
|
||||
"}\n"
|
||||
)})
|
||||
method = _find(r, ".Next()")
|
||||
assert (method, method) not in _calls(r)
|
||||
assert (method, _find(r, ".Other()")) in _calls(r)
|
||||
Reference in new issue
Block a user