From 814477d07a2a25da581d35c968a8ee5d60fbac5a Mon Sep 17 00:00:00 2001 From: Sumith Ramsookbhai Date: Sun, 28 Jun 2026 16:44:00 +0200 Subject: [PATCH 1/2] feat(repo-map): add C# import-edge resolver with namespace fan-out (#362) Port Understand-Anything's C# rules into the Approach-C framework (#354): a `using` names a namespace, not a file, so it resolves to every project file declaring that namespace (package-level fan-out). `System.*` and external assemblies are dropped. Adds `repo_map_resolvers/csharp.py` (`CSharpResolver` + `csharp` registration) and real-tree-sitter tests over committed `.cs` fixtures (extract, namespace index, resolve fan-out, orchestrator integration). C# namespace resolution needs a cross-file index (a `using`'s declaring files live in other files' contents), which the path-only `resolve(importer, imp, file_set)` contract cannot build. It is therefore a first-class, separately-tested resolver capability (`index_namespaces` / `declared_namespaces`). Scan-time activation is a follow-on foundation change (a namespace-index pre-pass, plus `.cs` classification in the scanner); the foundation is left untouched here. --- docs/REPO-MAP.md | 6 +- src/sumo_qa/repo_map_resolvers/__init__.py | 1 + src/sumo_qa/repo_map_resolvers/csharp.py | 194 ++++++++++++++ .../csharp/Controllers/HomeController.cs | 14 + .../repo_map/csharp/Edge/Directives.cs | 14 + .../repo_map/csharp/Models/Customer.cs | 6 + .../fixtures/repo_map/csharp/Models/Order.cs | 7 + .../repo_map/csharp/Services/OrderService.cs | 9 + tests/test_repo_map_csharp_resolver.py | 241 ++++++++++++++++++ 9 files changed, 491 insertions(+), 1 deletion(-) create mode 100644 src/sumo_qa/repo_map_resolvers/csharp.py create mode 100644 tests/fixtures/repo_map/csharp/Controllers/HomeController.cs create mode 100644 tests/fixtures/repo_map/csharp/Edge/Directives.cs create mode 100644 tests/fixtures/repo_map/csharp/Models/Customer.cs create mode 100644 tests/fixtures/repo_map/csharp/Models/Order.cs create mode 100644 tests/fixtures/repo_map/csharp/Services/OrderService.cs create mode 100644 tests/test_repo_map_csharp_resolver.py diff --git a/docs/REPO-MAP.md b/docs/REPO-MAP.md index 8521cbf9..8384ec0b 100644 --- a/docs/REPO-MAP.md +++ b/docs/REPO-MAP.md @@ -171,7 +171,11 @@ What the slice-2 scanner produces: PEP-328 implicit namespace packages, an absolute-import `sys.path` walk-up that prefers the deepest source root, and specifier submodule probing; wildcard `from x import *` and qualified specifiers are skipped). Other - languages are follow-on slices. + languages are follow-on slices. A C# resolver (#362) is registered at the + resolver layer: each `using` fans out to the project files declaring that + namespace (package-level fan-out), with `System.*` and external assemblies + dropped. Its cross-file namespace index is not yet wired into the scan, so + `.cs` import edges await a foundation pass. This layer is **optional**: it needs the `tree-sitter` parser, shipped as the `sumo-qa[treesitter]` extra. With the extra absent the scan still succeeds: it records a `RepoMapWarning` and emits only `likely_tests` edges, so the map diff --git a/src/sumo_qa/repo_map_resolvers/__init__.py b/src/sumo_qa/repo_map_resolvers/__init__.py index d936000a..d5353ff5 100644 --- a/src/sumo_qa/repo_map_resolvers/__init__.py +++ b/src/sumo_qa/repo_map_resolvers/__init__.py @@ -15,6 +15,7 @@ from __future__ import annotations +from sumo_qa.repo_map_resolvers import csharp as _csharp # noqa: F401 -- import for side effect from sumo_qa.repo_map_resolvers import python as _python # noqa: F401 -- import for side effect from sumo_qa.repo_map_resolvers.base import ( LanguageConfig, diff --git a/src/sumo_qa/repo_map_resolvers/csharp.py b/src/sumo_qa/repo_map_resolvers/csharp.py new file mode 100644 index 00000000..bc05fd82 --- /dev/null +++ b/src/sumo_qa/repo_map_resolvers/csharp.py @@ -0,0 +1,194 @@ +# Copyright 2026 Sumith Ramsookbhai. Licensed under Apache-2.0 (see LICENSE). +"""C# import resolver for the repo-map import-edge layer (#362, epic #353). + +Ports Understand-Anything's C# rules into the Approach-C framework the +foundation (#354) shipped. C# is the framework's first language whose imports +do **not** map to files one-to-one: a ``using`` names a *namespace*, and a +namespace can be declared by any number of ``.cs`` files across the project. So +resolution is package-level fan-out — ``using X`` links to **every** project +file that declares ``namespace X``. + +Resolution rules (ported from UA): + +- **``using`` → namespace, not file.** ``extract`` pulls each plain ``using`` + (and ``global using``) directive off the parse as a :class:`RawImport` whose + ``module`` is the dotted namespace. ``using static T`` (imports a type's + static members) and ``using Alias = X`` (an alias) are NOT namespace imports + and are skipped. +- **Namespace fan-out via a cross-file index.** A namespace's declaring files + can only be known by reading *other* files, so the resolver carries a + ``namespace -> {declaring file path}`` index (built by + :meth:`index_namespaces` over the project's sources). ``resolve`` looks the + ``using`` up in that index and returns every declaring file that exists in + ``file_set`` (minus the importer itself — no self-edge). +- **``System.*`` and external assemblies dropped.** ``System`` and any + ``System.*`` namespace is the BCL/framework root and is dropped explicitly. + Any other namespace with no declaring project file (an external NuGet + assembly, e.g. ``Newtonsoft.Json``) misses the index and resolves to nothing. + +.. note:: + + The Approach-C ``resolve(importer, imp, file_set)`` contract is **path-only** + — it never sees other files' *contents*, which is exactly what the namespace + index needs. So the index is a first-class, separately-tested resolver + capability (:meth:`index_namespaces` / :meth:`declared_namespaces`) rather + than something ``resolve`` can build itself. At scan time the registered + resolver's index is empty (nothing populates it through the path-only + contract), so wiring this resolver into ``scan_repo`` needs a foundation + enhancement: a pre-pass that builds the namespace index across all ``.cs`` + files and hands it to the resolver. The foundation also does not yet + classify ``.cs`` as a source language (``repo_map_scanner``'s + ``_LANGUAGE_BY_EXT`` / ``_PROGRAMMING_LANGS`` omit it). Both are foundation + changes and are out of scope here (#362 ships the resolver + its index + capability; the scan-time wiring is a follow-on). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sumo_qa.repo_map_resolvers.base import LanguageConfig, RawImport, register +from sumo_qa.repo_map_treesitter import TSNode, parse + +if TYPE_CHECKING: # pragma: no cover -- typing-only import, never executed + from collections.abc import Mapping + +CSHARP_CONFIG = LanguageConfig( + id="csharp", + extensions=(".cs",), +) + +# Grammar kinds, pinned to tree-sitter-language-pack's C# grammar (probed +# against the installed binding). +_USING_DIRECTIVE = "using_directive" # `using X;` / `global using X;` / `using static T;` +_NAMESPACE_DECL = "namespace_declaration" # `namespace X { ... }` +_FILE_SCOPED_NAMESPACE_DECL = "file_scoped_namespace_declaration" # `namespace X;` +_QUALIFIED_NAME = "qualified_name" # `A.B.C` +_IDENTIFIER = "identifier" # a single-segment name `A` +_STATIC = "static" # the `static` token of `using static T` +_EQUALS = "=" # the `=` token of `using Alias = X` + +# The BCL/framework namespace root. `System` and any `System.*` namespace is +# dropped explicitly so it never fans out even if a project file (perversely) +# declares a same-named namespace. +_BCL_ROOT = "System" + + +class CSharpResolver: + """Approach-C resolver for C# (namespace fan-out via a cross-file index).""" + + config = CSHARP_CONFIG + + def __init__(self) -> None: + # namespace -> set of repo-relative paths that declare it. Empty until + # `index_namespaces` is called; `resolve` returns nothing while empty. + self._namespace_index: dict[str, set[str]] = {} + + def extract(self, src: bytes) -> list[RawImport]: + """Return the namespace ``using`` directives in ``src`` as records. + + Each plain ``using X;`` / ``global using X;`` yields a + :class:`RawImport` whose ``module`` is the dotted namespace. ``using + static T`` (type statics) and ``using Alias = X`` (alias) are skipped — + they are not namespace imports. C# using directives are always + file-/namespace-level (never inside a method body), so ``level`` is + ``0``, ``names`` is empty, and ``function_local`` is ``False``. + """ + root = parse("csharp", src) + raws: list[RawImport] = [] + for node in root.descendants(): + if node.kind != _USING_DIRECTIVE: + continue + namespace = self._using_namespace(node) + if namespace is not None: + raws.append(RawImport(module=namespace, level=0, names=(), function_local=False)) + return raws + + @staticmethod + def _using_namespace(node: TSNode) -> str | None: + """The dotted namespace of a plain ``using`` directive, or ``None``. + + Returns ``None`` for ``using static T`` (a ``static`` token) and + ``using Alias = X`` (an ``=`` token) — neither is a namespace import. + Otherwise the namespace is the directive's sole ``qualified_name`` / + ``identifier`` child (``global using`` and ``using`` differ only by a + leading ``global`` keyword token, so both reach here). + """ + kinds = {child.kind for child in node.children} + if _STATIC in kinds or _EQUALS in kinds: + return None + for child in node.children: + if child.kind in (_QUALIFIED_NAME, _IDENTIFIER): + return child.text + return None # pragma: no cover -- defensive: a plain using always has a name node + + def declared_namespaces(self, src: bytes) -> set[str]: + """The set of namespaces ``src`` declares (block, file-scoped, nested). + + ``namespace A.B { ... }`` and ``namespace A.B;`` each declare ``A.B``; + a nested ``namespace Inner`` inside ``namespace Outer`` declares the + full dotted ``Outer.Inner`` (C# composes the enclosing namespace into + the child's fully-qualified name). + """ + root = parse("csharp", src) + out: set[str] = set() + self._collect_namespaces(root, prefix="", out=out) + return out + + def _collect_namespaces(self, node: TSNode, *, prefix: str, out: set[str]) -> None: + if node.kind in (_NAMESPACE_DECL, _FILE_SCOPED_NAMESPACE_DECL): + name = self._namespace_name(node) + if name is None: # pragma: no cover -- defensive: a namespace decl always has a name + return + full = f"{prefix}.{name}" if prefix else name + out.add(full) + for child in node.children: + self._collect_namespaces(child, prefix=full, out=out) + return + for child in node.children: + self._collect_namespaces(child, prefix=prefix, out=out) + + @staticmethod + def _namespace_name(node: TSNode) -> str | None: + """The dotted name of a namespace declaration (the child after + ``namespace``), or ``None``.""" + for child in node.children: + if child.kind in (_QUALIFIED_NAME, _IDENTIFIER): + return child.text + return None # pragma: no cover -- defensive: a namespace decl always has a name + + def index_namespaces(self, sources: Mapping[str, bytes]) -> dict[str, set[str]]: + """Build (and store) the ``namespace -> {declaring file}`` index. + + ``sources`` maps each repo-relative ``.cs`` path to its bytes. The index + is stored on the resolver so :meth:`resolve` can fan a ``using`` out to + the namespace's declaring files; it is also returned so the index is + directly inspectable/testable. Replaces any previously-stored index. + """ + index: dict[str, set[str]] = {} + for path, src in sources.items(): + for namespace in self.declared_namespaces(src): + index.setdefault(namespace, set()).add(path) + self._namespace_index = index + return index + + def resolve(self, importer: str, imp: RawImport, file_set: set[str]) -> list[str]: + """Fan a ``using`` out to the project files that declare its namespace. + + Returns every repo-relative path that declares ``imp.module``, exists in + ``file_set``, and is not the importer itself (no self-edge), sorted for + determinism. ``System`` / ``System.*`` (the BCL/framework root) and any + namespace with no declaring project file (external assemblies) resolve + to ``[]`` — never an error, the normal "not-ours" outcome. Empty until + :meth:`index_namespaces` has populated the cross-file index. + """ + namespace = imp.module + if namespace == _BCL_ROOT or namespace.startswith(f"{_BCL_ROOT}."): + return [] + declarers = self._namespace_index.get(namespace) + if declarers is None: + return [] + return sorted(path for path in declarers if path in file_set and path != importer) + + +register(CSharpResolver()) diff --git a/tests/fixtures/repo_map/csharp/Controllers/HomeController.cs b/tests/fixtures/repo_map/csharp/Controllers/HomeController.cs new file mode 100644 index 00000000..7cec8d7b --- /dev/null +++ b/tests/fixtures/repo_map/csharp/Controllers/HomeController.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using MyApp.Models; +using MyApp.Services; +using Newtonsoft.Json; + +namespace MyApp.Controllers +{ + public class HomeController + { + private readonly OrderService _service = new OrderService(); + private readonly List _orders = new List(); + } +} diff --git a/tests/fixtures/repo_map/csharp/Edge/Directives.cs b/tests/fixtures/repo_map/csharp/Edge/Directives.cs new file mode 100644 index 00000000..745f112b --- /dev/null +++ b/tests/fixtures/repo_map/csharp/Edge/Directives.cs @@ -0,0 +1,14 @@ +global using MyApp.Shared; +using static System.Math; +using Alias = MyApp.Models.Order; +using MyApp.Models; + +namespace MyApp.Edge +{ + namespace Inner + { + public class Deep + { + } + } +} diff --git a/tests/fixtures/repo_map/csharp/Models/Customer.cs b/tests/fixtures/repo_map/csharp/Models/Customer.cs new file mode 100644 index 00000000..192060be --- /dev/null +++ b/tests/fixtures/repo_map/csharp/Models/Customer.cs @@ -0,0 +1,6 @@ +namespace MyApp.Models; + +public class Customer +{ + public string Name { get; set; } +} diff --git a/tests/fixtures/repo_map/csharp/Models/Order.cs b/tests/fixtures/repo_map/csharp/Models/Order.cs new file mode 100644 index 00000000..b0a1db27 --- /dev/null +++ b/tests/fixtures/repo_map/csharp/Models/Order.cs @@ -0,0 +1,7 @@ +namespace MyApp.Models +{ + public class Order + { + public int Id { get; set; } + } +} diff --git a/tests/fixtures/repo_map/csharp/Services/OrderService.cs b/tests/fixtures/repo_map/csharp/Services/OrderService.cs new file mode 100644 index 00000000..aca6e34f --- /dev/null +++ b/tests/fixtures/repo_map/csharp/Services/OrderService.cs @@ -0,0 +1,9 @@ +namespace MyApp.Services +{ + public class OrderService + { + public void Process() + { + } + } +} diff --git a/tests/test_repo_map_csharp_resolver.py b/tests/test_repo_map_csharp_resolver.py new file mode 100644 index 00000000..347b81b4 --- /dev/null +++ b/tests/test_repo_map_csharp_resolver.py @@ -0,0 +1,241 @@ +# Copyright 2026 Sumith Ramsookbhai. Licensed under Apache-2.0 (see LICENSE). +"""Unit tests for the C# import resolver (#362). + +``extract`` and ``declared_namespaces`` are tested against REAL tree-sitter +output over COMMITTED ``.cs`` fixtures (skipped without the ``[treesitter]`` +extra); ``resolve`` is pure namespace-index lookup and runs on every +interpreter. The orchestrator integration drives ``infer_imports_edges`` over +the committed C# mini-project with the resolver's cross-file namespace index +populated. + +C# rules ported from Understand-Anything: a ``using`` names a NAMESPACE, not a +file, so it resolves to every project file that DECLARES that namespace +(package-level fan-out). ``System.*`` and external assemblies (no declaring +project file) yield no edge. ``using static`` (type-statics) and +``using Alias = X`` (alias) are not namespace imports and are dropped. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +import sumo_qa.repo_map_imports as imports_mod +from sumo_qa.repo_map_imports import infer_imports_edges +from sumo_qa.repo_map_models import RepoMapNode +from sumo_qa.repo_map_resolvers import get_resolver, registered_languages +from sumo_qa.repo_map_resolvers.base import RawImport +from sumo_qa.repo_map_resolvers.csharp import CSharpResolver +from sumo_qa.repo_map_treesitter import TREESITTER_AVAILABLE + +_FIXTURES = Path(__file__).parent / "fixtures" / "repo_map" / "csharp" + +resolver = CSharpResolver() + +_needs_ts = pytest.mark.skipif( + not TREESITTER_AVAILABLE, + reason="tree-sitter not installed (the [treesitter] extra is absent)", +) + + +# ---------- registry ---------- + + +def test_csharp_resolver_is_registered(): + assert "csharp" in registered_languages() + assert get_resolver("csharp") is not None + + +def test_csharp_config_owns_cs_extension(): + assert resolver.config.id == "csharp" + assert resolver.config.extensions == (".cs",) + + +# ---------- extract (real tree-sitter, committed fixtures) ---------- + + +@_needs_ts +def test_extract_using_directives_are_namespaces_in_source_order(): + src = (_FIXTURES / "Controllers" / "HomeController.cs").read_bytes() + raws = resolver.extract(src) + assert [r.module for r in raws] == [ + "System", + "System.Collections.Generic", + "MyApp.Models", + "MyApp.Services", + "Newtonsoft.Json", + ] + # Every C# using directive is a module-level (non-lazy) namespace import with + # no per-specifier names (the whole namespace is brought in). + assert all(r.level == 0 and not r.function_local and r.names == () for r in raws) + + +@_needs_ts +def test_extract_skips_using_static_and_alias_keeps_plain_and_global(): + # `global using MyApp.Shared` and plain `using MyApp.Models` are namespace + # imports; `using static System.Math` (type statics) and + # `using Alias = MyApp.Models.Order` (alias) are NOT namespace fan-out. + src = (_FIXTURES / "Edge" / "Directives.cs").read_bytes() + assert [r.module for r in resolver.extract(src)] == ["MyApp.Shared", "MyApp.Models"] + + +# ---------- declared_namespaces (real tree-sitter, committed fixtures) ---------- + + +@_needs_ts +def test_declared_namespaces_block_form(): + src = (_FIXTURES / "Services" / "OrderService.cs").read_bytes() + assert resolver.declared_namespaces(src) == {"MyApp.Services"} + + +@_needs_ts +def test_declared_namespaces_file_scoped_form(): + src = (_FIXTURES / "Models" / "Customer.cs").read_bytes() + assert resolver.declared_namespaces(src) == {"MyApp.Models"} + + +@_needs_ts +def test_declared_namespaces_nested_yields_full_dotted_names(): + # Nested namespaces declare the parent AND the dotted child. + src = (_FIXTURES / "Edge" / "Directives.cs").read_bytes() + assert resolver.declared_namespaces(src) == {"MyApp.Edge", "MyApp.Edge.Inner"} + + +# ---------- cross-file namespace index (real tree-sitter, committed fixtures) ---------- + + +@_needs_ts +def test_index_maps_namespace_to_all_declaring_files_fan_out(): + # Two files declare `MyApp.Models` (one block-scoped, one file-scoped); the + # index fans that namespace out to BOTH declaring files. + sources = { + rel: (_FIXTURES / rel).read_bytes() + for rel in ("Models/Order.cs", "Models/Customer.cs", "Services/OrderService.cs") + } + index = CSharpResolver().index_namespaces(sources) + assert index["MyApp.Models"] == {"Models/Order.cs", "Models/Customer.cs"} + assert index["MyApp.Services"] == {"Services/OrderService.cs"} + + +# ---------- resolve (pure namespace-index lookup, runs everywhere) ---------- + + +def _resolver_with_index(index: dict[str, set[str]]) -> CSharpResolver: + r = CSharpResolver() + r._namespace_index = {ns: set(paths) for ns, paths in index.items()} + return r + + +def test_resolve_using_fans_out_to_namespace_declaring_files_sorted(): + r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs", "Models/Customer.cs"}}) + imp = RawImport(module="MyApp.Models", level=0, names=(), function_local=False) + files = {"Models/Order.cs", "Models/Customer.cs", "Controllers/HomeController.cs"} + assert r.resolve("Controllers/HomeController.cs", imp, files) == [ + "Models/Customer.cs", + "Models/Order.cs", + ] + + +def test_resolve_external_namespace_not_in_index_yields_nothing(): + r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs"}}) + imp = RawImport(module="Newtonsoft.Json", level=0, names=(), function_local=False) + files = {"Models/Order.cs", "Controllers/HomeController.cs"} + assert r.resolve("Controllers/HomeController.cs", imp, files) == [] + + +def test_resolve_system_dotted_namespace_is_dropped_even_if_declared(): + # `System.*` is the BCL/framework root and is dropped EXPLICITLY, not merely + # via an index miss: even a (perverse) project file declaring `System.Text` + # yields no edge. Without the explicit drop the index hit would resolve. + r = _resolver_with_index({"System.Text": {"Weird/System.cs"}}) + imp = RawImport(module="System.Text", level=0, names=(), function_local=False) + files = {"Weird/System.cs", "App.cs"} + assert r.resolve("App.cs", imp, files) == [] + + +def test_resolve_bare_system_namespace_is_dropped(): + r = _resolver_with_index({"System": {"Weird/System.cs"}}) + imp = RawImport(module="System", level=0, names=(), function_local=False) + assert r.resolve("App.cs", imp, {"Weird/System.cs"}) == [] + + +def test_resolve_system_prefix_substring_is_not_dropped(): + # Substring-confusion guard (equivalence partitioning): `SystemX.Utils` is a + # DIFFERENT namespace that merely starts with the letters "System"; the BCL + # drop keys on `System` exactly or the `System.` dotted prefix, never a bare + # substring, so this must still resolve. + r = _resolver_with_index({"SystemX.Utils": {"Lib/SystemX.cs"}}) + imp = RawImport(module="SystemX.Utils", level=0, names=(), function_local=False) + files = {"Lib/SystemX.cs", "App.cs"} + assert r.resolve("App.cs", imp, files) == ["Lib/SystemX.cs"] + + +def test_resolve_excludes_files_not_in_file_set(): + # A namespace declarer that is not among the scanned nodes (absent from + # file_set) is excluded: resolve only returns paths that exist in the map. + r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs", "Stale/Ghost.cs"}}) + imp = RawImport(module="MyApp.Models", level=0, names=(), function_local=False) + files = {"Models/Order.cs", "App.cs"} # Ghost.cs absent + assert r.resolve("App.cs", imp, files) == ["Models/Order.cs"] + + +def test_resolve_excludes_the_importer_itself(): + # A file that declares a namespace AND imports it gets no self-edge: the + # importer is excluded from its own fan-out. + r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs", "Models/Customer.cs"}}) + imp = RawImport(module="MyApp.Models", level=0, names=(), function_local=False) + files = {"Models/Order.cs", "Models/Customer.cs"} + assert r.resolve("Models/Order.cs", imp, files) == ["Models/Customer.cs"] + + +def test_resolve_with_empty_index_yields_nothing(): + # The default (unpopulated) resolver — today's scan-time state — resolves + # nothing: the cross-file namespace index must be built and loaded first. + imp = RawImport(module="MyApp.Models", level=0, names=(), function_local=False) + assert CSharpResolver().resolve("App.cs", imp, {"Models/Order.cs"}) == [] + + +# ---------- orchestrator integration (real tree-sitter, committed fixtures) ---------- + + +@_needs_ts +def test_infer_imports_edges_emits_csharp_namespace_fan_out(monkeypatch): + # Build source nodes for the committed C# mini-project, populate the + # resolver's cross-file namespace index, and run the orchestrator end-to-end: + # the controller's `using MyApp.Models` fans out to BOTH declaring files, + # `using MyApp.Services` resolves to the one, and System.*/Newtonsoft yield + # no edge. + rels = [ + "Models/Order.cs", + "Models/Customer.cs", + "Services/OrderService.cs", + "Controllers/HomeController.cs", + ] + nodes = [ + RepoMapNode(id=f"file:{rel}", type="source_file", path=rel, language="csharp") + for rel in rels + ] + populated = CSharpResolver() + populated.index_namespaces({rel: (_FIXTURES / rel).read_bytes() for rel in rels}) + monkeypatch.setattr( + imports_mod, + "get_resolver", + lambda lang: populated if lang == "csharp" else None, + ) + + edges = infer_imports_edges(nodes, _FIXTURES) + pairs = {(e.source, e.target) for e in edges} + controller = "file:Controllers/HomeController.cs" + assert (controller, "file:Models/Order.cs") in pairs + assert (controller, "file:Models/Customer.cs") in pairs # fan-out: second declarer + assert (controller, "file:Services/OrderService.cs") in pairs + # external assembly / BCL namespaces produce no edge + assert all("Newtonsoft" not in e.target for e in edges) + assert {e.reason for e in edges} == {"imports MyApp.Models", "imports MyApp.Services"} + # module-level usings -> high confidence; no dangling edges + assert all(e.confidence == "high" for e in edges) + node_ids = {n.id for n in nodes} + assert all(e.source in node_ids and e.target in node_ids for e in edges) + # exactly the three resolved fan-out edges, nothing fabricated + assert len(edges) == 3 From e24574a9f889ce2d3d014742939cd31cb588ecc8 Mon Sep 17 00:00:00 2001 From: sumithr Date: Fri, 3 Jul 2026 12:31:41 +0200 Subject: [PATCH 2/2] fix(repo-map): resolve using-alias namespaces and document global-using limit in C# resolver (#362) --- src/sumo_qa/repo_map_resolvers/csharp.py | 58 ++++++++++++++++-------- tests/test_repo_map_csharp_resolver.py | 36 ++++++++++++--- 2 files changed, 70 insertions(+), 24 deletions(-) diff --git a/src/sumo_qa/repo_map_resolvers/csharp.py b/src/sumo_qa/repo_map_resolvers/csharp.py index bc05fd82..65c5d30a 100644 --- a/src/sumo_qa/repo_map_resolvers/csharp.py +++ b/src/sumo_qa/repo_map_resolvers/csharp.py @@ -13,8 +13,12 @@ - **``using`` → namespace, not file.** ``extract`` pulls each plain ``using`` (and ``global using``) directive off the parse as a :class:`RawImport` whose ``module`` is the dotted namespace. ``using static T`` (imports a type's - static members) and ``using Alias = X`` (an alias) are NOT namespace imports - and are skipped. + static members) is NOT a namespace import and is skipped. ``using Alias = + Namespace`` (an alias directive) records the RIGHT-HAND-SIDE namespace (the + alias name is ignored), so it fans out to that namespace's declaring files + exactly as a plain ``using Namespace;`` would. tree-sitter cannot tell a + namespace alias from a type alias, so a type alias's RHS is recorded too, but + it simply misses the namespace index and resolves to nothing. - **Namespace fan-out via a cross-file index.** A namespace's declaring files can only be known by reading *other* files, so the resolver carries a ``namespace -> {declaring file path}`` index (built by @@ -41,6 +45,18 @@ ``_LANGUAGE_BY_EXT`` / ``_PROGRAMMING_LANGS`` omit it). Both are foundation changes and are out of scope here (#362 ships the resolver + its index capability; the scan-time wiring is a follow-on). + +.. note:: Known limitations + + A ``global using`` (e.g. ``global using MyApp.Models;`` in a + ``GlobalUsings.cs``) applies *project-wide* in C#: other files that use types + from ``MyApp.Models`` without a local ``using`` should get edges too. This + resolver only creates edges from the ``global using``'s OWN declaring file — + the path-only, per-file ``resolve(importer, imp, file_set)`` contract has no + project-wide view with which to apply one file's global usings to another. + Project-wide application needs the SAME cross-file pre-pass that populates the + namespace index (the foundation follow-up noted above); it is deliberately + NOT attempted here. """ from __future__ import annotations @@ -66,7 +82,6 @@ _QUALIFIED_NAME = "qualified_name" # `A.B.C` _IDENTIFIER = "identifier" # a single-segment name `A` _STATIC = "static" # the `static` token of `using static T` -_EQUALS = "=" # the `=` token of `using Alias = X` # The BCL/framework namespace root. `System` and any `System.*` namespace is # dropped explicitly so it never fans out even if a project file (perversely) @@ -88,11 +103,13 @@ def extract(self, src: bytes) -> list[RawImport]: """Return the namespace ``using`` directives in ``src`` as records. Each plain ``using X;`` / ``global using X;`` yields a - :class:`RawImport` whose ``module`` is the dotted namespace. ``using - static T`` (type statics) and ``using Alias = X`` (alias) are skipped — - they are not namespace imports. C# using directives are always - file-/namespace-level (never inside a method body), so ``level`` is - ``0``, ``names`` is empty, and ``function_local`` is ``False``. + :class:`RawImport` whose ``module`` is the dotted namespace, and an + alias ``using Alias = X;`` yields one whose ``module`` is the + RIGHT-HAND-SIDE namespace ``X`` (the alias name is ignored). ``using + static T`` (type statics) is skipped — it is not a namespace import. C# + using directives are always file-/namespace-level (never inside a method + body), so ``level`` is ``0``, ``names`` is empty, and + ``function_local`` is ``False``. """ root = parse("csharp", src) raws: list[RawImport] = [] @@ -106,21 +123,26 @@ def extract(self, src: bytes) -> list[RawImport]: @staticmethod def _using_namespace(node: TSNode) -> str | None: - """The dotted namespace of a plain ``using`` directive, or ``None``. - - Returns ``None`` for ``using static T`` (a ``static`` token) and - ``using Alias = X`` (an ``=`` token) — neither is a namespace import. - Otherwise the namespace is the directive's sole ``qualified_name`` / - ``identifier`` child (``global using`` and ``using`` differ only by a - leading ``global`` keyword token, so both reach here). + """The dotted namespace a ``using`` directive brings in, or ``None``. + + ``using static T`` (imports a type's static members) is not a namespace + import and yields ``None``. Otherwise the namespace is the directive's + LAST ``qualified_name`` / ``identifier`` child: a plain ``using X;`` / + ``global using X;`` has exactly one name node (``X``), while an alias + ``using Alias = X;`` has two (``[Alias, X]``) and the namespace is + always the right-hand ``X`` — the alias name precedes the ``=`` token, + so the RHS is last. tree-sitter cannot distinguish a namespace alias + from a type alias; a type alias's RHS is returned too but simply misses + the namespace index and resolves to nothing. """ kinds = {child.kind for child in node.children} - if _STATIC in kinds or _EQUALS in kinds: + if _STATIC in kinds: return None + namespace: str | None = None for child in node.children: if child.kind in (_QUALIFIED_NAME, _IDENTIFIER): - return child.text - return None # pragma: no cover -- defensive: a plain using always has a name node + namespace = child.text + return namespace def declared_namespaces(self, src: bytes) -> set[str]: """The set of namespaces ``src`` declares (block, file-scoped, nested). diff --git a/tests/test_repo_map_csharp_resolver.py b/tests/test_repo_map_csharp_resolver.py index 347b81b4..3d1f85bc 100644 --- a/tests/test_repo_map_csharp_resolver.py +++ b/tests/test_repo_map_csharp_resolver.py @@ -11,8 +11,9 @@ C# rules ported from Understand-Anything: a ``using`` names a NAMESPACE, not a file, so it resolves to every project file that DECLARES that namespace (package-level fan-out). ``System.*`` and external assemblies (no declaring -project file) yield no edge. ``using static`` (type-statics) and -``using Alias = X`` (alias) are not namespace imports and are dropped. +project file) yield no edge. ``using static`` (type-statics) is dropped; an +alias ``using Alias = X`` records its RIGHT-HAND-SIDE namespace ``X`` (the alias +name is ignored) and fans out just like a plain ``using X;``. """ from __future__ import annotations @@ -72,12 +73,18 @@ def test_extract_using_directives_are_namespaces_in_source_order(): @_needs_ts -def test_extract_skips_using_static_and_alias_keeps_plain_and_global(): +def test_extract_records_alias_rhs_skips_static_keeps_plain_and_global(): # `global using MyApp.Shared` and plain `using MyApp.Models` are namespace - # imports; `using static System.Math` (type statics) and - # `using Alias = MyApp.Models.Order` (alias) are NOT namespace fan-out. + # imports; `using static System.Math` (type statics) is dropped; the alias + # `using Alias = MyApp.Models.Order` records its RIGHT-HAND-SIDE + # `MyApp.Models.Order` (a type alias here: it misses the namespace index and + # resolves to nothing, but extract still records the RHS in source order). src = (_FIXTURES / "Edge" / "Directives.cs").read_bytes() - assert [r.module for r in resolver.extract(src)] == ["MyApp.Shared", "MyApp.Models"] + assert [r.module for r in resolver.extract(src)] == [ + "MyApp.Shared", + "MyApp.Models.Order", + "MyApp.Models", + ] # ---------- declared_namespaces (real tree-sitter, committed fixtures) ---------- @@ -127,6 +134,23 @@ def _resolver_with_index(index: dict[str, set[str]]) -> CSharpResolver: return r +@_needs_ts +def test_alias_directive_records_rhs_namespace_and_fans_out(): + # A NAMESPACE alias `using Models = MyApp.Models;`: the alias NAME is ignored + # and the RHS namespace `MyApp.Models` is recorded, so it fans out to the + # files declaring `MyApp.Models` exactly as a plain `using MyApp.Models;` + # would (#362 review fix — the alias was previously dropped entirely). + raws = resolver.extract(b"using Models = MyApp.Models;\n") + assert [r.module for r in raws] == ["MyApp.Models"] + + r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs", "Models/Customer.cs"}}) + files = {"Models/Order.cs", "Models/Customer.cs", "Controllers/HomeController.cs"} + assert r.resolve("Controllers/HomeController.cs", raws[0], files) == [ + "Models/Customer.cs", + "Models/Order.cs", + ] + + def test_resolve_using_fans_out_to_namespace_declaring_files_sorted(): r = _resolver_with_index({"MyApp.Models": {"Models/Order.cs", "Models/Customer.cs"}}) imp = RawImport(module="MyApp.Models", level=0, names=(), function_local=False)