Skip to content

Commit 931ca22

Browse files
JensD-gitclaude
authored andcommitted
fix(csharp): keep names that differ only by _ or case apart, in ids and in member-call keys (#4415)
make_id strips leading/trailing underscores and casefolds, while C# is case-sensitive and spells private members `_Name`. In one file, `Action()` / `_Action()`, `Size` / `_Size`, `Load()` / `load()` and the types `Pair` / `_Pair` minted one id; add_node kept the first declaration and dropped the second, and the dropped method's calls were credited to the survivor. Apply the rule of #3302 to C#: a pre-scan groups the declared names of a file (types; per type its methods, properties and enum members) that would share an id, and _underscore_salted_nid (renamed from the Python helper, unchanged) keeps the plain id on the one name without a leading underscore and salts the rest. In-file type references and base lists go through the same rule. A name without a colliding sibling keeps its id. The C# member-call resolver keyed names by lowercased alphanumerics, so `this.Put()` bound to `_Put()` on a nearer base, and `Token` / `TOKEN` were one type key. The key now keeps `_` and case. Fixes #4415. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> (cherry picked from commit 914dda6)
1 parent b4f4a5b commit 931ca22

5 files changed

Lines changed: 441 additions & 28 deletions

File tree

‎graphify/extract.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5367,7 +5367,10 @@ def _resolve_csharp_member_calls(
53675367
Must run after id-disambiguation so node ids and caller_nids are final.
53685368
"""
53695369
def _key(label: str) -> str:
5370-
return re.sub(r"[^a-zA-Z0-9]+", "", str(label)).lower()
5370+
# Case and `_` are part of a C# name: `Put` and `_Put` are two
5371+
# methods, so `this.Put()` must not bind to `_Put` (#4415). Only the
5372+
# label decoration (`.Put()`) goes.
5373+
return re.sub(r"\W+", "", str(label))
53715374

53725375
contained = {e.get("target") for e in all_edges if e.get("relation") == "contains"}
53735376

‎graphify/extractors/engine.py‎

Lines changed: 144 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,107 @@ def _csharp_pre_scan_interfaces(root_node, source: bytes) -> set[str]:
168168
stack.extend(n.children)
169169
return out
170170

171+
_CSHARP_TYPE_DECLARATIONS = frozenset({
172+
"class_declaration",
173+
"interface_declaration",
174+
"enum_declaration",
175+
"struct_declaration",
176+
"record_declaration",
177+
})
178+
179+
180+
def _csharp_type_name_for_id(node, class_name: str) -> str:
181+
"""A C# type's name as its node id spells it: the arity folds in (#4249).
182+
183+
`Effect` and `Effect<T>` are different types, so the generic one is named
184+
the way C# metadata names it (`` Effect`1 ``); arity 0 is the bare name.
185+
"""
186+
arity = sum(
187+
1 for c in node.children if c.type == "type_parameter_list"
188+
for _p in c.children if _p.type in ("type_parameter", "identifier")
189+
)
190+
return f"{class_name}`{arity}" if arity else class_name
191+
192+
193+
def _csharp_pre_scan_name_collisions(
194+
root_node, source: bytes, stem: str
195+
) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
196+
"""Pre-scan a C# file for declared names that collapse to one node id.
197+
198+
C# is case-sensitive and `_Name` is the usual spelling of a private member,
199+
but ``ids.py:make_id`` strips leading/trailing underscores and casefolds, so
200+
`Action()` / `_Action()`, `Size` / `_Size`, `Load()` / `load()` and the types
201+
`Pair` / `_Pair` each mint ONE id. ``add_node`` keeps the first declaration
202+
and drops the second; the dropped method's calls are credited to the
203+
survivor, and a type's members hang off the other type (#4415). This is
204+
the Python #3302 collision in C#; the outcome is the same rule
205+
(``_underscore_salted_nid``).
206+
207+
Returns ``(type_groups, member_groups)``, each ``{plain_nid: {raw names}}``
208+
for the ids two or more distinct names would share. Types are keyed the way
209+
the walk mints them (``_make_id(stem, namespace, name_for_id)``), members
210+
(methods, properties, enum members) by ``_make_id(type_nid, name)`` where
211+
``type_nid`` is the type's FINAL id, already salted when the type itself
212+
collides. Same-file partial declarations of one type share an id, so their
213+
members are grouped together. Overloads are one name, never a collision.
214+
"""
215+
type_names: dict[str, set[str]] = {}
216+
member_names: dict[str, set[str]] = {}
217+
type_decls: list[tuple[object, str, str]] = []
218+
219+
def _visit(n, ns: list[str]) -> None:
220+
# Types are declared only at file level, in namespace and type bodies
221+
# and in #if wrappers around them, so only those are entered: the
222+
# recursion depth is the nesting depth of declarations, never of
223+
# expressions.
224+
scoped = list(ns)
225+
for c in n.children:
226+
if c.type == "namespace_declaration":
227+
ns_name = _csharp_namespace_name(c, source)
228+
body = c.child_by_field_name("body")
229+
if body is not None:
230+
_visit(body, scoped + [ns_name] if ns_name else scoped)
231+
elif c.type == "file_scoped_namespace_declaration":
232+
# Applies to the rest of the file, as in the walk.
233+
ns_name = _csharp_namespace_name(c, source)
234+
if ns_name:
235+
scoped = scoped + [ns_name]
236+
elif c.type in _CSHARP_TYPE_DECLARATIONS:
237+
name_node = c.child_by_field_name("name")
238+
name = _read_text(name_node, source) if name_node is not None else ""
239+
if name:
240+
plain = _make_id(stem, ".".join(scoped), _csharp_type_name_for_id(c, name))
241+
type_names.setdefault(plain, set()).add(name)
242+
type_decls.append((c, plain, name))
243+
# Nested types take the namespace, not the enclosing type (ids
244+
# omit the outer type), so they join the same groups.
245+
_visit(c, scoped)
246+
elif c.type == "declaration_list" or c.type.startswith("preproc_"):
247+
_visit(c, scoped)
248+
249+
_visit(root_node, [])
250+
type_groups = {nid: names for nid, names in type_names.items() if len(names) >= 2}
251+
252+
def _members(n, type_nid: str) -> None:
253+
for c in n.children:
254+
if c.type in ("method_declaration", "property_declaration",
255+
"enum_member_declaration"):
256+
name_node = c.child_by_field_name("name")
257+
name = _read_text(name_node, source) if name_node is not None else ""
258+
if name:
259+
member_names.setdefault(_make_id(type_nid, name), set()).add(name)
260+
elif c.type in ("declaration_list", "enum_member_declaration_list") or (
261+
c.type.startswith("preproc_")
262+
):
263+
# The body, and #if/#region wrappers the walk sees through (#2631).
264+
_members(c, type_nid)
265+
266+
for decl, plain, name in type_decls:
267+
_members(decl, _underscore_salted_nid(plain, name, type_groups))
268+
member_groups = {nid: names for nid, names in member_names.items() if len(names) >= 2}
269+
return type_groups, member_groups
270+
271+
171272
def _csharp_classify_base(name: str, interface_names: set[str]) -> str:
172273
"""`implements` if the base name is an interface (declared or by I-prefix convention), else `inherits`."""
173274
if name in interface_names:
@@ -1189,10 +1290,11 @@ def _record(plain_nid: str, name: str) -> None:
11891290
return {nid: names for nid, names in groups.items() if len(names) >= 2}
11901291

11911292

1192-
def _python_underscore_salted_nid(plain_nid: str, name: str, groups: dict[str, set[str]]) -> str:
1193-
"""Resolve a Python function/method's real node id against the collision map.
1293+
def _underscore_salted_nid(plain_nid: str, name: str, groups: dict[str, set[str]]) -> str:
1294+
"""Resolve a declaration's real node id against the collision map.
11941295

1195-
A name with no leading underscore at all is "public" per PEP 8 convention.
1296+
Shared by the Python and C# pre-scans (#3302, #4415). A name with no
1297+
leading underscore at all is "public" per PEP 8 convention.
11961298
When a collision group has exactly one public member, that member keeps the
11971299
plain id — cross-file/documentation references overwhelmingly target the
11981300
public name, and keeping it stable means an incremental rebuild that adds or
@@ -4102,7 +4204,8 @@ def _csharp_namespace_name(node, source: bytes) -> str:
41024204
def _csharp_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str,
41034205
nodes: list, edges: list, seen_ids: set, function_bodies: list,
41044206
parent_class_nid: str | None, add_node_fn, add_edge_fn,
4105-
walk_fn, namespace_stack: list[str], scope_stack: list[str]) -> bool:
4207+
walk_fn, namespace_stack: list[str], scope_stack: list[str],
4208+
member_groups: dict[str, set[str]] | None = None) -> bool:
41064209
"""Handle C# namespaces, enum members, and transparent class-member wrappers."""
41074210
if node.type == "enum_member_declaration" and parent_class_nid:
41084211
# `enum_declaration` is in C#'s class_types, so the enum type is a node
@@ -4118,11 +4221,13 @@ def _csharp_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path:
41184221
if not member_name:
41194222
return True
41204223
line = node.start_point[0] + 1
4121-
member_nid = _make_id(parent_class_nid, member_name)
41224224
# C# is case-sensitive, so `enum E { Value, value }` is legal, but the id
4123-
# recipe casefolds — both members normalize to one id. Emitting the
4124-
# second would hang a duplicate edge on the first member's node, so the
4125-
# first declaration keeps it (same guard as the property nodes in #3006).
4225+
# recipe casefolds — both members normalize to one id. The pre-scan
4226+
# salts such a pair apart (#4415); the guard stays for anything else
4227+
# that lands on one id.
4228+
member_nid = _underscore_salted_nid(
4229+
_make_id(parent_class_nid, member_name), member_name, member_groups or {}
4230+
)
41264231
if member_nid not in seen_ids:
41274232
add_node_fn(member_nid, member_name, line)
41284233
add_edge_fn(parent_class_nid, member_nid, "case_of", line)
@@ -5388,8 +5493,13 @@ def _extract_generic(
53885493
csharp_method_returns: dict[str, dict[str, list]] = {}
53895494

53905495
csharp_interface_names: set[str] = set()
5496+
csharp_type_groups: dict[str, set[str]] = {}
5497+
csharp_member_groups: dict[str, set[str]] = {}
53915498
if config.ts_module == "tree_sitter_c_sharp":
53925499
csharp_interface_names = _csharp_pre_scan_interfaces(root, source)
5500+
csharp_type_groups, csharp_member_groups = _csharp_pre_scan_name_collisions(
5501+
root, source, stem
5502+
)
53935503

53945504
swift_protocol_names: set[str] = set()
53955505
swift_class_names: set[str] = set()
@@ -5444,6 +5554,8 @@ def add_edge(src: str, tgt: str, relation: str, line: int,
54445554

54455555
def ensure_named_node(name: str, line: int) -> str:
54465556
nid = _make_id(stem, ".".join(namespace_stack), name)
5557+
if config.ts_module == "tree_sitter_c_sharp":
5558+
nid = _underscore_salted_nid(nid, name, csharp_type_groups)
54475559
if nid in seen_ids:
54485560
return nid
54495561
nid = _make_id(name)
@@ -5590,13 +5702,11 @@ def walk(node, parent_class_nid: str | None = None) -> None:
55905702
# matching how C# metadata itself names a generic type
55915703
# (`` Effect`1 ``), so each arity gets its own node; the
55925704
# label is untouched; arity 0 keeps today's id exactly.
5593-
_csharp_arity = sum(
5594-
1 for c in node.children if c.type == "type_parameter_list"
5595-
for _p in c.children if _p.type in ("type_parameter", "identifier")
5596-
)
5597-
if _csharp_arity:
5598-
class_name_for_id = f"{class_name}`{_csharp_arity}"
5705+
class_name_for_id = _csharp_type_name_for_id(node, class_name)
55995706
class_nid = _make_id(stem, ".".join(namespace_stack), class_name_for_id)
5707+
if config.ts_module == "tree_sitter_c_sharp":
5708+
# `Pair` / `_Pair` in one file share an id otherwise (#4415).
5709+
class_nid = _underscore_salted_nid(class_nid, class_name, csharp_type_groups)
56005710
if config.ts_module == "tree_sitter_python" and parent_class_nid:
56015711
class_nid = _make_id(parent_class_nid, class_name)
56025712
line = node.start_point[0] + 1
@@ -6033,13 +6143,19 @@ def _php_emit_base(base_name: str, rel: str, at_line: int) -> None:
60336143
)
60346144
base_nid = None
60356145
if base_arity:
6036-
_arity_nid = _make_id(
6037-
stem, ".".join(namespace_stack), f"{base}`{base_arity}"
6146+
_arity_nid = _underscore_salted_nid(
6147+
_make_id(
6148+
stem, ".".join(namespace_stack), f"{base}`{base_arity}"
6149+
),
6150+
base, csharp_type_groups,
60386151
)
60396152
if _arity_nid in seen_ids:
60406153
base_nid = _arity_nid
60416154
if base_nid is None:
6042-
base_nid = _make_id(stem, ".".join(namespace_stack), base)
6155+
base_nid = _underscore_salted_nid(
6156+
_make_id(stem, ".".join(namespace_stack), base),
6157+
base, csharp_type_groups,
6158+
)
60436159
if base_nid not in seen_ids:
60446160
base_nid = _make_id(base)
60456161
if base_nid not in seen_ids:
@@ -6577,7 +6693,10 @@ def scala_base_name(type_node) -> str | None:
65776693
property_name = _read_text(prop_node_name, source)
65786694
if property_name:
65796695
property_line = node.start_point[0] + 1
6580-
property_nid = _make_id(parent_class_nid, property_name)
6696+
property_nid = _underscore_salted_nid(
6697+
_make_id(parent_class_nid, property_name),
6698+
property_name, csharp_member_groups,
6699+
)
65816700
if property_nid not in seen_ids:
65826701
add_node(property_nid, property_name, property_line)
65836702
add_edge(parent_class_nid, property_nid, "defines",
@@ -7036,9 +7155,13 @@ def scala_base_name(type_node) -> str | None:
70367155
if parent_class_nid:
70377156
func_nid = _make_id(parent_class_nid, sanitized_name)
70387157
if config.ts_module == "tree_sitter_python":
7039-
func_nid = _python_underscore_salted_nid(
7158+
func_nid = _underscore_salted_nid(
70407159
func_nid, sanitized_name, python_underscore_groups
70417160
)
7161+
elif config.ts_module == "tree_sitter_c_sharp":
7162+
func_nid = _underscore_salted_nid(
7163+
func_nid, sanitized_name, csharp_member_groups
7164+
)
70427165
ruby_method_metadata = None
70437166
if ruby_method_kind is not None:
70447167
kinds = ruby_method_kinds.setdefault(func_nid, set())
@@ -7073,7 +7196,7 @@ def scala_base_name(type_node) -> str | None:
70737196
else:
70747197
func_nid = _make_id(stem, sanitized_name)
70757198
if config.ts_module == "tree_sitter_python":
7076-
func_nid = _python_underscore_salted_nid(
7199+
func_nid = _underscore_salted_nid(
70777200
func_nid, sanitized_name, python_underscore_groups
70787201
)
70797202
add_node(func_nid, f"{func_name}()", line)
@@ -7643,7 +7766,7 @@ def scala_base_name(type_node) -> str | None:
76437766
if _csharp_extra_walk(node, source, file_nid, stem, str_path,
76447767
nodes, edges, seen_ids, function_bodies,
76457768
parent_class_nid, add_node, add_edge, walk,
7646-
namespace_stack, scope_stack):
7769+
namespace_stack, scope_stack, csharp_member_groups):
76477770
return
76487771

76497772
if config.ts_module == "tree_sitter_swift":

‎tests/test_csharp_enum_members.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,15 +76,18 @@ def test_an_explicit_value_does_not_change_the_member(tmp_path):
7676

7777

7878
def test_case_only_sibling_members_do_not_duplicate_an_edge(tmp_path):
79-
# Legal C#, and one id after normalization. The first declaration keeps the
80-
# node rather than a second edge hanging off it.
79+
# Legal C#, and one id after normalization. Each member gets its own node
80+
# (#4415) with its own edge, rather than a second edge hanging off the
81+
# first member's node.
8182
case_of, r = _extract(tmp_path, {"S.cs": (
8283
"public enum Odd {\n"
8384
" Value,\n"
8485
" value\n"
8586
"}\n"
8687
)})
87-
assert len(case_of) == 1
88+
odd = _find(r, "Odd")
89+
assert case_of == {(odd, _find(r, "Value")), (odd, _find(r, "value"))}
90+
assert _find(r, "Value") != _find(r, "value")
8891

8992

9093
def test_a_namespaced_enum_still_emits_members(tmp_path):

‎tests/test_csharp_member_nodes.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,12 +146,15 @@ def test_methods_are_still_methods(tmp_path):
146146

147147

148148
def test_case_only_sibling_properties_do_not_duplicate_an_edge(tmp_path):
149-
# Legal C#, and one id after normalization. One node, one edge, rather than a
150-
# second edge hung on the first property's node.
149+
# Legal C#, and one id after normalization. Each property gets its own node
150+
# (#4415) and one edge, rather than a second edge hung on the first
151+
# property's node.
151152
defines, r = _extract(tmp_path, {"S.cs": (
152153
"public class Odd {\n"
153154
" public int Count { get; set; }\n"
154155
" public int count { get; set; }\n"
155156
"}\n"
156157
)})
157-
assert len(defines) == 1
158+
odd = _find(r, "Odd")
159+
assert defines == {(odd, _find(r, "Count")), (odd, _find(r, "count"))}
160+
assert _find(r, "Count") != _find(r, "count")

0 commit comments

Comments
 (0)