fix(csharp): make constructors nodes and link new/base/this to the overload by arity

A C# constructor had no node. Calls in its body were credited to the
type (#4246), calls in `: base(...)`/`: this(...)` arguments were never
walked, and `new X(a, b)` could only point at the type, never at the
overload it runs. On Dapper, AutoMapper and Newtonsoft.Json (Roslyn answer
key) 151 call links made from constructors were all lost and none of the
130 constructor initializers was linked.

- Each constructor (instance, static, and a type's primary constructor)
  is a node owned by its type through a `method` edge, labeled
  `.TypeName()` with metadata kind "constructor" plus arity/signature.
  The id is `_make_id(type_id, TypeName)`, the one a method named after
  the type would get; other signatures are salted like method overloads
  (#4584), a static constructor is its own "static" signature, and if a
  member spelled like the type in another case (`foo()` in `Foo`)
  already owns that id the constructor takes a salted one. No existing
  node id changes (checked on all three projects).
- Body and initializer calls belong to the constructor.
- `new X(...)` sites and initializers are recorded in raw_calls with no
  callee (so every name-keyed consumer skips them and the id passes
  remap their caller). A tail C# pass links the constructor whose
  parameter count fits, next to the existing edge to the type.
  `: this(...)` uses the own type, `: base(...)` the single resolvable
  base. Two fitting overloads, an unresolved base, or a type the caller
  did not bind give no edge.
- Constructors are left out of every name-keyed call index (in-file
  label map, global label index, member-call index, overload index,
  interface dispatch), so a constructor can never be picked for an
  ordinary call or shadow its type.
- AST cache schema 40.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 10332b79f5)
This commit is contained in:
rohit-jsfreaky authored and safishamsi committed 2026-11-07 17:20:08 +00:00
1 parent ebef2af2b9
commit c3b6cfbd9f
9 files changed
+467 -19

No files matched your search

+14
View File
@@ -197,6 +197,20 @@ lack this path. The merge runs after colliding ids are salted apart by path, so
a half whose file stem collides with another file's (`Spec.cs` and `_Spec.cs`,
`Cfg/Helpers.cs` and `Cfg_Helpers.cs`) still merges and keeps its members.
C# constructors (instance, static and a type's primary constructor) are nodes
owned by their type through a `method` edge, labeled `.TypeName()` with
metadata `kind: "constructor"`. The id is the one a method named after the type
would get, `_make_id(type_id, TypeName)`; each further signature is salted like
a method overload, a static constructor is its own `static` signature, and when
a member spelled like the type in another case (`foo()` in `Foo`) already owns
that id, the constructor takes a salted one, so no existing id moves. Calls in
a constructor's body and `: base(...)`/`: this(...)` arguments are its calls.
`new X(...)` keeps its edge to the type and also links the constructor whose
parameter count fits, as do `: base(...)`/`: this(...)`; two fitting overloads,
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.
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
+136
View File
@@ -63,6 +63,7 @@ from graphify.extractors.csharp import (
_resolve_cross_file_csharp_imports,
_resolve_csharp_type_references,
bare_csharp_method_labels_in_nodes,
is_csharp_constructor_node,
)
from graphify.extractors.dart import extract_dart # noqa: F401
from graphify.extractors.dm import extract_dm, extract_dmf, extract_dmi, extract_dmm # noqa: F401
@@ -6310,6 +6311,7 @@ def _csharp_overload_index(nodes: list[dict], edges: list[dict]) -> dict:
e.get("target"): e.get("source") for e in edges
if e.get("relation") == "method"
and "arity" in ((node_by_id.get(e.get("target")) or {}).get("metadata") or {})
and not is_csharp_constructor_node(node_by_id.get(e.get("target")) or {})
},
}
@@ -6412,6 +6414,8 @@ def _resolve_csharp_member_calls(
if tnode is None:
continue
enclosing_type.setdefault(tgt, src)
if is_csharp_constructor_node(tnode):
continue # owns its calls (enclosing_type), but is never `x.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", "")))
@@ -7740,6 +7744,127 @@ def _resolve_c_include_edges(
e.pop("target_file", None)
def _resolve_csharp_constructor_calls(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link a C# construction to the constructor overload it runs.
`new X(a, b)` already has a `calls` edge to the type X (in-file or from
the shared/qualified passes). This adds one to the X constructor whose
parameter count fits two arguments, and links a constructor's
`: this(...)` to its own type's overload and `: base(...)` to its base
type's. Additive: the edge to the type stays.
Fail closed, never a guess across types or overloads:
* the type is the one the caller's own `calls` edges already bound for
that name; none, or two types with the name, gives no edge;
* `: base(...)` needs exactly one resolvable `inherits` target, and no
unresolved (out-of-corpus) base;
* exactly one non-static constructor (explicit or primary) must accept
the argument count (``_csharp_pick_overload``); a type with no
declared constructor gets no edge.
"""
records = [
rc for result in per_file if isinstance(result, dict)
for rc in result.get("raw_calls", []) or []
if rc.get("lang") == "csharp"
and (rc.get("csharp_ctor_site") or rc.get("csharp_ctor_init"))
]
if not records:
return
node_by_id = {n.get("id"): n for n in all_nodes}
ctors_of: dict[str, list[dict]] = {}
owner_of: dict[str, str] = {}
for e in all_edges:
if e.get("relation") != "method":
continue
tnode = node_by_id.get(e.get("target"))
type_nid = e.get("source")
if tnode is None or not isinstance(type_nid, str) or not is_csharp_constructor_node(tnode):
continue
owner_of.setdefault(tnode["id"], type_nid)
bucket = ctors_of.setdefault(type_nid, [])
if all(c["id"] != tnode["id"] for c in bucket):
bucket.append(tnode)
def _pick(type_nid: str | None, argc: object) -> dict | None:
ctors = [
c for c in ctors_of.get(type_nid or "", [])
if (c.get("metadata") or {}).get("signature") != "static"
]
if not ctors or not isinstance(argc, int):
return None
return _csharp_pick_overload(ctors, argc)
def _bare(label: object) -> str:
return re.sub(r"\W+", "", str(label or ""))
# caller -> bare type name -> {type nid: confidence of the `new` edge}
built: dict[str, dict[str, dict[str, str]]] = {}
callers = {rc.get("caller_nid") for rc in records if rc.get("csharp_ctor_site")}
for e in all_edges:
if e.get("relation") != "calls" or e.get("source") not in callers:
continue
tnode = node_by_id.get(e.get("target"))
if tnode is None or tnode["id"] in owner_of or not tnode.get("source_file"):
continue
built.setdefault(e["source"], {}).setdefault(_bare(tnode.get("label")), {})[
tnode["id"]
] = str(e.get("confidence") or "INFERRED")
bases_of: dict[str, set[str]] = {}
unresolved_base: set[str] = set()
for e in all_edges:
derived = e.get("source")
if (e.get("relation") != "inherits" or not isinstance(derived, str)
or not _is_cs_file(e.get("source_file"))):
continue
tnode = node_by_id.get(e.get("target"))
if tnode is None or not tnode.get("source_file"):
unresolved_base.add(derived)
else:
bases_of.setdefault(derived, set()).add(tnode["id"])
existing = {
(e.get("source"), e.get("target")) for e in all_edges if e.get("relation") == "calls"
}
for rc in records:
caller = rc.get("caller_nid")
if not caller:
continue
confidence = "EXTRACTED"
if rc.get("csharp_ctor_site"):
types = built.get(caller, {}).get(rc["csharp_ctor_site"], {})
if len(types) != 1:
continue
type_nid, confidence = next(iter(types.items()))
elif rc.get("csharp_ctor_init") == "this":
type_nid = owner_of.get(caller)
else:
owner = owner_of.get(caller)
bases = bases_of.get(owner or "", set())
if owner is None or owner in unresolved_base or len(bases) != 1:
continue
type_nid = next(iter(bases))
target = _pick(type_nid, rc.get("arity"))
if target is None or target["id"] == caller or (caller, target["id"]) in existing:
continue
existing.add((caller, target["id"]))
all_edges.append({
"source": caller,
"target": target["id"],
"relation": "calls",
"context": "call",
"confidence": confidence,
"confidence_score": 1.0 if confidence == "EXTRACTED" else 0.85,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _resolve_csharp_qualified_calls(
per_file: list[dict],
all_nodes: list[dict],
@@ -8674,6 +8799,14 @@ register_language_resolver(
"csharp_qualified_calls", frozenset({".cs"}), _resolve_csharp_qualified_calls
)
)
# C# constructors (`new X(a, b)`, `: base(...)`, `: this(...)`): the overload
# that runs, picked by argument count once the constructed type is bound.
# Runs after csharp_qualified_calls so every `new` has its type edge.
register_language_resolver(
LanguageResolver(
"csharp_constructor_calls", frozenset({".cs"}), _resolve_csharp_constructor_calls
)
)
# C# member-level interface dispatch (#3003): a call through an injected
# dependency lands on the interface's method, so the implementation sits in the
# graph unreachable from the call site. Lives in graphify.csharp_dispatch;
@@ -11530,6 +11663,9 @@ def extract(
for n in resolution_nodes:
if n.get("file_type") == "rationale" or n.get("type") == "namespace":
continue
# A C# constructor is named like its type but never called by name.
if is_csharp_constructor_node(n):
continue
raw = n.get("label", "")
normalised = raw.strip("()").lstrip(".")
if normalised:
+15
View File
@@ -18,6 +18,21 @@ from graphify.extractors.base import _make_id
from graphify.rcfile import effective_suffix
def is_csharp_constructor_node(node: dict) -> bool:
"""A C# constructor node (instance, static or primary).
A constructor carries its type's name but is reached only through `new`
or a `: base(...)` / `: this(...)` initializer, never by that name, so the
name-keyed call indexes leave it out.
"""
metadata = node.get("metadata") or {}
return (
isinstance(metadata, dict)
and metadata.get("kind") == "constructor"
and effective_suffix(str(node.get("source_file") or "")) == ".cs"
)
def _build_csharp_type_def_index(
all_nodes: list[dict],
all_edges: list[dict] | None = None,
+126 -15
View File
@@ -194,7 +194,7 @@ def _csharp_type_name_for_id(node, class_name: str) -> str:
return f"{class_name}`{arity}" if arity else class_name
def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
def _csharp_method_signature(node, source: bytes, params=None) -> tuple[str, dict]:
"""A C# method's parameter signature and the argument counts it accepts.
The signature (``"`1:this Foo,ref int,params int[]"``) tells overloads
@@ -205,7 +205,12 @@ def _csharp_method_signature(node, source: bytes) -> tuple[str, dict]:
parts: list[str] = []
arity = required = 0
variadic = extension = False
params = node.child_by_field_name("parameters")
# 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.
primary = params is not None
if params is None:
params = node.child_by_field_name("parameters")
children = params.children if params is not None else []
for i, c in enumerate(children):
if c.type == "parameter":
@@ -225,7 +230,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(
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")
)
@@ -250,6 +255,17 @@ def _csharp_argc(call_node) -> int | None:
return sum(1 for c in args.children if c.type == "argument") if args is not None else 0
def _csharp_creation_argc(node) -> int:
"""Argument count of a C# `new X(...)` / `new X { ... }` / `: base(...)`.
No argument list (`new X { A = 1 }`) runs the parameterless constructor.
"""
args = node.child_by_field_name("arguments")
if args is None:
args = next((c for c in node.children if c.type == "argument_list"), None)
return sum(1 for c in args.children if c.type == "argument") if args is not None else 0
def _csharp_pick_overload(overloads: list[dict], argc: int | None) -> dict | None:
"""The one overload a call with ``argc`` arguments can mean, or None.
@@ -275,7 +291,7 @@ def _csharp_pick_overload(overloads: list[dict], argc: int | None) -> dict | Non
def _csharp_pre_scan_name_collisions(
root_node, source: bytes, stem: str
) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
) -> tuple[dict[str, set[str]], dict[str, set[str]], set[str]]:
"""Pre-scan a C# file for declared names that collapse to one node id.
C# is case-sensitive and `_Name` is the usual spelling of a private member,
@@ -287,8 +303,10 @@ def _csharp_pre_scan_name_collisions(
the Python #3302 collision in C#; the outcome is the same rule
(``_underscore_salted_nid``).
Returns ``(type_groups, member_groups)``, each ``{plain_nid: {raw names}}``
for the ids two or more distinct names would share. Types are keyed the way
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
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
@@ -349,7 +367,7 @@ def _csharp_pre_scan_name_collisions(
for decl, plain, name in type_decls:
_members(decl, _underscore_salted_nid(plain, name, type_groups))
member_groups = {nid: names for nid, names in member_names.items() if len(names) >= 2}
return type_groups, member_groups
return type_groups, member_groups, set(member_names)
def _csharp_classify_base(name: str, interface_names: set[str]) -> str:
@@ -6569,10 +6587,13 @@ def _extract_generic(
csharp_interface_names: set[str] = set()
csharp_type_groups: dict[str, set[str]] = {}
csharp_member_groups: dict[str, set[str]] = {}
csharp_member_ids: set[str] = set()
# plain constructor nid -> {signature: node}, like csharp_overloads.
csharp_ctor_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_pre_scan_name_collisions(
root, source, stem
csharp_type_groups, csharp_member_groups, csharp_member_ids = (
_csharp_pre_scan_name_collisions(root, source, stem)
)
swift_protocol_names: set[str] = set()
@@ -6706,6 +6727,41 @@ def _extract_generic(
file_metadata["ruby_external_method_owners"] = external_owners
file_node["metadata"] = sanitize_metadata(file_metadata)
# C# `new X(...)` sites and `: base(...)` / `: this(...)` initializers.
# They join raw_calls after the call walk, with no `callee`, so every
# name-keyed consumer skips them and only the constructor pass reads them.
csharp_ctor_records: list[dict] = []
def csharp_add_constructor(type_nid: str, type_name: str, decl, params,
line: int, static: bool) -> str:
"""Mint the node for one C# constructor and own it from its type.
The id is the one a method named after the type would get, so the
first declared constructor keeps it and each other signature is salted
like a method overload (#4584). A member spelled like the type in
another case (`Foo` / `foo()`) already owns that id: the constructor,
never the existing member, takes a salted one. A static constructor
has no parameters and is never what `new` runs, so it is its own
signature.
"""
signature, meta = _csharp_method_signature(decl, source, params)
if static:
signature, meta = "static", {"arity": 0}
ctor_nid = _make_id(type_nid, type_name)
if ctor_nid in csharp_member_ids:
ctor_nid = _make_id(ctor_nid, hashlib.sha1(
b".ctor", usedforsecurity=False).hexdigest()[:6])
group = csharp_ctor_overloads.setdefault(ctor_nid, {})
if group and signature not in group:
ctor_nid = _make_id(ctor_nid, hashlib.sha1(
signature.encode("utf-8"), usedforsecurity=False).hexdigest()[:6])
add_node(ctor_nid, f".{type_name}()", line,
metadata={**meta, "signature": signature, "kind": "constructor"})
if signature not in group and nodes and nodes[-1]["id"] == ctor_nid:
group[signature] = nodes[-1]
add_edge(type_nid, ctor_nid, "method", line)
return ctor_nid
def walk(node, parent_class_nid: str | None = None) -> None:
nonlocal ruby_singleton_context_depth
t = node.type
@@ -6926,6 +6982,17 @@ def _extract_generic(
add_edge(parent_class_nid, class_nid, "contains", line)
else:
add_edge(file_nid, class_nid, "contains", line)
if config.ts_module == "tree_sitter_c_sharp" and t != "interface_declaration":
# `class Foo(int x)` / `record R(int A)`: the primary
# constructor is one of Foo's constructors, so `new Foo(1)`
# must weigh it against the explicit ones (it has no body).
primary_params = next(
(c for c in node.children if c.type == "parameter_list"), None
)
if primary_params is not None:
csharp_add_constructor(
class_nid, class_name, node, primary_params, line, False
)
# TS/JS decorators on the class and its members (@Component, @Injectable,
# @Input, @Inject, @Entity, …). Decorators live only in class subtrees.
@@ -7709,12 +7776,37 @@ def _extract_generic(
if (config.ts_module == "tree_sitter_c_sharp"
and t == "constructor_declaration"
and parent_class_nid):
# A C# constructor has no node of its own, so its body was never
# walked for calls. Attribute them to the declaring type (#4246).
ctor_body = node.child_by_field_name("body")
if ctor_body is not None:
csharp_method_scopes[id(ctor_body)] = (node, parent_class_nid)
function_bodies.append((parent_class_nid, ctor_body))
# A constructor is a node of its own, like a method, so the calls
# in its body and initializer are its calls, not the type's
# (#4246 credited them to the type).
ctor_name_node = node.child_by_field_name("name")
ctor_name = _read_text(ctor_name_node, source) if ctor_name_node is not None else ""
if ctor_name:
ctor_line = node.start_point[0] + 1
ctor_nid = csharp_add_constructor(
parent_class_nid, ctor_name, node, None, ctor_line,
any(c.type == "modifier" and _read_text(c, source) == "static"
for c in node.children),
)
for part in node.children:
if part.type == "constructor_initializer":
csharp_method_scopes[id(part)] = (node, parent_class_nid)
function_bodies.append((ctor_nid, part))
keyword = next((c.type for c in part.children
if c.type in ("base", "this")), None)
if keyword is not None:
csharp_ctor_records.append({
"caller_nid": ctor_nid,
"lang": "csharp",
"csharp_ctor_init": keyword,
"arity": _csharp_creation_argc(part),
"source_file": str_path,
"source_location": f"L{part.start_point[0] + 1}",
})
ctor_body = node.child_by_field_name("body")
if ctor_body is not None:
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 == "field_declaration"
@@ -9193,6 +9285,12 @@ def _extract_generic(
continue
if n["id"] in _case_of_targets:
continue
# A C# constructor shares its type's name; it is reached through `new`
# or an initializer, never a bare call, and must not shadow the type.
if config.ts_module == "tree_sitter_c_sharp" and (
(n.get("metadata") or {}).get("kind") == "constructor"
):
continue
raw = n["label"]
normalised = raw.strip("()").lstrip(".")
if config.ts_module == "tree_sitter_lua":
@@ -10404,6 +10502,18 @@ def _extract_generic(
peers = csharp_overload_peers[tgt_nid]
picked = _csharp_pick_overload(peers, _csharp_argc(node))
tgt_nid = (picked or peers[0])["id"]
if (config.ts_module == "tree_sitter_c_sharp"
and node.type == "object_creation_expression" and callee_name):
# Which constructor runs is picked corpus-wide once the
# type is bound (_resolve_csharp_constructor_calls).
csharp_ctor_records.append({
"caller_nid": caller_nid,
"lang": "csharp",
"csharp_ctor_site": callee_name,
"arity": _csharp_creation_argc(node),
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
external_stub_target = bool(tgt_nid and not nid_to_sf.get(tgt_nid))
if tgt_nid and not external_stub_target:
pair = (caller_nid, tgt_nid)
@@ -11063,6 +11173,7 @@ def _extract_generic(
raw_calls.extend(_python_property_reads(
function_bodies, source, str_path, python_var_types, python_attr_types, method_owner,
))
raw_calls.extend(csharp_ctor_records)
result = {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
# Export the per-file field->type tables for the corpus member-call
# resolvers (#3151): a field declared on a superclass in ANOTHER file can
+3
View File
@@ -126,6 +126,9 @@ def resolve_interface_dispatch(
mnode = node_by_id.get(method_nid)
if mnode is None or not declared_in(mnode, suffixes):
continue
# A constructor shares its type's name but implements nothing.
if (mnode.get("metadata") or {}).get("kind") == "constructor":
continue
name = method_label(mnode)
if name:
# A set, so the same method arriving on two `method` edges cannot
+7 -3
View File
@@ -144,7 +144,9 @@ def test_element_access_without_element_type_gives_no_edge(tmp_path):
assert not {t for s, t in calls if s == save}
def test_constructor_calls_are_attributed_to_the_type(tmp_path):
def test_constructor_calls_are_attributed_to_the_constructor(tmp_path):
# A constructor is its own node, so its body's calls are its calls, not
# the type's (#4246 credited them to the type before constructors had nodes).
calls, r = _calls(tmp_path, {
"Bound.cs": (
"namespace Demo\n{\n"
@@ -159,7 +161,9 @@ def test_constructor_calls_are_attributed_to_the_type(tmp_path):
" }\n}\n"
),
})
assert (_find(r, "BoundFunc", "boundfunc"), _find(r, ".GameObjectOf()", "bound")) in calls
game_object_of = _find(r, ".GameObjectOf()", "bound")
assert (_find(r, ".BoundFunc()", "boundfunc"), game_object_of) in calls
assert (_find(r, "BoundFunc", "boundfunc"), game_object_of) not in calls
def test_constructor_typed_parameter_and_this_calls_resolve(tmp_path):
@@ -173,7 +177,7 @@ def test_constructor_typed_parameter_and_this_calls_resolve(tmp_path):
" }\n}\n"
),
})
holder = _find(r, "Holder", "holder")
holder = _find(r, ".Holder()", "holder")
assert (holder, _find(r, ".Apply()", "sequence")) in calls
assert (holder, _find(r, ".Apply()", "decoy")) not in calls
assert (holder, _find(r, ".Ping()", "basesvc")) in calls
+2 -1
View File
@@ -107,7 +107,8 @@ def test_extraction_keeps_the_bare_resolver_label(tmp_path):
_write(tmp_path, {"Report.cs": _ISSUE_REPRO})
raw = extract([tmp_path / "Report.cs"], root=tmp_path)
methods = sorted(n["label"] for n in raw["nodes"] if n["label"].endswith("()"))
assert methods == [".Build()", ".Build()", ".Build()", ".Run()"]
# `.Exporter()` is Exporter's constructor.
assert methods == [".Build()", ".Build()", ".Build()", ".Exporter()", ".Run()"]
def test_incremental_rebuild_binds_into_an_unchanged_file(tmp_path):
+147
View File
@@ -371,3 +371,150 @@ def test_qualified_construction_with_an_unknown_outer_type_gives_no_edge(tmp_pat
ensure = _find(r, ".Ensure()", "ensure")
slots = {n["id"] for n in r["nodes"] if n["label"] == "Slot"}
assert not any(t in slots for s, t in calls if s == ensure)
# Constructors are nodes: `new X(a, b)` and `: base(...)` / `: this(...)` reach
# the overload whose parameter count fits, next to the edge to the type.
def _ctor(r, type_name, signature):
ids = [n["id"] for n in r["nodes"]
if n["label"] == f".{type_name}()"
and (n.get("metadata") or {}).get("kind") == "constructor"
and (n.get("metadata") or {}).get("signature") == signature]
assert len(ids) == 1, (type_name, signature, ids)
return ids[0]
def test_construction_links_the_constructor_overload_its_arguments_fit(tmp_path):
calls, r = _extract(tmp_path, {
"Repo.cs": (
"public class Repo {\n"
" public Repo() { }\n"
" public Repo(int a) { }\n"
" public Repo(int a, int b) { }\n"
"}\n"
),
"User.cs": "public class User { public void Go() { var r = new Repo(1, 2); } }\n",
})
go = _find(r, ".Go()", "user")
assert (go, _find(r, "Repo", "repo")) in calls # the type edge stays
assert (go, _ctor(r, "Repo", "int,int")) in calls
assert (go, _ctor(r, "Repo", "int")) not in calls
assert (go, _ctor(r, "Repo", "")) not in calls
def test_construction_two_overloads_fit_gives_no_constructor_edge(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Repo { public Repo(int a) { } public Repo(string s) { } }\n"
"public class User { public void Go() { var r = new Repo(1); } }\n"
)})
go = _find(r, ".Go()", "user")
assert (go, _find(r, "Repo", "repo")) in calls
assert not {t for s, t in calls if s == go} & {
_ctor(r, "Repo", "int"), _ctor(r, "Repo", "string")
}
def test_constructor_body_and_initializer_calls_belong_to_the_constructor(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Base { public Base(int a) { } }\n"
"public class Svc : Base {\n"
" public Svc(int x) : base(Seed(x)) { Init(); }\n"
" static int Seed(int x) { return x; }\n"
" void Init() { }\n"
"}\n"
)})
ctor = _ctor(r, "Svc", "int")
svc = _find(r, "Svc", "svc")
for callee in (".Seed()", ".Init()"):
assert (ctor, _find(r, callee, "svc")) in calls
assert (svc, _find(r, callee, "svc")) not in calls
def test_this_initializer_links_the_own_overload(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Svc {\n"
" public Svc() : this(1, 2) { }\n"
" public Svc(int a) { }\n"
" public Svc(int a, int b) { }\n"
"}\n"
)})
assert (_ctor(r, "Svc", ""), _ctor(r, "Svc", "int,int")) in calls
assert (_ctor(r, "Svc", ""), _ctor(r, "Svc", "int")) not in calls
def test_base_initializer_links_the_base_constructor_in_another_file(tmp_path):
calls, r = _extract(tmp_path, {
"Base.cs": (
"namespace Demo {\n"
" public class Base { public Base(int a) { } public Base(string a, int b) { } }\n"
"}\n"
),
"Derived.cs": (
"namespace Demo {\n"
" public class Derived : Base { public Derived(int x) : base(\"s\", x) { } }\n"
"}\n"
),
})
derived = _ctor(r, "Derived", "int")
assert (derived, _ctor(r, "Base", "string,int")) in calls
assert (derived, _ctor(r, "Base", "int")) not in calls
def test_base_initializer_with_an_out_of_corpus_base_gives_no_edge(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Local { public Local(int a) { } }\n"
"public class Derived : System.Exception { public Derived(int x) : base(\"m\") { } }\n"
)})
derived = _ctor(r, "Derived", "int")
assert not {t for s, t in calls if s == derived}
def test_static_constructor_is_its_own_node_and_never_constructed(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public class Reg {\n"
" static Reg() { Load(); }\n"
" public Reg() { }\n"
" static void Load() { }\n"
"}\n"
"public class User { public void Go() { var r = new Reg(); } }\n"
)})
static_ctor, instance_ctor = _ctor(r, "Reg", "static"), _ctor(r, "Reg", "")
assert static_ctor != instance_ctor
assert (static_ctor, _find(r, ".Load()", "reg")) in calls
go = _find(r, ".Go()", "user")
assert (go, instance_ctor) in calls
assert (go, static_ctor) not in calls
def test_primary_constructor_competes_with_the_explicit_ones(tmp_path):
calls, r = _extract(tmp_path, {"S.cs": (
"public record Point(int X, int Y) { public Point(int x) : this(x, 0) { } }\n"
"public class User { public void Go() { var a = new Point(1, 2); var b = new Point(3); } }\n"
)})
primary, explicit = _ctor(r, "Point", "int,int"), _ctor(r, "Point", "int")
go = _find(r, ".Go()", "user")
assert {(go, primary), (go, explicit), (explicit, primary)} <= calls
def test_constructor_in_an_unchanged_file_resolves_on_an_incremental_rebuild(tmp_path):
import json
from graphify.watch import _rebuild_code
files = {
"Repo.cs": "public class Repo { public Repo() { } public Repo(int a, int b) { } }\n",
"User.cs": "public class User { public void Go() { var r = new Repo(1, 2); } }\n",
}
for name, body in files.items():
(tmp_path / name).write_text(body)
assert _rebuild_code(tmp_path, no_cluster=True, acquire_lock=False, force=True)
user = tmp_path / "User.cs"
user.write_text(user.read_text() + "// touched\n")
assert _rebuild_code(tmp_path, changed_paths=[user], no_cluster=True, acquire_lock=False)
graph = json.loads((tmp_path / "graphify-out" / "graph.json").read_text())
ctor = next(n["id"] for n in graph["nodes"]
if (n.get("metadata") or {}).get("signature") == "int,int")
go = next(n["id"] for n in graph["nodes"] if n["label"].endswith("Go()"))
assert any(l["source"] == go and l["target"] == ctor and l["relation"] == "calls"
for l in graph["links"])
@@ -284,3 +284,20 @@ def test_base_call_reaches_the_underscore_method(tmp_path):
sub, base = sorted(_ids(r, "._Action()"), key=lambda nid: "subwidget" not in nid)
assert (sub, base) in _edges(r, "calls")
assert (sub, _one(r, ".Action()")) not in _edges(r, "calls")
def test_constructor_never_takes_the_id_of_a_member_spelled_like_its_type(tmp_path):
# `Foo()` (the constructor) and `foo()` normalize to one id. The method
# had it before constructors were nodes and keeps it, wherever the
# constructor is declared; the constructor gets a salted id.
for body in (
"public class Foo { public Foo() { Bar(); } public void foo() { } public void Bar() { } }\n",
"public class Foo { public void foo() { } public Foo() { Bar(); } public void Bar() { } }\n",
):
r = _extract(tmp_path, {"Foo.cs": body})
method = _one(r, "Foo") + "_foo"
assert _one(r, ".foo()") == method
ctor = _one(r, ".Foo()")
assert ctor != method
assert (ctor, _one(r, ".Bar()")) in _edges(r, "calls")
assert (method, _one(r, ".Bar()")) not in _edges(r, "calls")