feat(csharp): bind extension calls on typed receivers (#4828)

`value.Mask()` to a classic `this`-parameter extension produced no `calls`
edge: `_resolve_csharp_member_calls` types the receiver and looks the method up
on the receiver's type, but an extension is declared on a static class, so the
lookup found nothing and the call was dropped. The helper looked dead.

New `csharp_extension_calls` resolver, registered after the nominal pass, joins
a call site to the declaration its `this` parameter names. This first stage
binds only provable calls:

  * the receiver's declared type is declared in the corpus and its base chain is
    fully resolved — an out-of-corpus base may declare an instance member of
    that name, and an instance member always wins over an extension;
  * the receiver type declares no instance member of that name;
  * the declaring static class's namespace is visible at the call site, walked
    innermost namespace declaration outward (`CsharpNameResolver
    .visible_namespaces`), so a file-level using is only considered at the
    compilation-unit level and an inner-namespace extension wins;
  * the extended type is the receiver's type, a resolved base, or an implemented
    interface; an open generic `this T` / `this object` declaration applies only
    when no exact or base match exists;
  * the declaration accepts the call's argument count, reusing the arity /
    min_arity facts from #4584 (the receiver is one parameter short of the call);
  * exactly one declaration survives; a tie binds nothing.

Edges are INFERRED 0.85 (the receiver type comes from the extractor's declaration
table), sourced at the call site.

The tests pair the implementation with an executable A/B record: 15 fixtures
whose ground truth is decidable from the C# spec, and 10 candidate strategies
measured on the nominal graph (production resolver disabled for extraction). The
matrix test pins the trades that were measured rather than assumed — no scope
check binds an unimported extension, no poison binds through an unknown base, no
deny-list binds `PropertyInfo.GetValue`, and the bare-name fallback reproduces
the #1609 god-node edge. The production pass is asserted against the same ground
truth in test_csharp_extension_resolution.py.

Refs #4828

(cherry picked from commit a83cc6c0e3)
This commit is contained in:
Deepjyoti-Sarmah authored and safishamsi committed 2026-11-09 16:46:28 +00:00
1 parent 5bfb4241d8
commit 637e9c6d8e
5 files changed
+1670

No files matched your search

+246
View File
@@ -6842,6 +6842,246 @@ def _resolve_csharp_member_calls(
})
def _resolve_csharp_extension_calls(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Bind C# extension-method calls (``recv.Ext()``) to their declaration (#4828).
An extension invocation is static dispatch: the receiver is the first
argument of a method declared on a *static class*, not a member of the
receiver's type. ``_resolve_csharp_member_calls`` therefore cannot see it —
it looks the name up on the receiver's type and its base chain, and an
extension lives on a sibling type — so a widely used helper had no callers
in the graph and looked dead.
The declaration side now records ``extended_type`` (plus arity and a
type-parameter marker) on the extension node; this pass joins call sites to
it. Every rule is a C# resolution rule, and anything unprovable is dropped:
* the receiver's declared type must be in the corpus and its base chain
fully resolved — an out-of-corpus base may declare an *instance* member
of that name, which always wins over an extension;
* the receiver type must declare no instance member of that name;
* the declaring static class's namespace must be visible at the call site,
walking the enclosing namespace declarations outward (a file-level
``using`` belongs to the compilation unit, so an inner-namespace
extension wins);
* the extended type must be the receiver's type or one of its resolved
base types or interfaces;
* the declaration must accept the call's argument count, using the same
``arity``/``min_arity`` facts #4584 already records (the receiver is one
parameter short of the call);
* more than one surviving declaration is ambiguous and binds nothing.
An open generic (``this T``) or ``this object`` declaration applies to any
receiver, but only when no exact/base match exists — C# prefers the
non-generic candidate.
"""
def _key(label: str) -> str:
# Case and `_` are part of a C# name (#4415); drop only the `.M()` decoration.
return re.sub(r"\W+", "", str(label))
node_by_id: dict[str, dict] = {n.get("id"): n for n in all_nodes}
contained = {e.get("target") for e in all_edges if e.get("relation") == "contains"}
type_def_nids: dict[str, list[str]] = {}
for nid in contained:
n = node_by_id.get(nid)
if (
n is not None
and _is_cs_file(n.get("source_file"))
and _is_type_like_definition(n)
):
type_def_nids.setdefault(_key(n.get("label", "")), []).append(nid)
resolver = CsharpNameResolver(all_nodes, all_edges)
# Extension declarations, by the name a call site spells.
ext_by_name: dict[str, list[dict]] = {}
method_owner: dict[str, str] = {}
method_index: dict[tuple[str, str], list[str]] = {}
for e in all_edges:
if e.get("relation") != "method":
continue
owner, method_nid = e.get("source"), e.get("target")
mnode = node_by_id.get(method_nid)
if mnode is None or not _is_cs_file(mnode.get("source_file")):
continue
method_owner.setdefault(method_nid, owner)
method_index.setdefault((owner, _key(mnode.get("label", ""))), []).append(method_nid)
meta = mnode.get("metadata") or {}
arity = meta.get("arity")
if not meta.get("extension") or not isinstance(arity, int):
continue
low = meta.get("min_arity")
ext_by_name.setdefault(_key(mnode.get("label", "")), []).append({
"method": method_nid,
"extended": str(meta.get("extended_type") or ""),
"ext_arity": meta.get("extended_type_arity") or 0,
"is_type_param": bool(meta.get("extended_is_type_param")),
"arity": arity,
"low": low if isinstance(low, int) else arity,
"variadic": bool(meta.get("variadic")),
"namespace": str(meta.get("namespace") or ""),
})
if not ext_by_name:
return
# Supertype graph. A target with no source_file is a placeholder for a type
# the corpus never declares: the chain through it is UNRESOLVED.
supers: dict[str, set[str]] = {}
for e in all_edges:
if e.get("relation") not in ("inherits", "implements"):
continue
if not _is_cs_file(e.get("source_file")):
continue
src, tgt = e.get("source"), e.get("target")
if isinstance(src, str) and isinstance(tgt, str):
supers.setdefault(src, set()).add(tgt)
closure_cache: dict[str, tuple[set[str], bool]] = {}
def _closure(nid: str) -> tuple[set[str], bool]:
cached = closure_cache.get(nid)
if cached is not None:
return cached
out: set[str] = set()
unresolved = False
stack = [nid]
while stack:
cur = stack.pop()
if cur in out:
continue
out.add(cur)
for sup in supers.get(cur, ()):
snode = node_by_id.get(sup)
if snode is None or not snode.get("source_file"):
unresolved = True
continue
stack.append(sup)
closure_cache[nid] = (out, unresolved)
return out, unresolved
def _resolve_type_nid(type_name: str | None, caller_node: dict | None,
src_file: str) -> str | None:
if not type_name:
return None
if caller_node is not None:
resolved, decisive = resolver.resolve_type_name(
type_name, caller_node, src_file
)
if resolved:
return resolved
if decisive:
return None
hits = type_def_nids.get(_key(type_name), [])
return hits[0] if len(hits) == 1 else None
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
for result in per_file:
for rc in result.get("raw_calls") or []:
if rc.get("lang") != "csharp" or not rc.get("is_member_call"):
continue
caller = rc.get("caller_nid")
callee = rc.get("callee")
argc = rc.get("arity")
receiver = rc.get("receiver")
chain = rc.get("receiver_chain") or []
if not caller or not callee or not isinstance(argc, int):
continue
if receiver == "base":
continue # base.M() is nominal dispatch, never an extension
src_file = str(rc.get("source_file") or "")
caller_node = node_by_id.get(caller)
if caller_node is None:
continue
recv_name = rc.get("receiver_type")
if not recv_name and chain:
if len(chain) > 1:
# `x.F.M()` needs F's declared type, not x's: fail closed
# rather than bind the extension to the root's type.
continue
recv_name = chain[0]
if not recv_name and receiver == "this":
owner = method_owner.get(caller)
owner_node = node_by_id.get(owner) if owner else None
recv_name = (owner_node or {}).get("label")
if not recv_name:
continue
recv_nid = _resolve_type_nid(recv_name, caller_node, src_file)
if recv_nid is None:
continue
closure, unresolved = _closure(recv_nid)
if unresolved:
# An out-of-corpus base may declare this name as an instance
# member, which beats any extension. Not provable: no edge.
continue
if any(method_index.get((owner, _key(callee))) for owner in closure):
continue # an instance member (or an override) wins
candidates = ext_by_name.get(_key(callee))
if not candidates:
continue
for visible in resolver.visible_namespaces(caller_node, src_file):
at_level = [d for d in candidates if d["namespace"] in visible]
if at_level:
candidates = at_level
break
else:
continue
exact = [
d for d in candidates
if not d["is_type_param"] and _key(d["extended"]) == _key(recv_name)
]
inherited = [
d for d in candidates
if not d["is_type_param"]
and _key(d["extended"]) in {
_key((node_by_id.get(c) or {}).get("label", "")) for c in closure
}
]
applicable = exact or inherited
if not applicable:
applicable = [
d for d in candidates
if d["is_type_param"] or d["extended"].lower() in ("object", "dynamic")
]
if not applicable:
continue
fits = [
d for d in applicable
if d["low"] <= argc and (argc <= d["arity"] - 1 or d["variadic"])
]
if len(fits) != 1:
continue # no declaration accepts this call shape, or ambiguous
method_nid = fits[0]["method"]
if method_nid == caller or (caller, method_nid) in existing_pairs:
continue
existing_pairs.add((caller, method_nid))
all_edges.append({
"source": caller,
"target": method_nid,
"relation": "calls",
"context": "call",
"confidence": "INFERRED",
# Receiver typed from the extractor's declaration table, so the
# discrete INFERRED rung (0.85) rather than a source-named type.
"confidence_score": 0.85,
"source_file": src_file,
"source_location": rc.get("source_location"),
"weight": 1.0,
})
def _bind_member_field_tables(
per_file: list[dict],
all_nodes: list[dict],
@@ -8879,6 +9119,12 @@ register_language_resolver(
register_language_resolver(
LanguageResolver("csharp_member_calls", frozenset({".cs"}), _resolve_csharp_member_calls)
)
# C# extension-method calls (#4828): `recv.Ext()` where Ext is a `this`-parameter
# method on a static class. Runs after the nominal pass so an instance member has
# already won, and adds only the calls that pass could not bind.
register_language_resolver(
LanguageResolver("csharp_extension_calls", frozenset({".cs"}), _resolve_csharp_extension_calls)
)
register_language_resolver(
LanguageResolver("java_member_calls", frozenset({".java"}), _resolve_java_member_calls)
)
+28
View File
@@ -422,6 +422,34 @@ class CsharpNameResolver:
_append_unique(scopes, namespace)
return scopes
def visible_namespaces(self, source_node: dict, source_file: str) -> list[set[str]]:
"""Namespaces visible to extension-method lookup, innermost level first.
C# 12.8.10.3: for each enclosing namespace declaration — innermost first,
ending with the compilation unit — consider that namespace and the
``using namespace`` directives declared at that level. A file-level
using belongs to the compilation unit, so it is only considered at the
outermost level; that is why an extension declared in an inner namespace
wins over one imported at the top of the file (#4828).
A namespace-scoped using is treated as visible at every level inside it.
That is coarser than the spec but only ever adds candidates at a deeper
level than the directive's own, and the caller drops ties.
"""
chain = [part for part in self._namespace(source_node).split(".") if part]
usings = self.namespace_usings_by_file.get(source_file, [])
levels: list[set[str]] = []
for i in range(len(chain), -1, -1):
visible = {".".join(chain[:i])}
for target_fqn, scope_kind, scope_id in usings:
if scope_kind == "file":
if i == 0:
visible.add(target_fqn)
elif self._using_in_scope(scope_kind, scope_id, source_node):
visible.add(target_fqn)
levels.append(visible)
return levels
def _resolve_alias(self, label: str, source_node: dict, source_file: str) -> str | None:
hits = set()
for target_fqn, scope_kind, scope_id in self.aliases_by_file.get(source_file, {}).get(label, []):
File diff suppressed because it is too large. Load diff
+295
View File
@@ -0,0 +1,295 @@
"""Decision record: A/B comparison of candidate C# extension binders (#4828).
The production pass is chosen by measuring candidates against fixtures whose
ground truth is decidable from the C# spec. This module keeps the comparison
executable: it is what tells a future change that removing the scope check, the
unresolved-base poison, or the deny-list costs a false edge.
Candidates are applied to the graph as the *nominal* pipeline builds it
(``production_extension=False`` in the harness), so the numbers stay comparable
no matter which stage of the production fix has landed. The production behaviour
itself is covered by ``test_csharp_extension_resolution.py``.
Fixtures: ``expect`` must bind, ``forbid``/``forbid_pairs`` must not, ``optional``
is unknowable without a BCL symbol table and is never scored.
"""
from __future__ import annotations
import pytest
from tests.csharp_extension_harness import (
FIXTURES,
STRATEGY_IDS,
STRATEGIES,
expected_pairs,
line_of,
strategy_bindings,
)
FIXTURE_IDS = list(FIXTURES)
# Strategies that claim "no false edge anywhere". The others are deliberately
# imprecise (that is the property being measured) and are scored by the matrix.
PRECISE_STRATEGIES = [
"S3_typed_assignable",
"S5_roc_guarded",
"S7_all_rungs",
"S9_signature_parse",
]
# Per strategy, the fixtures it must get fully right. Everything else may
# under-bind (scored by the matrix) but may still not over-bind.
STRATEGY_RECALL: dict[str, set[str]] = {
"S1_typed_exact": {"domain_cross_file", "same_file", "arity", "type_param_vs_class"},
"S2_typed_exact_scope": {"domain_cross_file", "same_file", "arity", "type_param_vs_class"},
"S3_typed_assignable": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
},
"S4_roc_naive": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard",
},
"S5_roc_guarded": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard",
},
"S6_reporter_patch": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"instance_wins", "primitive_and_thirdparty", "generic_wildcard",
"issue_repro",
},
"S7_all_rungs": {
"domain_cross_file", "same_file", "arity", "type_param_vs_class",
"base_and_interface", "inner_scope_wins", "instance_wins",
"primitive_and_thirdparty", "generic_wildcard", "issue_repro",
},
"S9_signature_parse": {
"domain_cross_file", "same_file", "arity", "base_and_interface",
"inner_scope_wins", "instance_wins",
},
}
# --------------------------------------------------------------------------- #
# fixture sanity
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_fixture_markers_are_unambiguous(name):
fixture = FIXTURES[name]
bodies = "\n".join(fixture.files.values())
import re as _re
markers = _re.findall(r"//\s*[A-Z]\d+", bodies)
for marker in set(markers):
assert markers.count(marker) == 1, (name, marker, markers.count(marker))
def source_of(marker):
hits = [b for b in fixture.files.values() if marker in b]
assert len(hits) == 1, (name, marker, len(hits))
return hits[0]
for call_marker, (t_file, t_marker) in fixture.expect.items():
assert line_of(source_of(call_marker), call_marker)
assert line_of(fixture.files[t_file], t_marker)
assert call_marker not in fixture.forbid, (name, call_marker)
for call_marker in fixture.forbid:
assert line_of(source_of(call_marker), call_marker)
for call_marker, (t_file, t_marker) in fixture.forbid_pairs.items():
assert line_of(source_of(call_marker), call_marker)
assert line_of(fixture.files[t_file], t_marker)
assert fixture.expect.get(call_marker) != (t_file, t_marker)
for call_marker in fixture.optional:
assert line_of(source_of(call_marker), call_marker)
# --------------------------------------------------------------------------- #
# per-candidate sweep
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("strategy_id", PRECISE_STRATEGIES)
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_precise_strategy_emits_no_forbidden_edge(name, strategy_id):
result = strategy_bindings(name, strategy_id)
assert result["violations"] == set(), f"{strategy_id} on {name}"
@pytest.mark.parametrize("strategy_id", STRATEGY_IDS)
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_strategy_to_upholds_the_ground_truth(name, strategy_id):
if strategy_id == "S0_baseline":
assert strategy_bindings(name, strategy_id)["added"] == []
return
required = STRATEGY_RECALL.get(strategy_id, set())
if name not in required:
pytest.skip("under-binding is scored by the matrix test")
result = strategy_bindings(name, strategy_id)
assert expected_pairs(name) <= result["bindings"], (
f"{strategy_id} on {name}: missing "
f"{sorted(expected_pairs(name) - result['bindings'])}"
)
# --------------------------------------------------------------------------- #
# the matrix
# --------------------------------------------------------------------------- #
def _score(strategy_id: str) -> dict:
expected_total = 0
correct = 0
wrong: list = []
for name in FIXTURE_IDS:
fixture = FIXTURES[name]
expected = expected_pairs(name)
expected_total += len(expected)
result = strategy_bindings(name, strategy_id)
correct += len(expected & result["bindings"])
for binding in result["bindings"] - expected:
if binding[0] in fixture.optional:
continue
wrong.append((name, *binding))
for edge in result["phantoms"]:
wrong.append((name, "phantom", str(edge.get("target"))))
return {
"expected": expected_total,
"correct": correct,
"wrong": wrong,
"recall": correct / expected_total if expected_total else 0.0,
"precision": correct / (correct + len(wrong)) if (correct + len(wrong)) else 1.0,
}
def test_strategy_matrix(capsys):
scores = {sid: _score(sid) for sid in STRATEGY_IDS}
lines = [
f"{'strategy':26} {'hits':>5} {'expected':>9} {'wrong':>6} "
f"{'recall':>7} {'precision':>10}"
]
for sid in STRATEGY_IDS:
s = scores[sid]
lines.append(
f"{sid:26} {s['correct']:5d} {s['expected']:9d} {len(s['wrong']):6d} "
f"{s['recall']:7.3f} {s['precision']:10.3f}"
)
with capsys.disabled():
print("\n" + "\n".join(lines))
# Baseline proves the fixtures are not already passing: it can satisfy only
# the ordinary static/instance calls, never an extension call.
assert scores["S0_baseline"]["wrong"] == []
assert scores["S0_baseline"]["correct"] < scores["S3_typed_assignable"]["correct"]
# Each added rung is weakly better on recall.
assert scores["S2_typed_exact_scope"]["recall"] >= scores["S1_typed_exact"]["recall"]
assert scores["S3_typed_assignable"]["recall"] >= scores["S2_typed_exact_scope"]["recall"]
assert scores["S5_roc_guarded"]["recall"] >= scores["S3_typed_assignable"]["recall"]
assert scores["S7_all_rungs"]["recall"] >= scores["S5_roc_guarded"]["recall"]
# The provable-only rung has no false edge anywhere in the corpus.
for sid in PRECISE_STRATEGIES:
assert scores[sid]["wrong"] == [], sid
# Relaxing a rule costs precision: each of these is a documented trade.
assert scores["S1_typed_exact"]["wrong"], "no-scope must bind an unimported extension"
assert scores["S2_typed_exact_scope"]["wrong"], "no-poison must bind through an unknown base"
assert scores["S4_roc_naive"]["wrong"], "no-deny-list must bind a BCL instance member"
assert scores["S6_reporter_patch"]["wrong"], "reporter patch must bind out of scope / through a base"
assert scores["S4_roc_naive"]["recall"] > scores["S5_roc_guarded"]["recall"]
assert scores["S5_roc_guarded"]["recall"] > scores["S3_typed_assignable"]["recall"]
# --------------------------------------------------------------------------- #
# explicit discriminators: each proves the flag it names is what changed
# --------------------------------------------------------------------------- #
def _has(name: str, strategy_id: str, call_marker: str, target: tuple[str, str]) -> bool:
return (call_marker, target) in strategy_bindings(name, strategy_id)["bindings"]
def test_scope_flag_is_what_excludes_an_unimported_extension():
target = ("Other.cs", "// D1")
assert _has("out_of_scope", "S1_typed_exact", "// E1", target)
for sid in ("S2_typed_exact_scope", "S3_typed_assignable",
"S5_roc_guarded", "S7_all_rungs"):
assert not _has("out_of_scope", sid, "// E1", target), sid
def test_scope_level_is_what_picks_the_inner_extension():
inner = ("Inner.cs", "// D2")
outer = ("Outer.cs", "// D1")
assert not _has("inner_scope_wins", "S1_typed_exact", "// E1", inner)
assert _has("inner_scope_wins", "S3_typed_assignable", "// E1", inner)
assert not _has("inner_scope_wins", "S3_typed_assignable", "// E1", outer)
def test_assignability_is_what_reaches_base_and_interface_extensions():
base = ("Domain.cs", "// D1")
iface = ("Domain.cs", "// D2")
assert not _has("base_and_interface", "S2_typed_exact_scope", "// E1", base)
assert not _has("base_and_interface", "S2_typed_exact_scope", "// E2", iface)
assert _has("base_and_interface", "S3_typed_assignable", "// E1", base)
assert _has("base_and_interface", "S3_typed_assignable", "// E2", iface)
def test_poison_flag_is_what_refuses_an_unknown_base():
target = ("W.cs", "// D1")
assert _has("unresolved_base_poison", "S2_typed_exact_scope", "// E1", target)
assert not _has("unresolved_base_poison", "S3_typed_assignable", "// E1", target)
def test_out_of_corpus_rung_is_what_reaches_string_and_thirdparty():
targets = {
"// E1": ("Ext.cs", "// D1"),
"// E2": ("Ext.cs", "// D2"),
"// E3": ("Ext.cs", "// D3"),
}
for marker, target in targets.items():
assert not _has("primitive_and_thirdparty", "S3_typed_assignable", marker, target), marker
assert _has("primitive_and_thirdparty", "S5_roc_guarded", marker, target), marker
def test_deny_list_is_what_prevents_a_bcl_false_positive():
"""`PropertyInfo.GetValue(obj)`: the 2-arg extension fits the arity, so only
the deny-list stands between the naive rung and a false edge."""
target = ("E.cs", "// D2")
assert _has("bcl_name_cost", "S4_roc_naive", "// E1", target)
assert not _has("bcl_name_cost", "S5_roc_guarded", "// E1", target)
def test_untyped_rung_is_what_reaches_a_chained_receiver():
target = ("Ext.cs", "// D1")
assert not _has("issue_repro", "S5_roc_guarded", "// E2", target)
assert _has("issue_repro", "S7_all_rungs", "// E2", target)
# ... while the typed (primitive) receiver needs no untyped rung at all.
assert _has("issue_repro", "S5_roc_guarded", "// E1", target)
def test_metadata_beats_signature_parsing_on_this_T():
"""Both `this T` declarations look identical in the signature text."""
concrete = ("T.cs", "// D1")
assert _has("type_param_vs_class", "S3_typed_assignable", "// E1", concrete)
assert not _has("type_param_vs_class", "S9_signature_parse", "// E1", concrete)
# The generic `this T` is the wildcard rung, reachable only with the
# `extended_is_type_param` fact that the signature text cannot carry.
wildcard = ("Gen.cs", "// D1")
assert _has("generic_wildcard", "S5_roc_guarded", "// E1", wildcard)
assert not _has("generic_wildcard", "S9_signature_parse", "// E1", wildcard)
def test_control_bare_name_reintroduces_the_god_node_edge():
"""The anti-pattern is real on this corpus, which is why it is rejected."""
control = strategy_bindings("god_node_control", "S8_bare_name_control")
assert ("// F1", ("Cache.cs", "// D1")) in control["bindings"]
for sid in STRATEGY_IDS:
if sid == "S8_bare_name_control":
continue
assert not _has("god_node_control", sid, "// F1", ("Cache.cs", "// D1")), sid
+98
View File
@@ -0,0 +1,98 @@
"""Production behaviour for C# extension-call binding (#4828).
Ground truth lives in ``tests/csharp_extension_harness.py``: ``expect`` edges must
exist in the real pipeline output, ``forbid`` edges must not. ``STAGE_FIXTURES``
names the fixtures the pass is required to satisfy *at this stage* of the fix;
the forbidden-edge tests run against every fixture from the first stage, so a
later stage can only add recall, never a false edge.
"""
from __future__ import annotations
import pytest
from tests.csharp_extension_harness import (
FIXTURES,
expected_pairs,
graph_bindings,
)
FIXTURE_IDS = list(FIXTURES)
# Stage 1: in-corpus receivers, scope, assignability, poison, arity.
# Stage 2 adds: primitive_and_thirdparty, generic_wildcard, bcl_name_cost,
# static_class_receiver.
# Stage 3 adds: issue_repro.
STAGE_FIXTURES = {
"domain_cross_file",
"same_file",
"arity",
"type_param_vs_class",
"base_and_interface",
"inner_scope_wins",
"instance_wins",
}
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_production_never_emits_a_forbidden_edge(name):
result = graph_bindings(name)
assert result["violations"] == set(), sorted(result["violations"])
@pytest.mark.parametrize("name", FIXTURE_IDS)
def test_production_invents_no_call_site(name):
assert graph_bindings(name)["phantoms"] == []
@pytest.mark.parametrize("name", sorted(STAGE_FIXTURES))
def test_production_binds_the_decidable_extension_calls(name):
result = graph_bindings(name)
missing = expected_pairs(name) - result["bindings"]
assert not missing, f"{name}: missing {sorted(missing)}"
def test_extension_edge_is_inferred_at_the_call_site():
from tests.csharp_extension_harness import corpus
data = corpus("domain_cross_file")
by_id = {n["id"]: n for n in data["nodes"]}
paint_calls = [
e for e in data["edges"]
if e.get("relation") == "calls"
and by_id.get(e.get("target"), {}).get("label") == ".Paint()"
]
assert len(paint_calls) == 2
assert {e["source_location"] for e in paint_calls} == {"L5", "L6"}
for edge in paint_calls:
assert edge["confidence"] == "INFERRED"
assert edge["confidence_score"] == 0.85
assert edge["context"] == "call"
def test_instance_member_wins_over_a_same_named_extension():
"""`Cache.GetValue()` is nominal; the extension of the same name must not win."""
result = graph_bindings("instance_wins")
assert ("// E1", ("Cache.cs", "// D1")) in result["bindings"]
assert ("// E1", ("Cache.cs", "// D2")) not in result["bindings"]
def test_static_form_is_never_rebound_to_the_extension():
"""`Conv.ToInt32(x)` names its type in source and is bound by the nominal pass."""
result = graph_bindings("static_class_receiver")
assert ("// B1", ("E.cs", "// D1")) in result["bindings"]
assert ("// B1", ("E.cs", "// D2")) not in result["bindings"]
def test_ambiguity_binds_nothing():
result = graph_bindings("ambiguous_same_scope")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_out_of_scope_extension_binds_nothing():
result = graph_bindings("out_of_scope")
assert not any(marker == "// E1" for marker, _target in result["bindings"])
def test_unresolved_base_poisons_the_lookup():
result = graph_bindings("unresolved_base_poison")
assert not any(marker == "// E1" for marker, _target in result["bindings"])