Merge pull request #4889 from SyedFahad7/cursor/csharp-method-owner-labels-5c23
fix(csharp): label C# methods with their owning type (#4883)
This commit is contained in:
7 files changed
+434
-5
No files matched your search
+5
-1
@@ -82,9 +82,13 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
from graphify.build import _is_file_node_label
|
||||
if _is_file_node_label(label, source_file):
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
# Method stub: AST extractor labels methods as '.method_name()'; C# methods
|
||||
# carry their owner for display ('Owner.method_name()', #4883).
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
if bare_csharp_method_label(label, source_file) is not None:
|
||||
return True
|
||||
# Module-level function stub: labeled 'function_name()' - only has a contains edge
|
||||
# These are real functions but structurally isolated by definition; not a gap worth flagging
|
||||
if label.endswith("()") and G.degree(node_id) <= 1:
|
||||
|
||||
+45
-4
@@ -875,6 +875,39 @@ def disambiguate_file_labels_in_nodes(nodes: "list") -> None:
|
||||
nodes[i]["label"] = new_label
|
||||
|
||||
|
||||
def _qualify_csharp_method_labels(G: "nx.Graph") -> None:
|
||||
"""Give C# method nodes an ``Owner.Name()`` display label (#4883). Ids and
|
||||
edges are never changed, and an undirected graph's owner side is read from
|
||||
the edge's recorded ``_src``/``_tgt``. Idempotent."""
|
||||
from graphify.extractors.csharp import csharp_method_label_reassignments
|
||||
method_edges = [
|
||||
(data.get("_src", u), data.get("_tgt", v))
|
||||
for u, v, data in G.edges(data=True)
|
||||
if data.get("relation") == "method"
|
||||
]
|
||||
for nid, new_label in csharp_method_label_reassignments(
|
||||
G.nodes(data=True), method_edges
|
||||
).items():
|
||||
G.nodes[nid]["label"] = new_label
|
||||
|
||||
|
||||
def qualify_csharp_method_labels_in_nodes(nodes: "list", edges: "list") -> None:
|
||||
"""Raw node/edge-list form of :func:`_qualify_csharp_method_labels`, in
|
||||
place, for the --no-cluster writers that bypass build_from_json (#4883)."""
|
||||
from graphify.extractors.csharp import csharp_method_label_reassignments
|
||||
method_edges = [
|
||||
(e.get("source"), e.get("target"))
|
||||
for e in edges
|
||||
if isinstance(e, dict) and e.get("relation") == "method"
|
||||
]
|
||||
reassigned = csharp_method_label_reassignments(
|
||||
((n.get("id"), n) for n in nodes if isinstance(n, dict)), method_edges
|
||||
)
|
||||
for n in nodes:
|
||||
if isinstance(n, dict) and n.get("id") in reassigned:
|
||||
n["label"] = reassigned[n["id"]]
|
||||
|
||||
|
||||
def _infer_merge_root(graph_path: Path) -> str | None:
|
||||
"""Best-effort scan root for relativizing paths in build_merge when the caller
|
||||
passes no ``root`` (#1571).
|
||||
@@ -1136,6 +1169,7 @@ def _alias_index(nodes: "Iterable[tuple[str, dict]]") -> dict[str, str]:
|
||||
endpoint the same way (#4670).
|
||||
"""
|
||||
from graphify.extractors.base import _file_stem as _fs
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
|
||||
|
||||
alias_candidates: dict[str, set[str]] = {}
|
||||
@@ -1169,8 +1203,10 @@ def _alias_index(nodes: "Iterable[tuple[str, dict]]") -> dict[str, str]:
|
||||
alias = old_stem + suffix
|
||||
alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
|
||||
alias_candidates.setdefault(alias, set()).add(nid)
|
||||
if attrs.get("_origin") == "ast" and str(attrs.get("label", "")).startswith("."):
|
||||
m_name = make_id(str(attrs.get("label", "")).strip().removeprefix(".").removesuffix("()"))
|
||||
m_label = str(attrs.get("label", ""))
|
||||
m_label = bare_csharp_method_label(m_label.strip(), sf) or m_label
|
||||
if attrs.get("_origin") == "ast" and m_label.startswith("."):
|
||||
m_name = make_id(m_label.strip().removeprefix(".").removesuffix("()"))
|
||||
m_alias = f"{new_stem}_{m_name}"
|
||||
if _normalize_id(nid) != _normalize_id(m_alias):
|
||||
alias_candidates.setdefault(_normalize_id(m_alias), set()).add(nid)
|
||||
@@ -1575,6 +1611,7 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
_noloc_nodes: dict[tuple[str, str], str] = {} # (source_file, label) -> ghost node id
|
||||
_ast_file_nodes: list[tuple[str, str]] = [] # (node_id, source_file) for AST file-self nodes (#3344)
|
||||
_ast_method_nodes: dict[tuple[str, str], list[str]] = {} # (source_file, norm_method) -> [ast_nid, ...]
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
|
||||
# Pass 1: collect canonical nodes — AST-origin nodes take precedence over LLM nodes.
|
||||
# When 2+ AST nodes share a key (same-named symbols in same-named files across
|
||||
@@ -1636,8 +1673,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# a dotfile label like `.env` is never mistaken for a method
|
||||
# (#3705 follow-up). Key on the normalized name for parity with
|
||||
# the alias index below and the rest of the dedup passes.
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
m_name = make_id(label.removeprefix(".").removesuffix("()"))
|
||||
m_label = bare_csharp_method_label(label, sf) or label
|
||||
if m_label.startswith(".") and m_label.endswith("()"):
|
||||
m_name = make_id(m_label.removeprefix(".").removesuffix("()"))
|
||||
_ast_method_nodes.setdefault((sf, m_name), []).append(nid)
|
||||
else:
|
||||
# First non-AST node for this (file, label) wins as canonical; a
|
||||
@@ -2060,6 +2098,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# directory-qualified display label so lookup/discovery can disambiguate
|
||||
# them (#2032). Labels only — ids and edges are untouched.
|
||||
_disambiguate_file_node_labels(G)
|
||||
# Also last, after the method-ghost passes above: C# methods display with
|
||||
# their owning type (#4883).
|
||||
_qualify_csharp_method_labels(G)
|
||||
return G
|
||||
|
||||
|
||||
|
||||
@@ -4947,6 +4947,8 @@ def dispatch_command(cmd: str) -> None:
|
||||
# gets this), so apply it directly on the merged node list.
|
||||
from graphify.build import disambiguate_file_labels_in_nodes as _disamb_labels
|
||||
_disamb_labels(merged["nodes"])
|
||||
from graphify.build import qualify_csharp_method_labels_in_nodes as _qualify_cs_methods
|
||||
_qualify_cs_methods(merged["nodes"], merged["edges"])
|
||||
# Same endpoint rules as build_from_json (#2873): an import of an
|
||||
# external module gets a typed stub node, and any other edge without
|
||||
# two declared endpoints is dropped instead of shipping a phantom.
|
||||
|
||||
@@ -59,6 +59,7 @@ from graphify.extractors.csharp import (
|
||||
_is_dotnet_source_file,
|
||||
_resolve_cross_file_csharp_imports,
|
||||
_resolve_csharp_type_references,
|
||||
bare_csharp_method_labels_in_nodes,
|
||||
)
|
||||
from graphify.extractors.dart import extract_dart # noqa: F401
|
||||
from graphify.extractors.dm import extract_dm, extract_dmf, extract_dmi, extract_dmm # noqa: F401
|
||||
@@ -9536,6 +9537,10 @@ def extract(
|
||||
fresh results are appended to the returned nodes/edges.
|
||||
"""
|
||||
paths = [Path(p) for p in paths]
|
||||
if resolution_context_nodes:
|
||||
# Persisted C# method labels carry their owner (#4883); the resolvers
|
||||
# match the bare `.Name()` form a fresh extraction produces.
|
||||
resolution_context_nodes = bare_csharp_method_labels_in_nodes(resolution_context_nodes)
|
||||
anchor_root = Path(root) if root is not None else None
|
||||
_check_tree_sitter_version()
|
||||
_raise_recursion_limit()
|
||||
|
||||
@@ -11,6 +11,7 @@ the core migration happens.
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _make_id
|
||||
@@ -187,6 +188,92 @@ def _metadata(value: object) -> dict:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _is_plain_csharp_name(text: str) -> bool:
|
||||
return bool(text) and not any(ch in text for ch in ".()") and not any(
|
||||
ch.isspace() for ch in text
|
||||
)
|
||||
|
||||
|
||||
def bare_csharp_method_label(label: object, source_file: object) -> str | None:
|
||||
"""Return the ``.Name()`` resolver form of a C# method label, else ``None``.
|
||||
|
||||
Accepts both the extractor's bare ``.Name()`` and the owner-qualified
|
||||
``Owner.Name()`` display form the graph build assigns (#4883). Extraction
|
||||
emits, and call resolution, interface dispatch, and the method-ghost index
|
||||
match on, the bare form, so anything reading labels back from a persisted
|
||||
graph normalizes through here. C# method and type names never contain a
|
||||
dot (an explicit interface implementation is still labeled ``.Build()``),
|
||||
so the split is unambiguous.
|
||||
"""
|
||||
if not _is_cs_file(source_file) or not isinstance(label, str):
|
||||
return None
|
||||
if not label.endswith("()"):
|
||||
return None
|
||||
owner, dot, name = label[:-2].rpartition(".")
|
||||
if not dot or not _is_plain_csharp_name(name):
|
||||
return None
|
||||
if owner and not _is_plain_csharp_name(owner):
|
||||
return None
|
||||
return f".{name}()"
|
||||
|
||||
|
||||
def bare_csharp_method_labels_in_nodes(nodes: list[dict]) -> list[dict]:
|
||||
"""Copy of *nodes* with owner-qualified C# method labels reverted to ``.Name()``.
|
||||
|
||||
Nodes that need no change are returned as-is; changed nodes are shallow
|
||||
copies, so the caller's list and dicts are never mutated.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for node in nodes:
|
||||
label = node.get("label")
|
||||
bare = bare_csharp_method_label(label, node.get("source_file"))
|
||||
out.append(node if bare is None or bare == label else {**node, "label": bare})
|
||||
return out
|
||||
|
||||
|
||||
def csharp_method_label_reassignments(
|
||||
nodes: Iterable[tuple[object, dict]],
|
||||
method_edges: Iterable[tuple[object, object]],
|
||||
) -> dict[str, str]:
|
||||
"""Return ``{method_id: "Owner.Name()"}`` display labels for C# methods (#4883).
|
||||
|
||||
*nodes* are ``(id, attrs)`` pairs and *method_edges* are ``(owner_id,
|
||||
method_id)`` pairs from ``method`` edges. A method with zero or several
|
||||
distinct owner labels, or an owner whose label is not a plain type name,
|
||||
is omitted and keeps its bare ``.Name()`` label. Derived from the bare form,
|
||||
so applying it to already-qualified labels is a no-op.
|
||||
"""
|
||||
owner_label_by_id: dict[str, str] = {}
|
||||
bare_by_id: dict[str, str] = {}
|
||||
for nid, attrs in nodes:
|
||||
if not isinstance(nid, str) or not isinstance(attrs, dict):
|
||||
continue
|
||||
label = attrs.get("label")
|
||||
source_file = attrs.get("source_file")
|
||||
if not isinstance(label, str) or not _is_cs_file(source_file):
|
||||
continue
|
||||
if _is_plain_csharp_name(label):
|
||||
owner_label_by_id[nid] = label
|
||||
continue
|
||||
bare = bare_csharp_method_label(label, source_file)
|
||||
if bare is not None:
|
||||
bare_by_id[nid] = bare
|
||||
|
||||
owner_labels_by_method: dict[str, set[str | None]] = {}
|
||||
for owner, method in method_edges:
|
||||
if isinstance(owner, str) and isinstance(method, str) and method in bare_by_id:
|
||||
owner_labels_by_method.setdefault(method, set()).add(owner_label_by_id.get(owner))
|
||||
|
||||
out: dict[str, str] = {}
|
||||
for method, owner_labels in owner_labels_by_method.items():
|
||||
if len(owner_labels) != 1:
|
||||
continue
|
||||
owner_label = next(iter(owner_labels))
|
||||
if owner_label is not None:
|
||||
out[method] = f"{owner_label}{bare_by_id[method]}"
|
||||
return out
|
||||
|
||||
|
||||
class CsharpNameResolver:
|
||||
"""Namespace/using/alias-aware C# simple-name resolution.
|
||||
|
||||
|
||||
@@ -2547,9 +2547,11 @@ def _rebuild_code(
|
||||
dedupe_nodes as _dedupe_nodes,
|
||||
disambiguate_file_labels_in_nodes as _disamb_labels,
|
||||
finalize_raw_graph_endpoints as _finalize_raw_graph_endpoints,
|
||||
qualify_csharp_method_labels_in_nodes as _qualify_cs_methods,
|
||||
)
|
||||
raw_nodes = _dedupe_nodes(result.get("nodes", []))
|
||||
_disamb_labels(raw_nodes)
|
||||
_qualify_cs_methods(raw_nodes, result.get("edges", []))
|
||||
from graphify.extract import RUN_ONLY_EXTRACTION_KEYS as _RUN_ONLY_KEYS
|
||||
candidate_graph_data = {
|
||||
**{
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""C# method nodes display their owning type (#4883).
|
||||
|
||||
Every method used to be labeled `.Build()`, so `IReport.Build()`,
|
||||
`PdfReport.Build()` and `CsvReport.Build()` printed identically and only the
|
||||
line told them apart. The graph build now gives each C# method an
|
||||
`Owner.Name()` display label. Ids and edges are unchanged, and extraction
|
||||
still emits the bare `.Name()` form that call resolution matches on; a
|
||||
persisted graph handed back as incremental resolution context is normalized
|
||||
back to it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
from graphify.extractors.csharp import (
|
||||
bare_csharp_method_label,
|
||||
csharp_method_label_reassignments,
|
||||
)
|
||||
|
||||
_ISSUE_REPRO = (
|
||||
"public interface IReport { string Build(); }\n"
|
||||
"public class PdfReport : IReport { public string Build() { return \"pdf\"; } }\n"
|
||||
"public class CsvReport : IReport { public string Build() { return \"csv\"; } }\n"
|
||||
"public class Exporter {\n"
|
||||
" private readonly IReport _report;\n"
|
||||
" public Exporter(IReport report) { _report = report; }\n"
|
||||
" public string Run() { return _report.Build(); }\n"
|
||||
"}\n"
|
||||
)
|
||||
|
||||
_SPLIT = {
|
||||
"Report.cs": (
|
||||
"public interface IReport { string Build(); }\n"
|
||||
"public class PdfReport : IReport { public string Build() { return \"pdf\"; } }\n"
|
||||
"public class CsvReport : IReport { public string Build() { return \"csv\"; } }\n"
|
||||
),
|
||||
"Exporter.cs": (
|
||||
"public class Exporter {\n"
|
||||
" private readonly IReport _report;\n"
|
||||
" public Exporter(IReport report) { _report = report; }\n"
|
||||
" public string Run() { return _report.Build(); }\n"
|
||||
"}\n"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _write(root: Path, files: dict[str, str]) -> None:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
for name, body in files.items():
|
||||
(root / name).write_text(body, encoding="utf-8")
|
||||
|
||||
|
||||
def _graph(root: Path) -> dict:
|
||||
return json.loads((root / "graphify-out" / "graph.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _labels(graph: dict) -> dict[str, str]:
|
||||
return {n["id"]: n["label"] for n in graph["nodes"]}
|
||||
|
||||
|
||||
def _edges(graph: dict, relations: tuple[str, ...]) -> set[tuple[str, str, str]]:
|
||||
return {
|
||||
(e["source"], e["relation"], e["target"])
|
||||
for e in graph.get("links", graph.get("edges", []))
|
||||
if e["relation"] in relations
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_cluster", [False, True])
|
||||
def test_issue_repro_methods_display_their_owning_type(tmp_path, no_cluster):
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
_write(tmp_path, {"Report.cs": _ISSUE_REPRO})
|
||||
assert _rebuild_code(tmp_path, no_cluster=no_cluster, acquire_lock=False, force=True)
|
||||
labels = _labels(_graph(tmp_path))
|
||||
|
||||
assert labels["report_ireport_build"] == "IReport.Build()"
|
||||
assert labels["report_pdfreport_build"] == "PdfReport.Build()"
|
||||
assert labels["report_csvreport_build"] == "CsvReport.Build()"
|
||||
assert labels["report_exporter_run"] == "Exporter.Run()"
|
||||
assert labels["report_ireport"] == "IReport"
|
||||
assert labels["report"] == "Report.cs"
|
||||
|
||||
|
||||
def test_ids_and_edges_match_the_raw_extraction(tmp_path):
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
_write(tmp_path, {"Report.cs": _ISSUE_REPRO})
|
||||
raw = extract([tmp_path / "Report.cs"], root=tmp_path)
|
||||
assert _rebuild_code(tmp_path, acquire_lock=False, force=True)
|
||||
graph = _graph(tmp_path)
|
||||
|
||||
assert {n["id"] for n in graph["nodes"]} == {n["id"] for n in raw["nodes"]}
|
||||
structural = ("method", "calls", "dispatches_to", "implements", "contains")
|
||||
assert _edges(graph, structural) == {
|
||||
(e["source"], e["relation"], e["target"])
|
||||
for e in raw["edges"] if e["relation"] in structural
|
||||
}
|
||||
assert ("report_exporter_run", "calls", "report_ireport_build") in _edges(graph, ("calls",))
|
||||
|
||||
|
||||
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()"]
|
||||
|
||||
|
||||
def test_incremental_rebuild_binds_into_an_unchanged_file(tmp_path):
|
||||
"""Only the caller is re-extracted; the callee's persisted label is already
|
||||
`IReport.Build()`. The call and the dispatch edges must match a full build."""
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
inc, full = tmp_path / "inc", tmp_path / "full"
|
||||
for root in (inc, full):
|
||||
_write(root, _SPLIT)
|
||||
assert _rebuild_code(inc, no_cluster=True, acquire_lock=False, force=True)
|
||||
assert _labels(_graph(inc))["report_ireport_build"] == "IReport.Build()"
|
||||
for root in (inc, full):
|
||||
p = root / "Exporter.cs"
|
||||
p.write_text(p.read_text(encoding="utf-8") + "// touched\n", encoding="utf-8")
|
||||
assert _rebuild_code(
|
||||
inc, changed_paths=[inc / "Exporter.cs"], no_cluster=True, acquire_lock=False,
|
||||
)
|
||||
assert _rebuild_code(full, no_cluster=True, acquire_lock=False, force=True)
|
||||
|
||||
relations = ("calls", "dispatches_to")
|
||||
assert _edges(_graph(inc), relations) == _edges(_graph(full), relations)
|
||||
assert ("exporter_exporter_run", "calls", "report_ireport_build") in _edges(_graph(full), relations)
|
||||
inc_labels, full_labels = _labels(_graph(inc)), _labels(_graph(full))
|
||||
assert {nid: inc_labels.get(nid) for nid in full_labels} == full_labels
|
||||
|
||||
|
||||
def test_resolution_context_labels_are_normalized_without_mutating_the_caller(tmp_path):
|
||||
_write(tmp_path, _SPLIT)
|
||||
context = [
|
||||
{"id": "report_ireport", "label": "IReport", "source_file": "Report.cs",
|
||||
"file_type": "code", "type": None},
|
||||
{"id": "report_ireport_build", "label": "IReport.Build()", "source_file": "Report.cs",
|
||||
"file_type": "code", "type": None, "_callable": True,
|
||||
"metadata": {"arity": 0, "signature": ""}},
|
||||
]
|
||||
context_edges = [
|
||||
{"source": "report", "target": "report_ireport", "relation": "contains",
|
||||
"source_file": "Report.cs"},
|
||||
{"source": "report_ireport", "target": "report_ireport_build", "relation": "method",
|
||||
"source_file": "Report.cs"},
|
||||
]
|
||||
r = extract(
|
||||
[tmp_path / "Exporter.cs"], root=tmp_path,
|
||||
resolution_context_nodes=context, resolution_context_edges=context_edges,
|
||||
)
|
||||
assert ("exporter_exporter_run", "report_ireport_build") in {
|
||||
(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"
|
||||
}
|
||||
assert context[1]["label"] == "IReport.Build()"
|
||||
|
||||
|
||||
def test_rebuilding_from_qualified_labels_does_not_stack_the_owner():
|
||||
from graphify.build import build_from_json
|
||||
|
||||
extraction = {
|
||||
"nodes": [
|
||||
{"id": "r_pdfreport", "label": "PdfReport", "file_type": "code",
|
||||
"source_file": "Report.cs", "source_location": "L2", "_origin": "ast"},
|
||||
{"id": "r_pdfreport_build", "label": "PdfReport.Build()", "file_type": "code",
|
||||
"source_file": "Report.cs", "source_location": "L2", "_origin": "ast"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "r_pdfreport", "target": "r_pdfreport_build", "relation": "method",
|
||||
"confidence": "EXTRACTED", "source_file": "Report.cs"},
|
||||
],
|
||||
}
|
||||
G = build_from_json(extraction)
|
||||
assert G.nodes["r_pdfreport_build"]["label"] == "PdfReport.Build()"
|
||||
G2 = build_from_json({
|
||||
"nodes": [{"id": n, **d} for n, d in G.nodes(data=True)],
|
||||
"edges": extraction["edges"],
|
||||
})
|
||||
assert G2.nodes["r_pdfreport_build"]["label"] == "PdfReport.Build()"
|
||||
|
||||
|
||||
def test_qualified_methods_stay_out_of_god_nodes(tmp_path):
|
||||
from graphify.analyze import _is_file_node
|
||||
from graphify.build import build_from_json
|
||||
|
||||
_write(tmp_path, {"Report.cs": _ISSUE_REPRO})
|
||||
G = build_from_json(extract([tmp_path / "Report.cs"], root=tmp_path))
|
||||
assert G.nodes["report_pdfreport_build"]["label"] == "PdfReport.Build()"
|
||||
assert _is_file_node(G, "report_pdfreport_build")
|
||||
assert not _is_file_node(G, "report_pdfreport")
|
||||
|
||||
|
||||
def test_semantic_method_ghost_still_collapses_onto_a_qualified_method():
|
||||
"""#3705 parity: an LLM ghost `Build()` in the same file remaps onto the one
|
||||
AST method even when that method's persisted label is `PdfReport.Build()`."""
|
||||
from graphify.build import build_from_json
|
||||
|
||||
extraction = {
|
||||
"nodes": [
|
||||
{"id": "report_pdfreport_build", "label": "PdfReport.Build()", "file_type": "code",
|
||||
"source_file": "Report.cs", "source_location": "L2", "_origin": "ast"},
|
||||
{"id": "report_build", "label": "Build()", "file_type": "code",
|
||||
"source_file": "Report.cs"},
|
||||
{"id": "doc", "label": "Doc", "file_type": "document", "source_file": "d.md"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "doc", "target": "report_build", "relation": "references",
|
||||
"confidence": "INFERRED", "confidence_score": 0.85, "source_file": "d.md"},
|
||||
],
|
||||
}
|
||||
G = build_from_json(extraction)
|
||||
assert "report_build" not in G.nodes
|
||||
assert G.has_edge("doc", "report_pdfreport_build")
|
||||
|
||||
|
||||
def test_class_segment_less_method_alias_still_resolves_a_qualified_method():
|
||||
"""The raw --no-cluster writer finalizes endpoints after relabeling, so the
|
||||
`<file stem>_<method>` alias must still be read off `PdfReport.Build()`."""
|
||||
from graphify.build import finalize_raw_graph_endpoints
|
||||
|
||||
data = {
|
||||
"nodes": [
|
||||
{"id": "report_pdfreport_build", "label": "PdfReport.Build()", "file_type": "code",
|
||||
"source_file": "Report.cs", "source_location": "L2", "_origin": "ast"},
|
||||
{"id": "doc", "label": "Doc", "file_type": "document", "source_file": "d.md"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "doc", "target": "report_build", "relation": "references"},
|
||||
],
|
||||
}
|
||||
finalize_raw_graph_endpoints(data)
|
||||
assert [(e["source"], e["target"]) for e in data["edges"]] == [
|
||||
("doc", "report_pdfreport_build"),
|
||||
]
|
||||
|
||||
|
||||
def test_other_languages_keep_bare_method_labels(tmp_path):
|
||||
from graphify.build import build_from_json
|
||||
|
||||
_write(tmp_path, {
|
||||
"Report.java": "class PdfReport { String build() { return \"pdf\"; } }\n",
|
||||
"Report.swift": "class PdfReport { func build() -> String { return \"pdf\" } }\n",
|
||||
})
|
||||
G = build_from_json(extract(
|
||||
[tmp_path / "Report.java", tmp_path / "Report.swift"], root=tmp_path,
|
||||
))
|
||||
method_labels = {
|
||||
d["label"] for _, d in G.nodes(data=True) if str(d.get("label", "")).endswith("()")
|
||||
}
|
||||
assert method_labels == {".build()"}
|
||||
|
||||
|
||||
def test_reassignment_fails_closed_on_missing_or_conflicting_owners():
|
||||
nodes = [
|
||||
("a", {"label": "A", "source_file": "x.cs"}),
|
||||
("b", {"label": "B", "source_file": "x.cs"}),
|
||||
("ns", {"label": "Acme.Reports", "source_file": "x.cs"}),
|
||||
("m_two_owners", {"label": ".Two()", "source_file": "x.cs"}),
|
||||
("m_no_owner", {"label": ".None()", "source_file": "x.cs"}),
|
||||
("m_dotted_owner", {"label": ".Dotted()", "source_file": "x.cs"}),
|
||||
("m_ok", {"label": ".Ok()", "source_file": "x.cs"}),
|
||||
("m_java", {"label": ".Ok()", "source_file": "x.java"}),
|
||||
]
|
||||
edges = [
|
||||
("a", "m_two_owners"), ("b", "m_two_owners"),
|
||||
("ns", "m_dotted_owner"),
|
||||
("a", "m_ok"),
|
||||
("a", "m_java"),
|
||||
]
|
||||
assert csharp_method_label_reassignments(nodes, edges) == {"m_ok": "A.Ok()"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("label", "source_file", "expected"), [
|
||||
(".Build()", "Report.cs", ".Build()"),
|
||||
("PdfReport.Build()", "Report.cs", ".Build()"),
|
||||
("PdfReport.Build()", "Report.java", None),
|
||||
("PdfReport", "Report.cs", None),
|
||||
("Build()", "Report.cs", None),
|
||||
("Acme.PdfReport.Build()", "Report.cs", None),
|
||||
("Report.cs", "Report.cs", None),
|
||||
])
|
||||
def test_bare_label_recognizes_only_method_shapes(label, source_file, expected):
|
||||
assert bare_csharp_method_label(label, source_file) == expected
|
||||
Reference in new issue
Block a user