fix(graph): resolve C# using directives via namespace scan (closes #33)

C# imports previously always returned null because there is no direct
filename mapping for `using X.Y.Z;`. As a result `codebase_graph_query`
reported zero edges for C# projects, and the symbol-level tools
(impact, flow, symbol) silently lost cross-file resolution because they
walk the file-import graph for Tier 2/3 candidates.

Build a namespace-to-files map once per graph build by regex-scanning
every `.cs` file for `^namespace X.Y.Z` (covers both block-scoped and
file-scoped C# 10+ syntax) and consult it from the csharp branch of
resolveImport. When a namespace spans multiple files the first
candidate is returned; multi-file fan-out is tracked as a follow-up.
External namespaces (System.*, Microsoft.*) are still filtered upstream
by isExternalModule, so the map is only consulted for project-internal
names.

Cost is O(n) reads at graph-build time, gated by a `hasCs` precheck so
non-C# projects pay nothing.

Adds 12 unit tests covering block-scoped, file-scoped, multi-file,
multi-namespace-per-file, commented-out lines, non-.cs files, empty
projects, unknown namespaces, and external (System.*) filtering.
This commit is contained in:
Giancarlo Erra
2026-04-28 00:04:01 +01:00
parent 0e86cd0731
commit 0aaf3f1d75
3 changed files with 249 additions and 8 deletions
+10 -3
View File
@@ -13,7 +13,7 @@ import type {
} from "../types.js";
import { loadPathAliases } from "./graph-aliases.js";
import { extractImports } from "./graph-imports.js";
import { buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
import { buildCsNamespaceMap, buildJvmSuffixMap, resolveImport } from "./graph-resolution.js";
import { computeUnresolvedPct, resolveCallSites } from "./graph-symbol-resolution.js";
import { extractSymbolsAndCalls, rawCallsToUnresolvedEdges } from "./graph-symbols.js";
import { createIgnoreFilter, shouldIgnore } from "./ignore.js";
@@ -605,13 +605,20 @@ export async function buildCodeGraph(
// Build a suffix lookup map for JVM multi-module projects (Java/Kotlin/Scala).
// This resolves FQNs like com.example.Foo when the class lives under a nested
// src/main/java/ tree (e.g. module-a/sub/src/main/java/com/example/Foo.java).
// Cost: O(n) once here, O(1) per import lookup — negligible vs. full AST parse.
// Cost: O(n) once here, O(1) per import lookup (negligible vs. full AST parse).
const hasJvm = files.some((f) => {
const e = path.extname(f).toLowerCase();
return e === ".java" || e === ".kt" || e === ".kts" || e === ".scala";
});
const jvmSuffixMap = hasJvm ? buildJvmSuffixMap(fileSet) : undefined;
// Build a namespace lookup map for C# projects. Each `namespace X.Y.Z` block
// (or file-scoped `namespace X.Y.Z;`) is recorded so `using X.Y.Z;` directives
// can be resolved to the file(s) that contribute to that namespace. Without
// this, every C# import resolved to null and the file graph was empty.
const hasCs = files.some((f) => path.extname(f).toLowerCase() === ".cs");
const csNamespaceMap = hasCs ? buildCsNamespaceMap(fileSet, resolvedPath) : undefined;
for (const relPath of files) {
const ext = path.extname(relPath).toLowerCase();
const lang = getAstGrepLang(ext);
@@ -682,7 +689,7 @@ export async function buildCodeGraph(
// Try to resolve to a project file
// CSS imports from <style> blocks use CSS resolution even when the source file is Svelte/Vue
const resolutionLanguage = imp.isCssImport ? "css" : language;
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap);
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases, jvmSuffixMap, csNamespaceMap);
if (resolved) {
node.dependencies.push(resolved);
+70 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
import { readFileSync } from "node:fs";
import path from "node:path";
import type { PathAliases } from "./graph-aliases.js";
@@ -51,6 +52,56 @@ export function buildJvmSuffixMap(fileSet: Set<string>): Map<string, string> {
return map;
}
/**
* Build a namespace lookup map for C# files.
*
* Scans every `.cs` file in the project for `namespace X.Y.Z` declarations
* (both block-scoped `namespace X { ... }` and file-scoped `namespace X;`
* introduced in C# 10) and builds:
*
* key: "App.Services"
* value: ["src/Services/UserService.cs", "src/Services/OrderService.cs"]
*
* Used to resolve `using App.Services;` to the candidate files that
* contribute to that namespace. Without this, every C# `using` resolved
* to `null` and C# projects produced an empty file-import graph.
*
* Cost: O(n) reads at graph-build time (negligible vs. AST parsing). Files
* with no `namespace` declaration are silently skipped. Read failures are
* swallowed since this is best-effort.
*/
export function buildCsNamespaceMap(
fileSet: Set<string>,
projectPath: string,
): Map<string, string[]> {
const map = new Map<string, string[]>();
// Match both `namespace Foo.Bar { ... }` and the file-scoped C# 10+
// syntax `namespace Foo.Bar;`. The `^` plus `m` flag pins to line start
// so commented lines (`// namespace X.Y`) are not matched.
const namespaceRegex = /^namespace\s+([\w.]+)/gm;
for (const f of fileSet) {
if (path.extname(f).toLowerCase() !== ".cs") continue;
let source: string;
try {
source = readFileSync(path.join(projectPath, f), "utf-8");
} catch {
continue;
}
for (const match of source.matchAll(namespaceRegex)) {
const ns = match[1];
const existing = map.get(ns);
if (existing) {
if (!existing.includes(f)) existing.push(f);
} else {
map.set(ns, [f]);
}
}
}
return map;
}
/**
* Resolve a module specifier to a relative file path within the project.
* Returns null if the module is external (e.g., npm package, stdlib).
@@ -63,6 +114,7 @@ export function resolveImport(
language: string,
aliases?: PathAliases,
jvmSuffixMap?: Map<string, string>,
csNamespaceMap?: Map<string, string[]>,
): string | null {
// Skip obvious external/stdlib modules
if (isExternalModule(moduleSpecifier, language)) return null;
@@ -235,7 +287,24 @@ export function resolveImport(
}
case "csharp": {
// Namespaces don't map cleanly to files, skip
// C# `using X.Y.Z;` resolves via a namespace lookup map built once
// at graph-build time. Project-internal namespaces map to one or
// more files (multi-file namespaces are common in real .NET
// projects). External namespaces (`System.*`, `Microsoft.*`, etc.)
// are filtered earlier by `isExternalModule`.
//
// When a namespace spans multiple files we return the first
// candidate as the resolved dependency. This produces meaningful
// edges instead of the previous always-null behaviour, which left
// C# file graphs empty and silently degraded the symbol-level
// tools' cross-file resolution. A multi-file fan-out improvement
// is tracked as a follow-up.
if (csNamespaceMap) {
const candidates = csNamespaceMap.get(moduleSpecifier);
if (candidates && candidates.length > 0) {
return candidates[0];
}
}
return null;
}
+169 -4
View File
@@ -5,7 +5,11 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { buildJvmSuffixMap, resolveImport } from "../../src/services/graph-resolution.js";
import {
buildCsNamespaceMap,
buildJvmSuffixMap,
resolveImport,
} from "../../src/services/graph-resolution.js";
// ── Helper to create temp project layouts ─────────────────────────────
@@ -691,10 +695,10 @@ describe("graph-resolution", () => {
// ── C# resolution ─────────────────────────────────────────────────────
describe("C# resolution", () => {
it("returns null (namespaces don't map to files)", () => {
it("returns null when no namespace map is supplied (back-compat)", () => {
project = createTempProject({
"Models/User.cs": "",
"Program.cs": "",
"Models/User.cs": "namespace MyApp.Models { public class User {} }",
"Program.cs": "using MyApp.Models;",
});
const result = resolveImport(
@@ -707,6 +711,167 @@ describe("graph-resolution", () => {
expect(result).toBeNull();
});
it("resolves a using directive to a file via the namespace map", () => {
project = createTempProject({
"Models/User.cs": "namespace MyApp.Models { public class User {} }",
"Program.cs": "using MyApp.Models;\nnamespace MyApp { class Program {} }",
});
const csNamespaceMap = buildCsNamespaceMap(project.fileSet, project.root);
const result = resolveImport(
"MyApp.Models",
path.join(project.root, "Program.cs"),
project.root,
project.fileSet,
"csharp",
undefined,
undefined,
csNamespaceMap,
);
expect(result).toBe("Models/User.cs");
});
it("returns the first candidate when a namespace spans multiple files", () => {
project = createTempProject({
"Services/UserService.cs":
"namespace MyApp.Services { public class UserService {} }",
"Services/OrderService.cs":
"namespace MyApp.Services { public class OrderService {} }",
"Program.cs": "using MyApp.Services;",
});
const csNamespaceMap = buildCsNamespaceMap(project.fileSet, project.root);
const result = resolveImport(
"MyApp.Services",
path.join(project.root, "Program.cs"),
project.root,
project.fileSet,
"csharp",
undefined,
undefined,
csNamespaceMap,
);
// Multi-file namespaces resolve to the first registered file. Multi-file
// fan-out is a known follow-up.
expect(result).toBe("Services/UserService.cs");
});
it("returns null for unknown namespaces even with a populated map", () => {
project = createTempProject({
"Models/User.cs": "namespace MyApp.Models { public class User {} }",
"Program.cs": "using MyApp.Unknown;",
});
const csNamespaceMap = buildCsNamespaceMap(project.fileSet, project.root);
const result = resolveImport(
"MyApp.Unknown",
path.join(project.root, "Program.cs"),
project.root,
project.fileSet,
"csharp",
undefined,
undefined,
csNamespaceMap,
);
expect(result).toBeNull();
});
it("filters System.* and Microsoft.* as external before consulting the map", () => {
project = createTempProject({
"Program.cs": "namespace System.Collections { class Stub {} }",
});
const csNamespaceMap = buildCsNamespaceMap(project.fileSet, project.root);
const result = resolveImport(
"System.Collections",
path.join(project.root, "Program.cs"),
project.root,
project.fileSet,
"csharp",
undefined,
undefined,
csNamespaceMap,
);
expect(result).toBeNull();
});
});
// ── buildCsNamespaceMap ───────────────────────────────────────────────
describe("buildCsNamespaceMap", () => {
it("indexes block-scoped namespace declarations", () => {
project = createTempProject({
"Models/User.cs": "namespace MyApp.Models { public class User {} }",
"Models/Order.cs": "namespace MyApp.Models { public class Order {} }",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
const files = map.get("MyApp.Models") ?? [];
expect(files.sort()).toEqual(["Models/Order.cs", "Models/User.cs"]);
});
it("indexes file-scoped namespace declarations (C# 10+)", () => {
project = createTempProject({
"Services/UserService.cs":
"namespace MyApp.Services;\n\npublic class UserService {}",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.get("MyApp.Services")).toEqual(["Services/UserService.cs"]);
});
it("registers multiple namespaces declared in the same file", () => {
project = createTempProject({
"Mixed.cs":
"namespace MyApp.A { class A {} }\nnamespace MyApp.B { class B {} }",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.get("MyApp.A")).toEqual(["Mixed.cs"]);
expect(map.get("MyApp.B")).toEqual(["Mixed.cs"]);
});
it("does not match commented-out namespace lines", () => {
project = createTempProject({
"Program.cs":
"// namespace MyApp.Hidden;\nnamespace MyApp.Real { class C {} }",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.has("MyApp.Hidden")).toBe(false);
expect(map.get("MyApp.Real")).toEqual(["Program.cs"]);
});
it("ignores non-.cs files", () => {
project = createTempProject({
"notes.txt": "namespace Fake.Namespace;",
"Program.cs": "namespace Real.Namespace { class C {} }",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.has("Fake.Namespace")).toBe(false);
expect(map.get("Real.Namespace")).toEqual(["Program.cs"]);
});
it("returns an empty map for a project with no .cs files", () => {
project = createTempProject({ "index.ts": "", "style.css": "" });
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.size).toBe(0);
});
it("does not duplicate the same file when re-indexed", () => {
project = createTempProject({
"Dup.cs": "namespace MyApp.X { class A {} }\nnamespace MyApp.X { class B {} }",
});
const map = buildCsNamespaceMap(project.fileSet, project.root);
expect(map.get("MyApp.X")).toEqual(["Dup.cs"]);
});
});
// ── Swift resolution ──────────────────────────────────────────────────