feat(csharp): namespace-aware cross-file type resolution (#1562)
Extends the C# type-reference resolver (#1466) to be namespace-aware, advancing the #1318 shadow-node umbrella for C#: - The namespace is folded into the C# node id (_make_id(stem, namespace, name)), so two same-named types in different namespaces in one file no longer collapse — replacing #1466's detect-and-skip workaround for multi-namespace files. - Lexical per-block using-scope: a `using` applies only where it is in scope (file-level, or the enclosing namespace block via a scope chain), so sibling namespace blocks no longer share each other's usings. - Qualified references (`Namespace.Type`) resolve via in-scope aliases (`using Q = X.Y`) then exact known namespaces; generics are stripped. Preserves (and tightens) the refuse-rather-than-guess discipline: a bare reference resolves only when exactly one in-scope namespace provides the type; an ambiguous reference (e.g. `using A; using B;` both defining `Widget`) resolves to nothing rather than fanning out. Verified: `using A` -> A.Widget only; ambiguous -> no edge; qualified `B.Widget` -> B.Widget regardless of usings; sibling-block using-scope isolated; no dangling edges or fan-out. Reconciled onto current v8 (the PR predated the C++/ObjC member-call resolvers); full suite green, the C++/ObjC resolution coexists. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
committed by
safishamsi
co-authored by
Claude Opus 4.8
parent
49252d3cb7
commit
b9d8067d0a
+355
-117
@@ -29,10 +29,14 @@ from graphify.extractors.base import ( # noqa: F401
|
||||
_read_text,
|
||||
)
|
||||
from graphify.extractors.blade import extract_blade # noqa: F401
|
||||
from graphify.extractors.csharp import _resolve_csharp_type_references
|
||||
from graphify.extractors.csharp import (
|
||||
_resolve_cross_file_csharp_imports,
|
||||
_resolve_csharp_type_references,
|
||||
)
|
||||
from graphify.extractors.elixir import extract_elixir # noqa: F401
|
||||
from graphify.extractors.razor import extract_razor # noqa: F401
|
||||
from graphify.extractors.zig import extract_zig # noqa: F401
|
||||
from graphify.security import sanitize_metadata
|
||||
from graphify.paths import disambiguate_ambiguous_candidates
|
||||
|
||||
_RECURSION_LIMIT = 10_000
|
||||
@@ -77,6 +81,11 @@ def _file_node_id(rel_path: Path) -> str:
|
||||
return _make_id(_file_stem(rel_path))
|
||||
|
||||
|
||||
def _csharp_namespace_id(dotted_name: str) -> str:
|
||||
digest = hashlib.sha1(dotted_name.encode("utf-8")).hexdigest()[:16]
|
||||
return f"csharp_namespace:{digest}"
|
||||
|
||||
|
||||
_TSCONFIG_ALIAS_CACHE: dict[str, dict[str, list[str]]] = {}
|
||||
_WORKSPACE_PACKAGE_CACHE: dict[str, dict[str, Path]] = {}
|
||||
_WORKSPACE_MANIFEST_NAMES = ("pnpm-workspace.yaml", "package.json")
|
||||
@@ -714,22 +723,67 @@ def _csharp_classify_base(name: str, interface_names: set[str]) -> str:
|
||||
return "inherits"
|
||||
|
||||
|
||||
def _csharp_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
|
||||
"""Walk a C# type expression; append (name, role) tuples (role is 'type' or 'generic_arg')."""
|
||||
_CSHARP_TYPE_PARAMETER_SCOPE_DECLARATIONS = frozenset({
|
||||
"class_declaration",
|
||||
"interface_declaration",
|
||||
"record_declaration",
|
||||
"struct_declaration",
|
||||
"method_declaration",
|
||||
})
|
||||
|
||||
|
||||
def _csharp_type_parameters_in_scope(node, source: bytes) -> frozenset[str]:
|
||||
"""Return C# type-parameter names visible from ``node``."""
|
||||
names: set[str] = set()
|
||||
scope = node
|
||||
while scope is not None:
|
||||
if scope.type in _CSHARP_TYPE_PARAMETER_SCOPE_DECLARATIONS:
|
||||
for child in scope.children:
|
||||
if child.type != "type_parameter_list":
|
||||
continue
|
||||
for param in child.children:
|
||||
if param.type == "type_parameter":
|
||||
name_node = next(
|
||||
(sub for sub in param.children if sub.type == "identifier"),
|
||||
None,
|
||||
)
|
||||
if name_node is not None:
|
||||
name = _read_text(name_node, source)
|
||||
if name:
|
||||
names.add(name)
|
||||
elif param.type == "identifier":
|
||||
name = _read_text(param, source)
|
||||
if name:
|
||||
names.add(name)
|
||||
scope = scope.parent
|
||||
return frozenset(names)
|
||||
|
||||
|
||||
def _csharp_collect_type_refs(
|
||||
node,
|
||||
source: bytes,
|
||||
generic: bool,
|
||||
out: list[tuple[str, str, bool, str]],
|
||||
skip: frozenset[str] | None = None,
|
||||
) -> None:
|
||||
"""Walk a C# type expression; append (name, role, qualified, qualifier) tuples."""
|
||||
if node is None:
|
||||
return
|
||||
if skip is None:
|
||||
skip = _csharp_type_parameters_in_scope(node, source)
|
||||
t = node.type
|
||||
if t == "predefined_type":
|
||||
return
|
||||
if t == "identifier":
|
||||
name = _read_text(node, source)
|
||||
if name:
|
||||
out.append((name, "generic_arg" if generic else "type"))
|
||||
if name and name not in skip:
|
||||
out.append((name, "generic_arg" if generic else "type", False, ""))
|
||||
return
|
||||
if t == "qualified_name":
|
||||
text = _read_text(node, source).rsplit(".", 1)[-1]
|
||||
if text:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
prefix, _, text = _read_text(node, source).rpartition(".")
|
||||
text = text.split("<", 1)[0]
|
||||
if text and text not in skip:
|
||||
out.append((text, "generic_arg" if generic else "type", True, prefix))
|
||||
return
|
||||
if t == "generic_name":
|
||||
name_child = node.child_by_field_name("name")
|
||||
@@ -739,29 +793,31 @@ def _csharp_collect_type_refs(node, source: bytes, generic: bool, out: list[tupl
|
||||
name_child = sub
|
||||
break
|
||||
if name_child is not None:
|
||||
name = _read_text(name_child, source)
|
||||
if name:
|
||||
out.append((name, "generic_arg" if generic else "type"))
|
||||
qualified = name_child.type == "qualified_name"
|
||||
prefix, _, name = _read_text(name_child, source).rpartition(".")
|
||||
if name and name not in skip:
|
||||
out.append((name, "generic_arg" if generic else "type", qualified, prefix if qualified else ""))
|
||||
for sub in node.children:
|
||||
if sub.type == "type_argument_list":
|
||||
for arg in sub.children:
|
||||
if arg.is_named:
|
||||
_csharp_collect_type_refs(arg, source, True, out)
|
||||
_csharp_collect_type_refs(arg, source, True, out, skip)
|
||||
return
|
||||
if t in ("nullable_type", "array_type", "pointer_type", "ref_type"):
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_csharp_collect_type_refs(c, source, generic, out)
|
||||
_csharp_collect_type_refs(c, source, generic, out, skip)
|
||||
return
|
||||
if node.is_named:
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_csharp_collect_type_refs(c, source, generic, out)
|
||||
_csharp_collect_type_refs(c, source, generic, out, skip)
|
||||
|
||||
|
||||
def _csharp_attribute_names(method_node, source: bytes) -> list[str]:
|
||||
def _csharp_attribute_names(method_node, source: bytes) -> list[tuple[str, bool, str]]:
|
||||
"""Collect attribute names from a C# method/declaration's attribute_list children."""
|
||||
names: list[str] = []
|
||||
names: list[tuple[str, bool, str]] = []
|
||||
skip = _csharp_type_parameters_in_scope(method_node, source)
|
||||
for child in method_node.children:
|
||||
if child.type != "attribute_list":
|
||||
continue
|
||||
@@ -775,9 +831,10 @@ def _csharp_attribute_names(method_node, source: bytes) -> list[str]:
|
||||
name_node = sub
|
||||
break
|
||||
if name_node is not None:
|
||||
text = _read_text(name_node, source).rsplit(".", 1)[-1]
|
||||
if text:
|
||||
names.append(text)
|
||||
qualified = name_node.type == "qualified_name"
|
||||
prefix, _, text = _read_text(name_node, source).rpartition(".")
|
||||
if text and text not in skip:
|
||||
names.append((text, qualified, prefix if qualified else ""))
|
||||
return names
|
||||
|
||||
|
||||
@@ -1426,7 +1483,7 @@ def _find_body(node, config: LanguageConfig):
|
||||
|
||||
# ── Import handlers ───────────────────────────────────────────────────────────
|
||||
|
||||
def _import_python(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_python(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
t = node.type
|
||||
if t == "import_statement":
|
||||
for child in node.children:
|
||||
@@ -1489,7 +1546,7 @@ def _resolve_js_import_target(raw: str, str_path: str) -> "tuple[str, Path | Non
|
||||
return _make_id(module_name), None
|
||||
|
||||
|
||||
def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
is_reexport = node.type == "export_statement"
|
||||
# Only handle export_statement if it has a `from` clause (re-export).
|
||||
# Pure exports like `export const x = 1` or `export { localVar }` have no source module.
|
||||
@@ -1638,7 +1695,7 @@ def _dynamic_import_js(node, source: bytes, caller_nid: str, str_path: str, edge
|
||||
return True
|
||||
|
||||
|
||||
def _import_java(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_java(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
def _walk_scoped(n) -> str:
|
||||
parts: list[str] = []
|
||||
cur = n
|
||||
@@ -1691,7 +1748,7 @@ def _resolve_c_include_path(raw: str, str_path: str) -> "Path | None":
|
||||
return None
|
||||
|
||||
|
||||
def _import_c(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_c(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
for child in node.children:
|
||||
if child.type in ("string_literal", "system_lib_string", "string"):
|
||||
raw = _read_text(child, source).strip('"<> ')
|
||||
@@ -1728,27 +1785,38 @@ def _import_c(node, source: bytes, file_nid: str, stem: str, edges: list, str_pa
|
||||
break
|
||||
|
||||
|
||||
def _import_csharp(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
for child in node.children:
|
||||
if child.type in ("qualified_name", "identifier", "name_equals"):
|
||||
raw = _read_text(child, source)
|
||||
module_name = raw.split(".")[-1].strip()
|
||||
if module_name:
|
||||
tgt_nid = _make_id(module_name)
|
||||
edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "imports",
|
||||
"context": "import",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
break
|
||||
def _import_csharp(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
text = _read_text(node, source).strip().rstrip(";")
|
||||
if text.startswith("global "):
|
||||
text = text[len("global "):].strip()
|
||||
if not text.startswith("using"):
|
||||
return
|
||||
body = text[len("using"):].strip()
|
||||
using_kind, alias, target_fqn = "namespace", None, body
|
||||
if body.startswith("static "):
|
||||
using_kind, target_fqn = "static", body[len("static "):].strip()
|
||||
elif "=" in body:
|
||||
lhs, rhs = body.split("=", 1)
|
||||
using_kind, alias, target_fqn = "alias", lhs.strip(), rhs.strip()
|
||||
if not target_fqn:
|
||||
return
|
||||
edges.append({
|
||||
"source": file_nid,
|
||||
"target": _make_id(target_fqn),
|
||||
"relation": "imports",
|
||||
"context": "import",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"weight": 1.0,
|
||||
"metadata": sanitize_metadata({k: v for k, v in
|
||||
{"using_kind": using_kind, "alias": alias, "target_fqn": target_fqn,
|
||||
"scope_kind": "namespace" if scope_stack else "file",
|
||||
"scope_id": scope_stack[-1] if scope_stack else None}.items() if v is not None}),
|
||||
})
|
||||
|
||||
|
||||
def _import_kotlin(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_kotlin(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
path_node = node.child_by_field_name("path")
|
||||
if path_node:
|
||||
raw = _read_text(path_node, source)
|
||||
@@ -1784,7 +1852,7 @@ def _import_kotlin(node, source: bytes, file_nid: str, stem: str, edges: list, s
|
||||
break
|
||||
|
||||
|
||||
def _import_scala(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_scala(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
for child in node.children:
|
||||
if child.type in ("stable_id", "identifier"):
|
||||
raw = _read_text(child, source)
|
||||
@@ -1804,7 +1872,7 @@ def _import_scala(node, source: bytes, file_nid: str, stem: str, edges: list, st
|
||||
break
|
||||
|
||||
|
||||
def _import_php(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_php(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
for child in node.children:
|
||||
if child.type in ("qualified_name", "name", "identifier"):
|
||||
raw = _read_text(child, source)
|
||||
@@ -2230,23 +2298,56 @@ def _js_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str,
|
||||
|
||||
# ── C# extra walk for namespace declarations ──────────────────────────────────
|
||||
|
||||
def _csharp_namespace_name(node, source: bytes) -> str:
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is not None:
|
||||
return _read_text(name_node, source).strip()
|
||||
for child in node.children:
|
||||
if child.type in ("identifier", "qualified_name"):
|
||||
return _read_text(child, source).strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _csharp_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str,
|
||||
nodes: list, edges: list, seen_ids: set, function_bodies: list,
|
||||
parent_class_nid: str | None, add_node_fn, add_edge_fn,
|
||||
walk_fn) -> bool:
|
||||
"""Handle namespace_declaration for C#. Returns True if handled."""
|
||||
walk_fn, namespace_stack: list[str], scope_stack: list[str]) -> bool:
|
||||
"""Handle namespace declarations for C#. Returns True if handled."""
|
||||
if node.type == "namespace_declaration":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
ns_name = _read_text(name_node, source)
|
||||
ns_nid = _make_id(stem, ns_name)
|
||||
ns_name = _csharp_namespace_name(node, source)
|
||||
pushed = False
|
||||
if ns_name:
|
||||
namespace_stack.append(ns_name)
|
||||
scope_stack.append(f"s{node.start_byte}")
|
||||
pushed = True
|
||||
ns_label = ".".join(namespace_stack)
|
||||
ns_nid = _csharp_namespace_id(ns_label)
|
||||
line = node.start_point[0] + 1
|
||||
add_node_fn(ns_nid, ns_name, line)
|
||||
add_node_fn(ns_nid, ns_label, line, node_type="namespace", metadata={"kind": "csharp_namespace"})
|
||||
add_edge_fn(file_nid, ns_nid, "contains", line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
for child in body.children:
|
||||
walk_fn(child, parent_class_nid)
|
||||
try:
|
||||
for child in body.children:
|
||||
walk_fn(child, parent_class_nid)
|
||||
finally:
|
||||
if pushed:
|
||||
namespace_stack.pop()
|
||||
scope_stack.pop()
|
||||
elif pushed:
|
||||
namespace_stack.pop()
|
||||
scope_stack.pop()
|
||||
return True
|
||||
if node.type == "file_scoped_namespace_declaration":
|
||||
ns_name = _csharp_namespace_name(node, source)
|
||||
if ns_name:
|
||||
namespace_stack.append(ns_name)
|
||||
scope_stack.append(f"s{node.start_byte}")
|
||||
ns_label = ".".join(namespace_stack)
|
||||
ns_nid = _csharp_namespace_id(ns_label)
|
||||
line = node.start_point[0] + 1
|
||||
add_node_fn(ns_nid, ns_label, line, node_type="namespace", metadata={"kind": "csharp_namespace"})
|
||||
add_edge_fn(file_nid, ns_nid, "contains", line)
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -2525,7 +2626,7 @@ def _resolve_lua_import_target(raw_module: str, str_path: str) -> str:
|
||||
return _make_id(raw_module)
|
||||
|
||||
|
||||
def _import_lua(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
|
||||
def _import_lua(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> None:
|
||||
"""Extract require('module') from Lua variable_declaration nodes."""
|
||||
text = _read_text(node, source)
|
||||
import re
|
||||
@@ -2565,7 +2666,7 @@ _LUA_CONFIG = LanguageConfig(
|
||||
)
|
||||
|
||||
|
||||
def _import_swift(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> list[tuple[str, str]]:
|
||||
def _import_swift(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str, scope_stack: list[str] | None = None) -> list[tuple[str, str]]:
|
||||
"""Emit module-level ``imports`` edges and report the imported modules.
|
||||
|
||||
A Swift ``import CoreKit`` names a module, not a file path, so — unlike the
|
||||
@@ -2594,24 +2695,28 @@ def _import_swift(node, source: bytes, file_nid: str, stem: str, edges: list, st
|
||||
return modules
|
||||
|
||||
|
||||
def _read_csharp_type_name(node, source: bytes) -> str | None:
|
||||
"""Resolve a readable C# type name from a field/type node."""
|
||||
def _read_csharp_type_name(node, source: bytes) -> tuple[str, bool, str] | None:
|
||||
"""Resolve a C# type name, whether it was qualified, and its qualifier prefix."""
|
||||
if node is None:
|
||||
return None
|
||||
if node.type in ("identifier", "predefined_type"):
|
||||
return _read_text(node, source)
|
||||
return (_read_text(node, source), False, "")
|
||||
if node.type == "qualified_name":
|
||||
return _read_text(node, source).split(".")[-1]
|
||||
prefix, _, tail = _read_text(node, source).rpartition(".")
|
||||
tail = tail.split("<", 1)[0]
|
||||
return (tail, True, prefix)
|
||||
if node.type == "generic_name":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is not None:
|
||||
return _read_text(name_node, source)
|
||||
qualified = name_node.type == "qualified_name"
|
||||
prefix, _, tail = _read_text(name_node, source).rpartition(".")
|
||||
return (tail, qualified, prefix if qualified else "")
|
||||
for child in node.children:
|
||||
if not child.is_named:
|
||||
continue
|
||||
name = _read_csharp_type_name(child, source)
|
||||
if name:
|
||||
return name
|
||||
result = _read_csharp_type_name(child, source)
|
||||
if result:
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
@@ -2735,6 +2840,8 @@ def _extract_generic(
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
namespace_stack: list[str] = []
|
||||
scope_stack: list[str] = []
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
pending_listen_edges: list[tuple[str, str, int]] = []
|
||||
# tree-sitter-swift parses both `class Foo` and `extension Foo` as
|
||||
@@ -2760,20 +2867,33 @@ def _extract_generic(
|
||||
if config.ts_module == "tree_sitter_swift":
|
||||
swift_protocol_names, swift_class_names = _swift_pre_scan(root, source)
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
def add_node(nid: str, label: str, line: int, *, node_type: str | None = None,
|
||||
metadata: dict | None = None) -> None:
|
||||
if nid in seen_ids:
|
||||
return
|
||||
seen_ids.add(nid)
|
||||
merged = dict(metadata or {})
|
||||
if namespace_stack:
|
||||
merged.setdefault("namespace", ".".join(namespace_stack))
|
||||
if scope_stack and node_type != "namespace":
|
||||
merged.setdefault("scope_chain", list(scope_stack))
|
||||
node = {
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
}
|
||||
if node_type:
|
||||
node["type"] = node_type
|
||||
if merged:
|
||||
node["metadata"] = sanitize_metadata(merged)
|
||||
nodes.append(node)
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
context: str | None = None,
|
||||
metadata: dict | None = None) -> None:
|
||||
edge = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
@@ -2785,10 +2905,12 @@ def _extract_generic(
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
if metadata:
|
||||
edge["metadata"] = sanitize_metadata(metadata)
|
||||
edges.append(edge)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
nid = _make_id(stem, ".".join(namespace_stack), name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
@@ -2820,7 +2942,7 @@ def _extract_generic(
|
||||
# Import types
|
||||
if t in config.import_types:
|
||||
if config.import_handler:
|
||||
imported_modules = config.import_handler(node, source, file_nid, stem, edges, str_path)
|
||||
imported_modules = config.import_handler(node, source, file_nid, stem, edges, str_path, scope_stack)
|
||||
# Module-level import handlers (Swift) name a module, not a file
|
||||
# path, so there is no pre-existing node to anchor the edge to.
|
||||
# They return (id, label) pairs for which we materialize a
|
||||
@@ -2864,9 +2986,12 @@ def _extract_generic(
|
||||
if not name_node:
|
||||
return
|
||||
class_name = _read_text(name_node, source)
|
||||
class_nid = _make_id(stem, class_name)
|
||||
class_nid = _make_id(stem, ".".join(namespace_stack), class_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(class_nid, class_name, line)
|
||||
metadata = None
|
||||
if config.ts_module == "tree_sitter_c_sharp" and parent_class_nid:
|
||||
metadata = {"is_nested_type": True}
|
||||
add_node(class_nid, class_name, line, metadata=metadata)
|
||||
add_edge(file_nid, class_nid, "contains", line)
|
||||
|
||||
if config.ts_module == "tree_sitter_swift" and any(
|
||||
@@ -3050,25 +3175,20 @@ def _extract_generic(
|
||||
|
||||
# C#-specific: inheritance / interface implementation via base_list
|
||||
if config.ts_module == "tree_sitter_c_sharp":
|
||||
csharp_type_params = _csharp_type_parameters_in_scope(node, source)
|
||||
for child in node.children:
|
||||
if child.type != "base_list":
|
||||
continue
|
||||
for sub in child.children:
|
||||
if sub.type not in ("identifier", "generic_name", "qualified_name"):
|
||||
continue
|
||||
if sub.type == "generic_name":
|
||||
name_child = sub.child_by_field_name("name")
|
||||
base = (
|
||||
_read_text(name_child, source) if name_child
|
||||
else _read_text(sub.children[0], source)
|
||||
)
|
||||
elif sub.type == "qualified_name":
|
||||
base = _read_text(sub, source).rsplit(".", 1)[-1]
|
||||
else:
|
||||
base = _read_text(sub, source)
|
||||
if not base:
|
||||
base_info = _read_csharp_type_name(sub, source)
|
||||
if base_info is None:
|
||||
continue
|
||||
base_nid = _make_id(stem, base)
|
||||
base, qualified, qualifier = base_info
|
||||
if not base or base in csharp_type_params:
|
||||
continue
|
||||
base_nid = _make_id(stem, ".".join(namespace_stack), base)
|
||||
if base_nid not in seen_ids:
|
||||
base_nid = _make_id(base)
|
||||
if base_nid not in seen_ids:
|
||||
@@ -3081,7 +3201,12 @@ def _extract_generic(
|
||||
})
|
||||
seen_ids.add(base_nid)
|
||||
relation = _csharp_classify_base(base, csharp_interface_names)
|
||||
add_edge(class_nid, base_nid, relation, line)
|
||||
metadata = {"ref_token": base}
|
||||
if qualified:
|
||||
metadata["qualified"] = True
|
||||
if qualifier:
|
||||
metadata["ref_qualifier"] = qualifier
|
||||
add_edge(class_nid, base_nid, relation, line, metadata=metadata)
|
||||
if sub.type == "generic_name":
|
||||
for tal in sub.children:
|
||||
if tal.type != "type_argument_list":
|
||||
@@ -3089,12 +3214,19 @@ def _extract_generic(
|
||||
for arg in tal.children:
|
||||
if not arg.is_named:
|
||||
continue
|
||||
refs: list[tuple[str, str]] = []
|
||||
_csharp_collect_type_refs(arg, source, True, refs)
|
||||
for ref_name, _role in refs:
|
||||
refs: list[tuple[str, str, bool, str]] = []
|
||||
_csharp_collect_type_refs(
|
||||
arg, source, True, refs, csharp_type_params
|
||||
)
|
||||
for ref_name, _role, ref_qualified, ref_qualifier in refs:
|
||||
target = ensure_named_node(ref_name, line)
|
||||
metadata = {"ref_token": ref_name}
|
||||
if ref_qualified:
|
||||
metadata["qualified"] = True
|
||||
if ref_qualifier:
|
||||
metadata["ref_qualifier"] = ref_qualifier
|
||||
add_edge(class_nid, target, "references", line,
|
||||
context="generic_arg")
|
||||
context="generic_arg", metadata=metadata)
|
||||
|
||||
# Java-specific: extends (superclass) / implements (interfaces) / interface-extends
|
||||
if config.ts_module == "tree_sitter_java":
|
||||
@@ -3352,11 +3484,22 @@ def _extract_generic(
|
||||
type_node = child.child_by_field_name("type")
|
||||
if type_node is not None:
|
||||
break
|
||||
type_name = _read_csharp_type_name(type_node, source)
|
||||
if type_name:
|
||||
type_info = _read_csharp_type_name(type_node, source)
|
||||
if type_info:
|
||||
type_name, qualified, qualifier = type_info
|
||||
csharp_type_params = _csharp_type_parameters_in_scope(
|
||||
type_node if type_node is not None else node, source
|
||||
)
|
||||
if not type_name or type_name in csharp_type_params:
|
||||
return
|
||||
line = node.start_point[0] + 1
|
||||
metadata = {"ref_token": type_name}
|
||||
if qualified:
|
||||
metadata["qualified"] = True
|
||||
if qualifier:
|
||||
metadata["ref_qualifier"] = qualifier
|
||||
add_edge(parent_class_nid, ensure_named_node(type_name, line),
|
||||
"references", line, context="field")
|
||||
"references", line, context="field", metadata=metadata)
|
||||
return
|
||||
|
||||
if (config.ts_module == "tree_sitter_java"
|
||||
@@ -3551,32 +3694,55 @@ def _extract_generic(
|
||||
)
|
||||
|
||||
if config.ts_module == "tree_sitter_c_sharp":
|
||||
csharp_type_params = _csharp_type_parameters_in_scope(node, source)
|
||||
params_node = node.child_by_field_name("parameters")
|
||||
if params_node is not None:
|
||||
for p in params_node.children:
|
||||
if p.type != "parameter":
|
||||
continue
|
||||
type_node = p.child_by_field_name("type")
|
||||
refs: list[tuple[str, str]] = []
|
||||
_csharp_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
refs: list[tuple[str, str, bool, str]] = []
|
||||
_csharp_collect_type_refs(
|
||||
type_node, source, False, refs, csharp_type_params
|
||||
)
|
||||
for ref_name, role, qualified, qualifier in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "parameter_type"
|
||||
target_nid = ensure_named_node(ref_name, line)
|
||||
if target_nid != func_nid:
|
||||
add_edge(func_nid, target_nid, "references", line, context=ctx)
|
||||
metadata = {"ref_token": ref_name}
|
||||
if qualified:
|
||||
metadata["qualified"] = True
|
||||
if qualifier:
|
||||
metadata["ref_qualifier"] = qualifier
|
||||
add_edge(func_nid, target_nid, "references", line,
|
||||
context=ctx, metadata=metadata)
|
||||
return_node = node.child_by_field_name("returns")
|
||||
if return_node is not None:
|
||||
refs = []
|
||||
_csharp_collect_type_refs(return_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
refs: list[tuple[str, str, bool, str]] = []
|
||||
_csharp_collect_type_refs(
|
||||
return_node, source, False, refs, csharp_type_params
|
||||
)
|
||||
for ref_name, role, qualified, qualifier in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "return_type"
|
||||
target_nid = ensure_named_node(ref_name, line)
|
||||
if target_nid != func_nid:
|
||||
add_edge(func_nid, target_nid, "references", line, context=ctx)
|
||||
for attr_name in _csharp_attribute_names(node, source):
|
||||
metadata = {"ref_token": ref_name}
|
||||
if qualified:
|
||||
metadata["qualified"] = True
|
||||
if qualifier:
|
||||
metadata["ref_qualifier"] = qualifier
|
||||
add_edge(func_nid, target_nid, "references", line,
|
||||
context=ctx, metadata=metadata)
|
||||
for attr_name, qualified, qualifier in _csharp_attribute_names(node, source):
|
||||
target_nid = ensure_named_node(attr_name, line)
|
||||
if target_nid != func_nid:
|
||||
add_edge(func_nid, target_nid, "references", line, context="attribute")
|
||||
metadata = {"ref_token": attr_name}
|
||||
if qualified:
|
||||
metadata["qualified"] = True
|
||||
if qualifier:
|
||||
metadata["ref_qualifier"] = qualifier
|
||||
add_edge(func_nid, target_nid, "references", line,
|
||||
context="attribute", metadata=metadata)
|
||||
|
||||
if config.ts_module == "tree_sitter_java":
|
||||
params_node = node.child_by_field_name("parameters")
|
||||
@@ -3844,7 +4010,8 @@ def _extract_generic(
|
||||
if config.ts_module == "tree_sitter_c_sharp":
|
||||
if _csharp_extra_walk(node, source, file_nid, stem, str_path,
|
||||
nodes, edges, seen_ids, function_bodies,
|
||||
parent_class_nid, add_node, add_edge, walk):
|
||||
parent_class_nid, add_node, add_edge, walk,
|
||||
namespace_stack, scope_stack):
|
||||
return
|
||||
|
||||
if config.ts_module == "tree_sitter_swift":
|
||||
@@ -3877,6 +4044,8 @@ def _extract_generic(
|
||||
label_to_nid: dict[str, str] = {} # case-sensitive (Ruby, C#, Java, Kotlin, etc.)
|
||||
label_to_nid_ci: dict[str, str] = {} # case-insensitive (PHP functions/classes)
|
||||
for n in nodes:
|
||||
if n.get("type") == "namespace":
|
||||
continue
|
||||
raw = n["label"]
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
@@ -8049,7 +8218,7 @@ def _disambiguate_colliding_node_ids(
|
||||
"""
|
||||
by_id: dict[str, list[dict]] = {}
|
||||
for node in nodes:
|
||||
if node.get("type") == "module":
|
||||
if node.get("type") in ("module", "namespace"):
|
||||
continue
|
||||
nid = node.get("id")
|
||||
if isinstance(nid, str) and nid:
|
||||
@@ -8156,12 +8325,57 @@ def _disambiguate_colliding_node_ids(
|
||||
raw_call["caller_nid"] = unambiguous_remaps[str(raw_call["caller_nid"])]
|
||||
|
||||
|
||||
def _canonicalize_csharp_namespace_nodes(all_nodes: list[dict], all_edges: list[dict]) -> None:
|
||||
"""Collapse duplicate C# namespace node entries to one canonical node per label."""
|
||||
by_label: dict[str, list[dict]] = {}
|
||||
for node in all_nodes:
|
||||
if node.get("type") != "namespace":
|
||||
continue
|
||||
label = node.get("label")
|
||||
if isinstance(label, str):
|
||||
by_label.setdefault(label, []).append(node)
|
||||
|
||||
remap: dict[str, str] = {}
|
||||
drop_node_ids: set[int] = set()
|
||||
for group in by_label.values():
|
||||
if len(group) < 2:
|
||||
continue
|
||||
canonical = sorted(
|
||||
group,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
)[0]
|
||||
canonical_id = canonical.get("id")
|
||||
for node in group:
|
||||
if node is canonical:
|
||||
continue
|
||||
drop_node_ids.add(id(node))
|
||||
dup_id = node.get("id")
|
||||
if isinstance(dup_id, str) and isinstance(canonical_id, str):
|
||||
remap[dup_id] = canonical_id
|
||||
|
||||
if remap:
|
||||
for edge in all_edges:
|
||||
if edge.get("source") in remap:
|
||||
edge["source"] = remap[str(edge["source"])]
|
||||
if edge.get("target") in remap:
|
||||
edge["target"] = remap[str(edge["target"])]
|
||||
|
||||
if drop_node_ids:
|
||||
all_nodes[:] = [node for node in all_nodes if id(node) not in drop_node_ids]
|
||||
|
||||
|
||||
def _node_label_key(node: dict) -> str:
|
||||
label = str(node.get("label", "")).strip()
|
||||
return re.sub(r"[^a-zA-Z0-9]+", "", label).lower()
|
||||
|
||||
|
||||
def _is_type_like_definition(node: dict) -> bool:
|
||||
if node.get("type") == "namespace":
|
||||
return False
|
||||
label = str(node.get("label", "")).strip()
|
||||
if not label:
|
||||
return False
|
||||
@@ -8188,7 +8402,6 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
|
||||
stubs.append(node)
|
||||
|
||||
remap: dict[str, str] = {}
|
||||
drop_ids: set[str] = set()
|
||||
for stub in stubs:
|
||||
stub_id = str(stub.get("id", ""))
|
||||
if not stub_id:
|
||||
@@ -8199,17 +8412,36 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
|
||||
target_id = candidates[0].get("id")
|
||||
if isinstance(target_id, str) and target_id and target_id != stub_id:
|
||||
remap[stub_id] = target_id
|
||||
drop_ids.add(stub_id)
|
||||
|
||||
if not remap:
|
||||
return
|
||||
|
||||
by_id = {node.get("id"): node for node in nodes if node.get("id")}
|
||||
csharp_scoped_relations = {"inherits", "implements", "references", "imports"}
|
||||
for edge in edges:
|
||||
if edge.get("source") in remap:
|
||||
edge["source"] = remap[str(edge["source"])]
|
||||
if edge.get("target") in remap:
|
||||
edge["target"] = remap[str(edge["target"])]
|
||||
is_csharp_scoped_edge = (
|
||||
str(edge.get("source_file", "")).endswith(".cs")
|
||||
and edge.get("relation") in csharp_scoped_relations
|
||||
)
|
||||
source = edge.get("source")
|
||||
if source in remap:
|
||||
remapped_source = remap[str(source)]
|
||||
if not (
|
||||
is_csharp_scoped_edge
|
||||
and str(by_id.get(remapped_source, {}).get("source_file", "")).endswith(".cs")
|
||||
):
|
||||
edge["source"] = remapped_source
|
||||
target = edge.get("target")
|
||||
if target in remap:
|
||||
remapped_target = remap[str(target)]
|
||||
if not (
|
||||
is_csharp_scoped_edge
|
||||
and str(by_id.get(remapped_target, {}).get("source_file", "")).endswith(".cs")
|
||||
):
|
||||
edge["target"] = remapped_target
|
||||
|
||||
referenced = {x for e in edges for x in (e.get("source"), e.get("target"))}
|
||||
drop_ids = {stub_id for stub_id in remap if stub_id not in referenced}
|
||||
nodes[:] = [node for node in nodes if node.get("id") not in drop_ids]
|
||||
|
||||
|
||||
@@ -14506,6 +14738,7 @@ def extract(
|
||||
|
||||
_merge_swift_extensions(per_file, all_nodes, all_edges)
|
||||
_disambiguate_colliding_node_ids(all_nodes, all_edges, all_raw_calls, root)
|
||||
_canonicalize_csharp_namespace_nodes(all_nodes, all_edges)
|
||||
_rewire_unique_stub_nodes(all_nodes, all_edges)
|
||||
|
||||
# Add cross-file class-level edges (Python only - uses Python parser internally)
|
||||
@@ -14547,6 +14780,11 @@ def extract(
|
||||
except Exception as exc:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("C# type-reference resolution failed, skipping: %s", exc)
|
||||
try:
|
||||
_resolve_cross_file_csharp_imports(cs_results, cs_paths, all_nodes, all_edges)
|
||||
except Exception as exc:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("C# cross-file import resolution failed, skipping: %s", exc)
|
||||
|
||||
# Cross-file call resolution for all languages
|
||||
# Each extractor saved unresolved calls in raw_calls. Now that we have all
|
||||
@@ -14559,7 +14797,7 @@ def extract(
|
||||
# identifiers, and they were polluting matches for short names — #563).
|
||||
global_label_to_nids: dict[str, list[str]] = {}
|
||||
for n in all_nodes:
|
||||
if n.get("file_type") == "rationale":
|
||||
if n.get("file_type") == "rationale" or n.get("type") == "namespace":
|
||||
continue
|
||||
raw = n.get("label", "")
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
|
||||
+350
-115
@@ -10,140 +10,375 @@ the core migration happens.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _read_text
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def _resolve_csharp_type_references(
|
||||
def _build_csharp_type_def_index(all_nodes: list[dict]) -> dict[tuple[str, str], str]:
|
||||
"""Return deterministic ``(namespace, name) -> node_id`` C# type definitions."""
|
||||
candidates: dict[tuple[str, str], list[dict]] = {}
|
||||
for node in all_nodes:
|
||||
if node.get("type") == "namespace":
|
||||
continue
|
||||
metadata = node.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
if metadata.get("is_nested_type"):
|
||||
continue
|
||||
nid = node.get("id")
|
||||
label = node.get("label")
|
||||
if not (isinstance(nid, str) and nid and isinstance(label, str) and label):
|
||||
continue
|
||||
source_file = node.get("source_file")
|
||||
if (
|
||||
not isinstance(source_file, str)
|
||||
or not source_file.endswith(".cs")
|
||||
or node.get("file_type") != "code"
|
||||
):
|
||||
continue
|
||||
if label.endswith(")") or label.startswith(".") or "." in label:
|
||||
continue
|
||||
namespace = metadata.get("namespace", "")
|
||||
if not isinstance(namespace, str):
|
||||
namespace = ""
|
||||
candidates.setdefault((namespace, label), []).append(node)
|
||||
|
||||
return {
|
||||
key: sorted(
|
||||
nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
)[0]["id"]
|
||||
for key, nodes in candidates.items()
|
||||
}
|
||||
|
||||
|
||||
def _strip_trailing_csharp_generic_args(target_fqn: str) -> str:
|
||||
target_fqn = target_fqn.strip()
|
||||
if not target_fqn.endswith(">"):
|
||||
return target_fqn
|
||||
depth = 0
|
||||
for index in range(len(target_fqn) - 1, -1, -1):
|
||||
char = target_fqn[index]
|
||||
if char == ">":
|
||||
depth += 1
|
||||
elif char == "<":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return target_fqn[:index].strip()
|
||||
return target_fqn
|
||||
|
||||
|
||||
def _resolve_cross_file_csharp_imports(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Re-point dangling C# ``inherits``/``implements``/``references`` edges to the
|
||||
real definition, using the referencing file's ``using`` directives + enclosing
|
||||
namespace for exact disambiguation. Mirrors ``_resolve_java_type_references``.
|
||||
"""Re-point resolvable C# ``using`` import edges to canonical internal nodes.
|
||||
|
||||
C# deltas from Java: a plain ``using N;`` is NAMESPACE-WIDE (resolve a bare ``T``
|
||||
by trying ``(N, T)`` for each open namespace and accepting only a UNIQUE hit — the
|
||||
god-node guardrail), while ``using X = N.T;`` is a single-type alias. ``global
|
||||
using`` is normalized (the ``global`` prefix stripped); ``using static N.T;`` is
|
||||
ignored (it imports members, not a namespace/type). The global namespace is keyed
|
||||
as the bare label (``""``). A file with MULTIPLE namespace blocks does not register
|
||||
its defs (which namespace each def belongs to needs source-range tracking) — deferred.
|
||||
|
||||
Mutates ``all_nodes``/``all_edges`` in place. Runs after id-disambiguation and
|
||||
``_rewire_unique_stub_nodes`` so target ids are final and only the ambiguous
|
||||
remainder is left on shadow stubs.
|
||||
Namespace imports resolve only to canonical C# namespace nodes. Alias imports
|
||||
resolve only when the alias target's prefix is a known canonical namespace and
|
||||
the simple type name exists in the shared C# type-definition index. ``using
|
||||
static`` and nested type aliases remain deliberate gaps because they need
|
||||
member/nested-type modeling beyond this import pass.
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_c_sharp as tscs
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
_ = (per_file, paths)
|
||||
namespace_id_by_label: dict[str, str] = {}
|
||||
for node in sorted(
|
||||
all_nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
):
|
||||
if node.get("type") != "namespace":
|
||||
continue
|
||||
label = node.get("label")
|
||||
nid = node.get("id")
|
||||
if isinstance(label, str) and label and isinstance(nid, str) and nid:
|
||||
namespace_id_by_label.setdefault(label, nid)
|
||||
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
if not namespace_id_by_label and not type_def_index:
|
||||
return
|
||||
|
||||
language = Language(tscs.language())
|
||||
parser = Parser(language)
|
||||
|
||||
def _key(ns: str, label: str) -> str:
|
||||
return label if ns == "" else f"{ns}.{label}"
|
||||
|
||||
own_ns_by_file: dict[str, list[str]] = {}
|
||||
scope_by_file: dict[str, list[str]] = {}
|
||||
aliases_by_file: dict[str, dict[str, str]] = {}
|
||||
for path, result in zip(paths, per_file):
|
||||
srcs = {n.get("source_file") for n in result.get("nodes", []) if n.get("source_file")}
|
||||
if not srcs:
|
||||
continue
|
||||
try:
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
except Exception:
|
||||
continue
|
||||
own_ns: list[str] = []
|
||||
usings: list[str] = []
|
||||
aliases: dict[str, str] = {}
|
||||
|
||||
def walk(n) -> None:
|
||||
if n.type in ("namespace_declaration", "file_scoped_namespace_declaration"):
|
||||
nm = n.child_by_field_name("name")
|
||||
if nm is not None:
|
||||
own_ns.append(_read_text(nm, source).strip())
|
||||
elif n.type == "using_directive":
|
||||
text = _read_text(n, source).strip().rstrip(";")
|
||||
if text.startswith("global "):
|
||||
text = text[len("global "):].strip()
|
||||
if text.startswith("using"):
|
||||
body = text[len("using"):].strip()
|
||||
if body.startswith("static "):
|
||||
pass # `using static N.T;` imports members, not a type/namespace — skip
|
||||
elif "=" in body:
|
||||
lhs, rhs = body.split("=", 1)
|
||||
if lhs.strip() and rhs.strip():
|
||||
aliases[lhs.strip()] = rhs.strip()
|
||||
elif body:
|
||||
usings.append(body)
|
||||
for child in n.children:
|
||||
walk(child)
|
||||
|
||||
walk(tree.root_node)
|
||||
scope = list(dict.fromkeys((own_ns or [""]) + usings + [""]))
|
||||
for s in srcs:
|
||||
own_ns_by_file[s] = own_ns
|
||||
scope_by_file[s] = scope
|
||||
aliases_by_file[s] = aliases
|
||||
|
||||
fqn_to_id: dict[str, str] = {}
|
||||
for node in all_nodes:
|
||||
label = node.get("label", "")
|
||||
src = node.get("source_file", "")
|
||||
nid = node.get("id", "")
|
||||
if not (label and src and nid) or src not in own_ns_by_file:
|
||||
continue
|
||||
if not label[:1].isupper() or label.endswith(")") or label.endswith(".cs"):
|
||||
continue
|
||||
ns_list = own_ns_by_file.get(src, [])
|
||||
if len(ns_list) == 0:
|
||||
fqn_to_id.setdefault(_key("", label), nid)
|
||||
elif len(ns_list) == 1:
|
||||
fqn_to_id.setdefault(_key(ns_list[0], label), nid)
|
||||
# len > 1: skip (deferred)
|
||||
|
||||
stub_label: dict[str, str] = {
|
||||
node["id"]: node.get("label", "")
|
||||
for node in all_nodes
|
||||
if node.get("id") and not node.get("source_file") and node.get("label", "")[:1].isupper()
|
||||
}
|
||||
if not stub_label:
|
||||
return
|
||||
|
||||
REPOINT_RELATIONS = {"implements", "inherits", "references"}
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") not in REPOINT_RELATIONS:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
tgt = edge.get("target")
|
||||
label = stub_label.get(tgt)
|
||||
if not label:
|
||||
metadata = edge.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
continue
|
||||
ref_file = edge.get("source_file", "")
|
||||
using_kind = metadata.get("using_kind")
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not using_kind or not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
|
||||
resolved = None
|
||||
alias_fqn = aliases_by_file.get(ref_file, {}).get(label)
|
||||
if alias_fqn:
|
||||
ns, _, simple = alias_fqn.rpartition(".")
|
||||
resolved = fqn_to_id.get(_key(ns, simple))
|
||||
if resolved is None:
|
||||
cands: list[str] = []
|
||||
for ns in scope_by_file.get(ref_file, []):
|
||||
hit = fqn_to_id.get(_key(ns, label))
|
||||
if hit and hit not in cands:
|
||||
cands.append(hit)
|
||||
if len(cands) == 1:
|
||||
resolved = cands[0]
|
||||
if resolved and resolved != tgt:
|
||||
if using_kind == "namespace":
|
||||
resolved = namespace_id_by_label.get(target_fqn)
|
||||
elif using_kind == "alias":
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
prefix, sep, name = base_fqn.rpartition(".")
|
||||
if sep and prefix in namespace_id_by_label:
|
||||
resolved = type_def_index.get((prefix, name))
|
||||
|
||||
old_target = edge.get("target")
|
||||
if resolved and resolved != old_target:
|
||||
edge["target"] = resolved
|
||||
repointed_from.add(tgt)
|
||||
if isinstance(old_target, str) and old_target:
|
||||
repointed_from.add(old_target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
still_referenced: set[str] = set()
|
||||
for edge in all_edges:
|
||||
still_referenced.add(edge.get("source"))
|
||||
still_referenced.add(edge.get("target"))
|
||||
all_nodes[:] = [
|
||||
node for node in all_nodes
|
||||
if node.get("id") not in repointed_from or node.get("id") in still_referenced
|
||||
]
|
||||
|
||||
|
||||
def _resolve_csharp_type_references(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Arbitrate all C# ``inherits``/``implements``/``references`` targets.
|
||||
|
||||
The extractor emits provisional same-file bindings and sourceless stubs. This
|
||||
pass is the single soundness gate: it uses only graph-stamped namespace/import
|
||||
facts, keeps a binding only when the referenced simple name resolves to one
|
||||
in-scope real type definition, and otherwise leaves the edge on a dangling stub.
|
||||
"""
|
||||
_ = (per_file, paths)
|
||||
|
||||
def _is_cs_file(value: object) -> bool:
|
||||
return isinstance(value, str) and value.endswith(".cs")
|
||||
|
||||
def _metadata(value: object) -> dict:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
def _namespace(node: dict | None) -> str:
|
||||
metadata = _metadata((node or {}).get("metadata"))
|
||||
namespace = metadata.get("namespace", "")
|
||||
return namespace if isinstance(namespace, str) else ""
|
||||
|
||||
def _append_unique(items: list[str], value: str) -> None:
|
||||
if value not in items:
|
||||
items.append(value)
|
||||
|
||||
node_by_id = {
|
||||
node["id"]: node
|
||||
for node in all_nodes
|
||||
if isinstance(node.get("id"), str) and node.get("id")
|
||||
}
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
known_namespaces = {
|
||||
node.get("label")
|
||||
for node in all_nodes
|
||||
if node.get("type") == "namespace" and isinstance(node.get("label"), str)
|
||||
}
|
||||
|
||||
# Each using carries its lexical scope: ("file", None) applies file-wide;
|
||||
# ("namespace", scope_id) applies only where scope_id is in the ref's scope_chain.
|
||||
namespace_usings_by_file: dict[str, list[tuple[str, str, str | None]]] = {}
|
||||
aliases_by_file: dict[str, dict[str, list[tuple[str, str, str | None]]]] = {}
|
||||
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
if not (
|
||||
source_node
|
||||
and isinstance(source_node.get("label"), str)
|
||||
and source_node.get("label", "").endswith(".cs")
|
||||
):
|
||||
continue
|
||||
source_file = source_node.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
scope_kind = metadata.get("scope_kind") or "file"
|
||||
scope_id = metadata.get("scope_id")
|
||||
using_kind = metadata.get("using_kind")
|
||||
if using_kind == "namespace":
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = namespace_usings_by_file.setdefault(source_file, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
elif using_kind == "alias":
|
||||
alias = metadata.get("alias")
|
||||
if isinstance(alias, str) and alias:
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = aliases_by_file.setdefault(source_file, {}).setdefault(alias, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
|
||||
def _scope_chain(node: dict) -> list[str]:
|
||||
chain = _metadata(node.get("metadata")).get("scope_chain")
|
||||
return chain if isinstance(chain, list) else []
|
||||
|
||||
def _using_in_scope(scope_kind: str, scope_id: str | None, source_node: dict) -> bool:
|
||||
if scope_kind == "file":
|
||||
return True
|
||||
return scope_id is not None and scope_id in _scope_chain(source_node)
|
||||
|
||||
def _scopes_for(source_node: dict, source_file: str) -> list[str]:
|
||||
scopes: list[str] = []
|
||||
_append_unique(scopes, _namespace(source_node))
|
||||
_append_unique(scopes, "")
|
||||
for namespace, scope_kind, scope_id in namespace_usings_by_file.get(source_file, []):
|
||||
if _using_in_scope(scope_kind, scope_id, source_node):
|
||||
_append_unique(scopes, namespace)
|
||||
return scopes
|
||||
|
||||
def _resolve_alias(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
hits = set()
|
||||
for target_fqn, scope_kind, scope_id in aliases_by_file.get(source_file, {}).get(label, []):
|
||||
if not _using_in_scope(scope_kind, scope_id, source_node):
|
||||
continue
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
namespace, sep, simple_name = base_fqn.rpartition(".")
|
||||
if not sep:
|
||||
simple_name = namespace
|
||||
namespace = ""
|
||||
if not simple_name:
|
||||
continue
|
||||
hit = type_def_index.get((namespace, simple_name))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
|
||||
def _resolve_label(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
if label in aliases_by_file.get(source_file, {}):
|
||||
return _resolve_alias(label, source_node, source_file)
|
||||
candidates: list[str] = []
|
||||
for namespace in _scopes_for(source_node, source_file):
|
||||
hit = type_def_index.get((namespace, label))
|
||||
if hit and hit not in candidates:
|
||||
candidates.append(hit)
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
def _resolve_qualified(label: str, qualifier: object, source_node: dict, source_file: str) -> str | None:
|
||||
# Sound qualified resolution: an in-scope alias for Q shadows the namespace Q. For a qualified
|
||||
# ref Q.label, look up (alias_target_namespace, label). If no in-scope alias, fall through to an
|
||||
# exact known namespace. Dangle on ambiguity / no hit / unknown qualifier.
|
||||
if not isinstance(qualifier, str) or not qualifier:
|
||||
return None
|
||||
in_scope = [
|
||||
entry for entry in aliases_by_file.get(source_file, {}).get(qualifier, [])
|
||||
if _using_in_scope(entry[1], entry[2], source_node)
|
||||
]
|
||||
if in_scope:
|
||||
hits = set()
|
||||
for target_fqn, _scope_kind, _scope_id in in_scope:
|
||||
alias_ns = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
hit = type_def_index.get((alias_ns, label))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
if qualifier in known_namespaces:
|
||||
return type_def_index.get((qualifier, label))
|
||||
return None
|
||||
|
||||
def _is_placeholder(node: dict | None) -> bool:
|
||||
return bool(node) and not node.get("source_file")
|
||||
|
||||
def _is_csharp_relevant_target(node: dict) -> bool:
|
||||
if node.get("type") == "namespace":
|
||||
return True
|
||||
source_file = node.get("source_file")
|
||||
return not source_file or _is_cs_file(source_file)
|
||||
|
||||
def _label_for_type_ref_target(target_node: dict, source_file: str) -> str | None:
|
||||
label = target_node.get("label")
|
||||
if not isinstance(label, str) or not label:
|
||||
return None
|
||||
if not label.endswith(".cs"):
|
||||
return label
|
||||
|
||||
stem = label[:-3]
|
||||
for alias in aliases_by_file.get(source_file, {}):
|
||||
if alias.lower() == stem.lower() or _make_id(alias) == _make_id(stem):
|
||||
return alias
|
||||
return stem or None
|
||||
|
||||
def _dangling_stub_id(label: str, current_target: object) -> str:
|
||||
current = node_by_id.get(current_target)
|
||||
if _is_placeholder(current) and current.get("label") == label:
|
||||
return str(current_target)
|
||||
|
||||
for node in all_nodes:
|
||||
nid = node.get("id")
|
||||
if (
|
||||
isinstance(nid, str)
|
||||
and node.get("label") == label
|
||||
and _is_placeholder(node)
|
||||
):
|
||||
return nid
|
||||
|
||||
stem = _make_id(label)
|
||||
stub_id = stem
|
||||
if stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label)
|
||||
suffix = 2
|
||||
while stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label, str(suffix))
|
||||
suffix += 1
|
||||
node = {
|
||||
"id": stub_id,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
}
|
||||
all_nodes.append(node)
|
||||
node_by_id[stub_id] = node
|
||||
return stub_id
|
||||
|
||||
REPOINT_RELATIONS = {"implements", "inherits", "references"}
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") not in REPOINT_RELATIONS:
|
||||
continue
|
||||
source_file = edge.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
target_node = node_by_id.get(edge.get("target"))
|
||||
if not source_node or not target_node:
|
||||
continue
|
||||
if not _is_csharp_relevant_target(target_node):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
label = metadata.get("ref_token") or _label_for_type_ref_target(target_node, source_file)
|
||||
if not label:
|
||||
continue
|
||||
if metadata.get("qualified"):
|
||||
resolved = _resolve_qualified(label, metadata.get("ref_qualifier"), source_node, source_file)
|
||||
else:
|
||||
resolved = _resolve_label(label, source_node, source_file)
|
||||
target = edge.get("target")
|
||||
desired = resolved or _dangling_stub_id(label, target)
|
||||
if desired != target:
|
||||
edge["target"] = desired
|
||||
if isinstance(target, str) and _is_placeholder(target_node):
|
||||
repointed_from.add(target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
@@ -33,6 +33,27 @@ def _defs(result: dict, label: str) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def test_csharp_declaration_nodes_carry_enclosing_namespace(tmp_path: Path):
|
||||
block = _write(
|
||||
tmp_path / "block.cs",
|
||||
"namespace Game.Core { public class Damage {} }\n",
|
||||
)
|
||||
nested = _write(
|
||||
tmp_path / "nested.cs",
|
||||
"namespace Outer { namespace Inner { public class NestedDamage {} } }\n",
|
||||
)
|
||||
file_scoped = _write(
|
||||
tmp_path / "file_scoped.cs",
|
||||
"namespace FileScoped.Core;\npublic class FileScopedDamage {}\n",
|
||||
)
|
||||
result = extract([block, nested, file_scoped], cache_root=tmp_path)
|
||||
|
||||
assert _defs(result, "Damage")[0].get("metadata", {}).get("namespace") == "Game.Core"
|
||||
assert _defs(result, "NestedDamage")[0].get("metadata", {}).get("namespace") == "Outer.Inner"
|
||||
assert _defs(result, "FileScopedDamage")[0].get("metadata", {}).get("namespace") == "FileScoped.Core"
|
||||
assert _defs(result, "Damage")[0]["metadata"].get("scope_chain"), "lexical scope_chain must be stamped"
|
||||
|
||||
|
||||
def test_csharp_cross_file_inherits_resolves_to_real_def(tmp_path: Path):
|
||||
core = _write(tmp_path / "core.cs",
|
||||
"namespace Game.Core { public class Damage { public int Calc() { return 1; } } }\n")
|
||||
@@ -170,3 +191,379 @@ def test_csharp_using_alias_resolves_to_aliased_type(tmp_path: Path):
|
||||
assert all("core.cs" in d["source_file"] for d in damage), (
|
||||
"the alias `Dmg` must resolve to the real Game.Core.Damage def, not a shadow stub"
|
||||
)
|
||||
|
||||
|
||||
def test_csharp_namespace_nodes_canonical_and_discriminated(tmp_path: Path):
|
||||
a = _write(tmp_path / "a.cs", "namespace N { class A {} }\n")
|
||||
b = _write(tmp_path / "b.cs", "namespace N { class B {} }\n")
|
||||
nested = _write(tmp_path / "n.cs", "namespace Outer { namespace Inner { class C {} } }\n")
|
||||
result = extract([a, b, nested], cache_root=tmp_path)
|
||||
|
||||
ns = [n for n in result["nodes"] if n.get("type") == "namespace"]
|
||||
by_label = {}
|
||||
for n in ns:
|
||||
by_label.setdefault(n["label"], []).append(n)
|
||||
assert len(by_label.get("N", [])) == 1, "namespace N must be one canonical node across files"
|
||||
assert "Outer.Inner" in by_label, sorted(by_label)
|
||||
assert all(n["id"].startswith("csharp_namespace:") for n in ns), [n["id"] for n in ns]
|
||||
|
||||
|
||||
def test_csharp_import_edges_carry_using_kind(tmp_path: Path):
|
||||
f = _write(
|
||||
tmp_path / "a.cs",
|
||||
"using Game.Core;\nusing static System.Math;\nglobal using System;\n"
|
||||
"using X = Game.Core.Damage;\nclass Z {}\n",
|
||||
)
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
imports = {
|
||||
(e["metadata"].get("using_kind"), e["metadata"].get("target_fqn"), e["metadata"].get("alias"))
|
||||
for e in result["edges"]
|
||||
if e.get("relation") == "imports" and e.get("metadata")
|
||||
}
|
||||
assert ("namespace", "Game.Core", None) in imports, imports
|
||||
assert ("namespace", "System", None) in imports, imports
|
||||
assert ("static", "System.Math", None) in imports, imports
|
||||
assert ("alias", "Game.Core.Damage", "X") in imports, imports
|
||||
|
||||
|
||||
def test_csharp_import_edges_resolve_internal_namespace_and_alias(tmp_path: Path):
|
||||
core = _write(
|
||||
tmp_path / "core.cs",
|
||||
"namespace Game.Core { public class Damage {} }\n",
|
||||
)
|
||||
user = _write(
|
||||
tmp_path / "u.cs",
|
||||
"using Game.Core;\n"
|
||||
"using UnityEngine;\n"
|
||||
"using Dmg = Game.Core.Damage;\n"
|
||||
"using DMath = System.Math;\n"
|
||||
"using static Game.Core.Damage;\n"
|
||||
"class Z {}\n",
|
||||
)
|
||||
result = extract([core, user], cache_root=tmp_path)
|
||||
by_id = {n["id"]: n for n in result["nodes"]}
|
||||
imports = [
|
||||
(e["metadata"]["using_kind"], e["metadata"].get("target_fqn"), by_id.get(e["target"]))
|
||||
for e in result["edges"]
|
||||
if e.get("relation") == "imports" and (e.get("metadata") or {}).get("using_kind")
|
||||
]
|
||||
|
||||
assert ("namespace", "Game.Core", "namespace") in [
|
||||
(kind, fqn, target.get("type") if target else None)
|
||||
for kind, fqn, target in imports
|
||||
]
|
||||
assert ("namespace", "UnityEngine", None) in [
|
||||
(kind, fqn, target.get("type") if target else None)
|
||||
for kind, fqn, target in imports
|
||||
]
|
||||
assert ("alias", "Game.Core.Damage", "Damage") in [
|
||||
(kind, fqn, target.get("label") if target else None)
|
||||
for kind, fqn, target in imports
|
||||
]
|
||||
assert ("alias", "System.Math", None) in [
|
||||
(kind, fqn, target.get("label") if target else None)
|
||||
for kind, fqn, target in imports
|
||||
]
|
||||
assert ("static", "Game.Core.Damage", None) in [
|
||||
(kind, fqn, target.get("label") if target else None)
|
||||
for kind, fqn, target in imports
|
||||
]
|
||||
assert not [
|
||||
n for n in result["nodes"]
|
||||
if not n.get("source_file") and n.get("label") in {"Game.Core", "Game.Core.Damage"}
|
||||
]
|
||||
|
||||
|
||||
def test_csharp_qualified_base_ref_is_flagged(tmp_path: Path):
|
||||
f = _write(tmp_path / "a.cs", "namespace N { class T {} class Use : B.T {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
assert any((e.get("metadata") or {}).get("qualified") for e in result["edges"]), \
|
||||
"the qualified base ref B.T must carry metadata.qualified"
|
||||
|
||||
|
||||
def test_csharp_one_file_same_name_no_collision_flag(tmp_path: Path):
|
||||
# ns_collision is gone: A.T and B.T are distinct nodes with no ns_collision metadata.
|
||||
dup = _write(tmp_path / "dup.cs", "namespace A { class T {} } namespace B { class T {} }\n")
|
||||
result = extract([dup], cache_root=tmp_path)
|
||||
tnodes = [n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file")]
|
||||
assert len({n["id"] for n in tnodes}) == 2, tnodes
|
||||
assert not any((n.get("metadata") or {}).get("ns_collision") for n in tnodes), \
|
||||
"ns_collision must no longer be stamped"
|
||||
|
||||
|
||||
def test_csharp_type_parameter_emits_no_reference(tmp_path: Path):
|
||||
f = _write(tmp_path / "a.cs", "namespace N { class T {} class Box<T> { T value; } }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
real_t = {n["id"] for n in result["nodes"] if n.get("label") == "T" and n.get("source_file")}
|
||||
box_to_t = [
|
||||
e for e in result["edges"]
|
||||
if e.get("relation") in ("references", "inherits", "implements")
|
||||
and e.get("target") in real_t
|
||||
and "box" in str(e.get("source", "")).lower()
|
||||
]
|
||||
assert not box_to_t, f"type parameter T must not produce a ref to the real N.T: {box_to_t}"
|
||||
|
||||
|
||||
def test_csharp_nested_type_carries_metadata(tmp_path: Path):
|
||||
f = _write(tmp_path / "a.cs", "namespace N { class Outer { class Inner {} } }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
inner = [n for n in result["nodes"] if n.get("label") == "Inner"]
|
||||
assert inner and inner[0].get("metadata", {}).get("is_nested_type") is True, inner
|
||||
|
||||
|
||||
def test_csharp_cross_namespace_ref_not_misbound(tmp_path: Path):
|
||||
# Use in namespace B must NOT bind to C.T (B never opens C) — even though T is globally unique.
|
||||
f = _write(tmp_path / "x.cs", "namespace B { class Use : T {} } namespace C { class T {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "inherits", "T") if t.get("source_file")]
|
||||
assert not resolved, f"Use:T in B must not bind C.T: {resolved}"
|
||||
|
||||
|
||||
def test_csharp_same_file_cross_namespace_ref_not_misbound(tmp_path: Path):
|
||||
# Same file, T defined in B, Use in C : T — must NOT bind B.T (the eager same-file binding case).
|
||||
f = _write(tmp_path / "x.cs", "namespace B { class T {} } namespace C { class Use : T {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "inherits", "T") if t.get("source_file")]
|
||||
assert not resolved, f"same-file Use:T in C must not bind B.T: {resolved}"
|
||||
|
||||
|
||||
def test_csharp_inherits_does_not_bind_namespace_node(tmp_path: Path):
|
||||
# class Use : Game where Game is a namespace — must NOT bind the namespace node (Chunk-1 review B1).
|
||||
f = _write(tmp_path / "y.cs", "namespace Game { class Damage {} class Use : Game {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
nsids = {n["id"] for n in result["nodes"] if n.get("type") == "namespace"}
|
||||
bad = [e for e in result["edges"] if e.get("relation") == "inherits" and e.get("target") in nsids]
|
||||
assert not bad, f"inherits must not target a namespace node: {bad}"
|
||||
|
||||
|
||||
def test_csharp_qualified_ref_unknown_qualifier_dangles(tmp_path: Path):
|
||||
# B.T where B is neither a known namespace nor an alias -> must NOT bind A.T (sound dangle).
|
||||
f = _write(tmp_path / "a.cs", "namespace A { class T {} class Use : B.T {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "inherits", "T") if t.get("source_file")]
|
||||
assert not resolved, f"unknown-qualifier B.T must not bind A.T: {resolved}"
|
||||
|
||||
|
||||
def test_csharp_qualified_ref_known_namespace_resolves(tmp_path: Path):
|
||||
a = _write(tmp_path / "n.cs", "namespace N { class T {} }\n")
|
||||
b = _write(tmp_path / "m.cs", "namespace M { class Use : N.T {} }\n")
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
n_t = next(n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file"))
|
||||
use = next(n for n in result["nodes"] if n.get("label") == "Use")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (use["id"], n_t["id"]) in inh, "M.Use : N.T must bind N.T"
|
||||
|
||||
|
||||
def test_csharp_qualified_generic_resolves_to_real_def(tmp_path: Path):
|
||||
# N.Box<int> previously emitted a junk 'B<C>'-style label; it must resolve to the real N.Box def.
|
||||
f = _write(tmp_path / "g.cs", "namespace N { class Box<TI> {} class Use { N.Box<int> b; } }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
box = next(n for n in result["nodes"] if n.get("label") == "Box" and n.get("source_file"))
|
||||
use = next(n for n in result["nodes"] if n.get("label") == "Use")
|
||||
refs = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "references"}
|
||||
assert (use["id"], box["id"]) in refs, "N.Box<int> field must resolve to the real N.Box def"
|
||||
assert not any("<" in (n.get("label") or "") for n in result["nodes"]), \
|
||||
"no node should carry a junk generic label"
|
||||
|
||||
|
||||
def test_csharp_qualified_alias_namespace_resolves(tmp_path: Path):
|
||||
# using B = X.Y (namespace alias) then B.T -> resolves the type T in namespace X.Y.
|
||||
a = _write(tmp_path / "n.cs", "namespace X.Y { class T {} }\n")
|
||||
b = _write(tmp_path / "m.cs", "using B = X.Y;\nnamespace M { class Use : B.T {} }\n")
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
t = next(n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file"))
|
||||
use = next(n for n in result["nodes"] if n.get("label") == "Use")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (use["id"], t["id"]) in inh, "B.T with `using B = X.Y;` must resolve to X.Y.T"
|
||||
|
||||
|
||||
def test_csharp_qualified_out_of_scope_alias_falls_through_to_namespace(tmp_path: Path):
|
||||
# B is a real namespace AND an out-of-scope alias (declared in A, used in M):
|
||||
# B.T in M must resolve to namespace B's T, not dangle.
|
||||
a = _write(tmp_path / "b.cs", "namespace B { class T {} }\n")
|
||||
c = _write(tmp_path / "m.cs",
|
||||
"namespace A { using B = X.Y; }\nnamespace M { class Use : B.T {} }\n")
|
||||
result = extract([a, c], cache_root=tmp_path)
|
||||
b_t = next(n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file"))
|
||||
use = next(n for n in result["nodes"] if n.get("label") == "Use")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (use["id"], b_t["id"]) in inh, "out-of-scope alias B must fall through to namespace B"
|
||||
|
||||
|
||||
def test_csharp_qualified_in_scope_alias_shadows_namespace(tmp_path: Path):
|
||||
# B is both a real namespace AND an in-scope alias (B = X.Y) in A's block; a later out-of-scope
|
||||
# alias (B = Z.Q in C) must not overwrite it. Good : B.T -> X.Y.T, not namespace B's T.
|
||||
a = _write(tmp_path / "xy.cs", "namespace X.Y { class T {} }\n")
|
||||
b = _write(tmp_path / "b.cs", "namespace B { class T {} }\n")
|
||||
c = _write(tmp_path / "use.cs",
|
||||
"namespace A { using B = X.Y; class Good : B.T {} }\nnamespace C { using B = Z.Q; }\n")
|
||||
result = extract([a, b, c], cache_root=tmp_path)
|
||||
xy_t = next(n for n in result["nodes"]
|
||||
if n.get("label") == "T" and (n.get("metadata") or {}).get("namespace") == "X.Y")
|
||||
b_t = next(n for n in result["nodes"]
|
||||
if n.get("label") == "T" and (n.get("metadata") or {}).get("namespace") == "B")
|
||||
good = next(n for n in result["nodes"] if n.get("label") == "Good")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (good["id"], xy_t["id"]) in inh, "in-scope alias B=X.Y must resolve B.T to X.Y.T"
|
||||
assert (good["id"], b_t["id"]) not in inh, "must NOT bind namespace B's T"
|
||||
|
||||
|
||||
def test_csharp_one_file_same_name_binds_own_namespace(tmp_path: Path):
|
||||
# T in both A and B of one file; Use:T in B must bind B.T (its own namespace), not A.T.
|
||||
f = _write(
|
||||
tmp_path / "c.cs",
|
||||
"namespace A { class T {} } namespace B { class T {} class Use : T {} }\n",
|
||||
)
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
b_t = next(n for n in result["nodes"]
|
||||
if n.get("label") == "T" and (n.get("metadata") or {}).get("namespace") == "B")
|
||||
a_t = next(n for n in result["nodes"]
|
||||
if n.get("label") == "T" and (n.get("metadata") or {}).get("namespace") == "A")
|
||||
use = next(n for n in result["nodes"] if n.get("label") == "Use")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (use["id"], b_t["id"]) in inh, "Use:T in B must bind B.T"
|
||||
assert (use["id"], a_t["id"]) not in inh, "Use:T must NOT bind A.T"
|
||||
|
||||
|
||||
def test_csharp_nested_type_not_importable_via_using(tmp_path: Path):
|
||||
# Inner is nested in Outer; `using N;` does not bring Inner into scope as a bare member.
|
||||
a = _write(tmp_path / "a.cs", "namespace N { class Outer { class Inner {} } }\n")
|
||||
b = _write(tmp_path / "b.cs", "using N;\nnamespace M { class Use { Inner x; } }\n")
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "references", "Inner") if t.get("source_file")]
|
||||
assert not resolved, f"nested Inner must not resolve via `using N;`: {resolved}"
|
||||
|
||||
|
||||
def test_csharp_generic_alias_resolves_to_base_type(tmp_path: Path):
|
||||
core = _write(tmp_path / "core.cs", "namespace N { class Box {} }\n")
|
||||
use = _write(tmp_path / "use.cs", "using Bx = N.Box<int>;\nclass Use : Bx {}\n")
|
||||
result = extract([core, use], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "inherits", "Box") if t.get("source_file")]
|
||||
assert resolved, "generic alias `using Bx = N.Box<int>;` must resolve to the real Box def"
|
||||
|
||||
|
||||
def test_csharp_type_ref_never_targets_a_file_label(tmp_path: Path):
|
||||
core = _write(tmp_path / "core.cs", "namespace N { class Box {} }\n")
|
||||
b = _write(tmp_path / "b.cs", "using B = N.Box;\nclass Use : B {}\n")
|
||||
result = extract([core, b], cache_root=tmp_path)
|
||||
bad = [
|
||||
e for e in result["edges"]
|
||||
if e.get("relation") in ("inherits", "implements", "references")
|
||||
and str(_node_by_id(result, e.get("target")).get("label", "") if _node_by_id(result, e.get("target")) else "").endswith(".cs")
|
||||
]
|
||||
assert not bad, f"a C# type ref must not target a .cs file-labeled node: {bad}"
|
||||
|
||||
|
||||
def test_csharp_type_ref_edges_carry_ref_token(tmp_path: Path):
|
||||
core = _write(tmp_path / "core.cs", "namespace N { class Base {} }\n")
|
||||
use = _write(tmp_path / "use.cs", "using N;\nnamespace M { class Use : Base {} }\n")
|
||||
result = extract([core, use], cache_root=tmp_path)
|
||||
inh = [
|
||||
e for e in result["edges"]
|
||||
if e.get("relation") == "inherits"
|
||||
and "use" in str(e.get("source", "")).lower()
|
||||
]
|
||||
assert inh, "expected the Use : Base inherits edge"
|
||||
assert any((e.get("metadata") or {}).get("ref_token") == "Base" for e in inh), \
|
||||
"the inherits edge must carry metadata.ref_token == 'Base'"
|
||||
|
||||
|
||||
def test_csharp_alias_matching_file_stem_resolves_via_token(tmp_path: Path):
|
||||
# alias name == file stem (B in b.cs) used to corrupt the target label; the
|
||||
# ref token makes the arbiter resolve it correctly regardless.
|
||||
core = _write(tmp_path / "core.cs", "namespace N { class Box {} }\n")
|
||||
b = _write(tmp_path / "b.cs", "using B = N.Box;\nclass Use : B {}\n")
|
||||
result = extract([core, b], cache_root=tmp_path)
|
||||
resolved = [t for t in _targets(result, "inherits", "Box") if t.get("source_file")]
|
||||
assert resolved, "Use : B (alias B == file stem) must resolve to the real Box def"
|
||||
|
||||
|
||||
def test_csharp_same_name_diff_namespace_have_distinct_ids(tmp_path: Path):
|
||||
# The id now carries the namespace, so A.T and B.T are distinct nodes (resolution unchanged here).
|
||||
f = _write(tmp_path / "x.cs", "namespace A { class T {} } namespace B { class T {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
ids = {n["id"] for n in result["nodes"] if n.get("label") == "T" and n.get("source_file")}
|
||||
assert len(ids) == 2, f"A.T and B.T must be distinct nodes: {ids}"
|
||||
|
||||
|
||||
def test_csharp_global_scope_id_unchanged(tmp_path: Path):
|
||||
# A C# type at global scope (no namespace) keeps the bare stem+name id (empty namespace dropped by make_id).
|
||||
from graphify.extractors.base import _make_id, _file_stem
|
||||
f = _write(tmp_path / "g.cs", "class Glob {}\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
glob = next(n for n in result["nodes"] if n.get("label") == "Glob")
|
||||
stem = _file_stem(tmp_path / "g.cs")
|
||||
if "/" in stem:
|
||||
stem = stem.rsplit("/", 1)[-1]
|
||||
assert glob["id"] == _make_id(stem, "Glob"), glob
|
||||
assert "namespace" not in (glob.get("metadata") or {})
|
||||
|
||||
|
||||
def test_csharp_namespaced_id_carries_namespace_segment(tmp_path: Path):
|
||||
f = _write(tmp_path / "n.cs", "namespace Game.Core { class Order {} }\n")
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
order = next(n for n in result["nodes"] if n.get("label") == "Order")
|
||||
assert order["id"].endswith("order") and "game_core" in order["id"], order["id"]
|
||||
assert (order.get("metadata") or {}).get("namespace") == "Game.Core"
|
||||
|
||||
def test_csharp_two_namespaces_each_resolve_own_type(tmp_path: Path):
|
||||
f = _write(
|
||||
tmp_path / "two.cs",
|
||||
"namespace A { class T {} class UseA : T {} } namespace B { class T {} class UseB : T {} }\n",
|
||||
)
|
||||
result = extract([f], cache_root=tmp_path)
|
||||
|
||||
def _n(label, ns):
|
||||
return next(x for x in result["nodes"]
|
||||
if x.get("label") == label and (x.get("metadata") or {}).get("namespace") == ns)
|
||||
|
||||
a_t, b_t, use_a, use_b = _n("T", "A"), _n("T", "B"), _n("UseA", "A"), _n("UseB", "B")
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (use_a["id"], a_t["id"]) in inh and (use_b["id"], b_t["id"]) in inh
|
||||
assert (use_a["id"], b_t["id"]) not in inh and (use_b["id"], a_t["id"]) not in inh
|
||||
|
||||
|
||||
def test_csharp_file_level_using_applies_across_blocks(tmp_path: Path):
|
||||
a = _write(tmp_path / "n.cs", "namespace N { class T {} }\n")
|
||||
b = _write(tmp_path / "u.cs", "using N;\nnamespace A { class X : T {} } namespace B { class Y : T {} }\n")
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
resolved = [t["id"] for t in _targets(result, "inherits", "T") if t.get("source_file")]
|
||||
assert len(resolved) >= 2, f"file-level using N must reach both A.X and B.Y: {resolved}"
|
||||
|
||||
|
||||
def test_csharp_namespace_scoped_using_isolated_to_sibling_block(tmp_path: Path):
|
||||
a = _write(tmp_path / "n.cs", "namespace N { class T {} }\n")
|
||||
b = _write(
|
||||
tmp_path / "u.cs",
|
||||
"namespace A { using N; class Good : T {} }\nnamespace A { class Bad : T {} }\n",
|
||||
)
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
good = next(n for n in result["nodes"] if n.get("label") == "Good")
|
||||
bad = next(n for n in result["nodes"] if n.get("label") == "Bad")
|
||||
n_t = next(n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file"))
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (good["id"], n_t["id"]) in inh, "Good (same block as using N) must bind N.T"
|
||||
assert (bad["id"], n_t["id"]) not in inh, "Bad (sibling block, no using) must NOT bind N.T"
|
||||
|
||||
|
||||
def test_csharp_using_flows_into_nested_block(tmp_path: Path):
|
||||
a = _write(tmp_path / "n.cs", "namespace N { class T {} }\n")
|
||||
b = _write(tmp_path / "u.cs", "namespace A { using N; namespace B { class Inner : T {} } }\n")
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
resolved = [t["id"] for t in _targets(result, "inherits", "T") if t.get("source_file")]
|
||||
assert resolved, "using N in outer block A must flow into nested block B"
|
||||
|
||||
|
||||
def test_csharp_alias_using_scoped_to_its_block(tmp_path: Path):
|
||||
a = _write(tmp_path / "n.cs", "namespace N { class T {} }\n")
|
||||
b = _write(
|
||||
tmp_path / "u.cs",
|
||||
"namespace A { using AliasT = N.T; class Good : AliasT {} }\nnamespace A { class Bad : AliasT {} }\n",
|
||||
)
|
||||
result = extract([a, b], cache_root=tmp_path)
|
||||
good = next(n for n in result["nodes"] if n.get("label") == "Good")
|
||||
bad = next(n for n in result["nodes"] if n.get("label") == "Bad")
|
||||
n_t = next(n for n in result["nodes"] if n.get("label") == "T" and n.get("source_file"))
|
||||
inh = {(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == "inherits"}
|
||||
assert (good["id"], n_t["id"]) in inh, "Good must bind N.T via the in-block alias"
|
||||
assert (bad["id"], n_t["id"]) not in inh, "Bad (sibling block) must NOT see the alias"
|
||||
|
||||
Reference in New Issue
Block a user