/** * C# language adapter backed by csharp-ls + Microsoft.CodeAnalysis. * LanguageServer (ADR-22). * * Wraps `csharp-ls` (razzmatazz/csharp-language-server) spawned as a * subprocess, speaking LSP over stdio. csharp-ls itself wraps the * official Roslyn LSP (Microsoft.CodeAnalysis.LanguageServer) and * presents a clean LSP-spec interface to clients — absorbs Roslyn's * custom protocol (project-restore signaling, .sln/.csproj * resolution, MSBuild SDK registration). Implements the * `LanguageAdapter` interface from src/types.ts per ADR-03 (adapters * are plugins) and ADR-07 (getTypeInfo is a required capability). * * Phase 3 implementation complete across 8 substeps: * - 3.1: skeleton — constructor, handler stubs, spawn pattern * (with Windows PATH-enrichment for dotnet tools), initialize * handshake, shutdown. * - 3.2: listSymbols — hierarchical-tree walk + parentId * back-pointer + File-kind-1 wrapper skip + Roslyn detail field * as signature substrate. * - 3.3: getSymbolDetails — hover-based signature refinement + * parseCsharpHoverContent + findSymbolByName + parseSymbolId. * - 3.4: findReferences — clean LSP Location[] (no URL-encoding * dedup needed; Roslyn cleaner than ruby-lsp per Phase 0). * - 3.5: getDiagnostics — LSP 3.17 pull-model * (textDocument/diagnostic REQUEST; net-new substrate parallel * to ADR-21 Ruby). * - 3.6: getTypeInfo — native typeDefinition + implementation; * declaration-line scan only for base-vs-interface * disambiguation (not multi-pass class-hierarchy walk parallel * to ADR-13 Pyright / ADR-21 Ruby). * - 3.7: getDocstring — forward-composition consumer of 3.3 * parseCsharpHoverContent prose field; XML doc summary + Parameters: * section surfaced as structured markdown. * - 3.8: adapter close + consolidation (THIS commit) — header * doc update + inline-require hoist + Phase 3 close substrate- * record observations. * * Divergences from ADR-13 (Pyright) + ADR-14 (gopls) + ADR-21 (Ruby) * documented in ADR-22: * - Wrapper-as-vehicle: csharp-ls wraps Microsoft.CodeAnalysis. * LanguageServer. ContextAtlas sees clean LSP-spec endpoints; the * wrapper absorbs Roslyn's custom protocol. * - Single-pattern install (dotnet tool global; no dual-pattern * parallel to Ruby's bundler-vs-gem). * - Windows PATH-enrichment for `%USERPROFILE%\.dotnet\tools` * (Bash/Git-Bash doesn't inherit dotnet tools path from * PowerShell-configured PATH). Parallel to ADR-21 RUBY_BIN_DIRS + * ADR-14 gopls "Go binary must be on PATH" finding. Phase 0 * spike empirical (2026-06-08). * - Pull-model diagnostics (LSP 3.17 `textDocument/diagnostic` * REQUEST), parallel to ADR-21; NOT publishDiagnostics * notification (parallel to Pyright/gopls). * - Native typeDefinition + implementation (Roslyn supports both); * no declaration-parse fallback parallel to ADR-13 Pyright * Protocol-cache or ADR-21 Ruby class-hierarchy parse. * - Hover includes XML doc summaries + parameter descriptions * out of the box (parallel to gopls; substantively different * from ADR-13 Pyright omits-docstrings). * - No cold-start `$/progress` readiness gate — Roslyn (via * csharp-ls) follows Pyright pattern per Phase 0 probe empirical; * per-call ceiling absorbs cold-start variance. * - csharp-ls is solo-maintained (Saulius Menkevičius); NOT * corporate-backed parallel to ruby-lsp's Shopify backing. * Maintenance-tail mitigations per ADR-22: A2 fallback path; * doctor staleness signal; minimum-version pin. * * See `docs/adr/csharp-roslyn-probe/findings-baseline.md` for the * Phase 0 empirical probe substrate motivating these design choices. */ import { LANG_CODES, type Diagnostic, type LanguageAdapter, type LanguageCode, type Reference, type ReferenceId, type Symbol as AtlasSymbol, type SymbolId, type SymbolKind, type TypeInfo } from "../types.js"; interface LspPosition { line: number; character: number; } interface LspRange { start: LspPosition; end: LspPosition; } interface LspDiagnostic { range: LspRange; severity?: number; message: string; code?: string | number; source?: string; } interface LspDocumentSymbol { name: string; detail?: string; kind: number; range: LspRange; selectionRange: LspRange; children?: LspDocumentSymbol[]; } interface LspLocation { uri: string; range: LspRange; } export declare function mapCsharpKind(lspKind: number): SymbolKind; export declare function mapDiagnosticSeverity(n: number | undefined): Diagnostic["severity"]; export declare function enrichPathForDotnetTools(): void; export interface CsharpAdapterOptions { /** * Override the csharp-ls binary path. When set, bypasses default * resolution and spawns the binary directly. Defaults to * `process.env.CONTEXTATLAS_CSHARP_LSP_BIN` when unset. */ cliPath?: string; /** Upper bound on a single LSP request. Defaults to 60s. */ requestTimeoutMs?: number; /** * Skip the `dotnet --version` preflight. Reserved for tests that * stub the LSP transport — production code should leave at default * `false` so the adapter fails fast when `dotnet` is missing from * PATH. */ skipDotnetPreflight?: boolean; /** * Override the `dotnet` binary used by the preflight. Defaults to * `"dotnet"` (resolved via PATH). Test-only; production users should * put `dotnet` on PATH per ADR-22. */ dotnetBin?: string; /** * Skip the PATH enrichment for dotnet tools. Reserved for tests * that control the spawn environment directly. Production code * should leave at default `false`. */ skipPathEnrichment?: boolean; } /** Extensions indexed at v1.1 per ADR-22 (`.cs` only at v1.1.0). */ export declare const CSHARP_EXTENSIONS: readonly string[]; export declare class CsharpAdapter implements LanguageAdapter { readonly language: LanguageCode; readonly extensions: readonly string[]; private readonly client; private readonly options; private rootPath; private readonly openFiles; private readonly diagnosticsByUri; private readonly diagnosticsListeners; constructor(options?: CsharpAdapterOptions); initialize(rootPath: string): Promise; shutdown(): Promise; /** * Resolve a filePath argument to absolute + workspace-relative * forms. Accepts either absolute paths or workspace-relative paths; * returns both for use by callers (LSP requests need absolute paths * via toFileUri; Symbol-IDs need workspace-relative paths per ADR-01). */ private resolveFile; /** * Send `textDocument/didOpen` for `absPath` if not already opened * in this session. csharp-ls (like Pyright + gopls + ruby-lsp) * requires files to be opened before symbol queries return results. */ private ensureOpen; /** * Construct a C# Symbol-ID per ADR-01 format: `sym:cs::`. * Path is workspace-relative forward-slash-separated; name is the * symbol identifier as csharp-ls emits it. C# has no `self.`-prefix- * verbatim pattern parallel to Ruby — static methods emit with same * name shape as instance methods (kind 6 uniformly). */ private symbolId; listSymbols(filePath: string): Promise; getSymbolDetails(id: SymbolId): Promise; findReferences(id: SymbolId): Promise; getDiagnostics(filePath: string): Promise; getTypeInfo(id: SymbolId): Promise; getDocstring(id: SymbolId): Promise; } /** * Run `dotnet --version` to verify dotnet SDK is installed and * accessible. Throws actionable error if missing. * * Per ADR-22 §"Toolchain" — dotnet is the prereq for csharp-ls * (csharp-ls is distributed as a dotnet tool; depends on dotnet * runtime). Preflight surfaces "dotnet not on PATH" before the * adapter spawns csharp-ls and hits the cryptic ENOENT path. * * Parallel to ADR-21 `runRubyVersionPreflight` and ADR-14 gopls's * `go version` preflight. */ export declare function runDotnetVersionPreflight(dotnetBin: string): Promise; /** * Detect a `.sln` / `.slnx` / `.csproj` file under `root` (any depth). * Used by doctor checks at Phase 5.2 to report detected project files. * csharp-ls itself auto-discovers via MSBuild resolution; this helper * is observational only (parallel to ADR-21 detectRails). * * Returns the first project file found (in priority order: .sln > * .slnx > .csproj), or null if none present. */ export declare function detectProjectFile(root: string): string | null; /** * Recursively search an LspDocumentSymbol tree for the first symbol * matching `name`. Returns the matched LspDocumentSymbol or null. * * C# symbol names from Roslyn include parameter lists for methods * (`FindByEmail(string email)`); caller passes the verbatim name as * parsed from Symbol-ID. Per ADR-22 §"Symbol-kind mapping", Roslyn * uses parameter-included names for overload disambiguation; * preserving this match shape end-to-end. * * Generic over the tree shape per ADR-21 RubyAdapter precedent * (findSymbolByName); the search is structurally identical across * adapters (depth-first, name-equality match). */ export declare function findSymbolByName(symbols: readonly LspDocumentSymbol[], name: string): LspDocumentSymbol | null; /** * Parse csharp-ls hover response markdown envelope into structured * `{ signature, prose }` shape per ADR-22 §LSP primitive mappings * (Phase 0 probe empirical substrate — see findings-baseline.md * §"Probe #3 — hover"). * * Roslyn hover envelope structure (probe-empirical): * ```csharp * * ``` * * * * Parameters: * - ``param``: * * Parser strips: * - The fenced ```csharp code block (extracts inner content as * signature) * * Parser preserves: * - First fenced ```csharp code block content as signature * - All post-fence prose as `prose` (consumed by getDocstring at * Substep 3.7; includes summary text + parameters list) * * Edge cases: * - Empty/null value → both fields null * - Code block only (no prose) → signature populated, prose null * (matches User.PremiumTierLimit-style hover with just signature) * - No code block → signature null, prose = stripped value * (defensive; not observed in Phase 0 probe but possible if * Roslyn returns plain-text hover in some edge case) * * Returns: `{ signature, prose }` — both string-or-null. * Forward-composition design per ADR-22: Substep 3.3 consumes * `signature`; Substep 3.7 consumes `prose`. Single hover request, * single markdown parse, two field consumers. */ export declare function parseCsharpHoverContent(value: string): { signature: string | null; prose: string | null; }; /** * Parse a C# SymbolId (`sym:cs::`) into its components. * Returns null for IDs that don't match the expected shape — callers * treat that as "no such symbol" rather than throwing. * * C# symbol names from Roslyn can contain `(`, `)`, `,`, ` `, * `<`, `>` from parameter lists (method overload disambiguation per * Roslyn convention) and generic type parameters (e.g., * `Repository`). Path component is the first colon-delimited * segment after `sym:cs:`; remaining is the name. */ export declare function parseSymbolId(id: SymbolId): { path: string; name: string; } | null; /** * LSP 3.17 DocumentDiagnosticReport variants per * https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_diagnostic * * Roslyn (via csharp-ls) emits the `kind: "full"` variant per Phase 0 * probe #6 empirical capture. The `kind: "unchanged"` variant is * defined for incremental refresh optimization (when caller passes * prior resultId); adapter doesn't use this at v1.1.0 — every call * is a fresh "full" query. */ export type DocumentDiagnosticReport = { kind: "full"; items?: LspDiagnostic[]; resultId?: string; relatedDocuments?: unknown; } | { kind: "unchanged"; resultId: string; relatedDocuments?: unknown; }; /** * Build ContextAtlas Diagnostic[] from a csharp-ls (Roslyn) pull-model * DocumentDiagnosticReport response. Exported for unit-test access to * variant handling without requiring live LSP integration. * * Variant handling per ADR-22 §"Diagnostics via PULL model": * - null response → empty array (defensive; per-call timeout * fallback case) * - kind: "unchanged" → empty array (Roslyn shouldn't emit this * when no previousResultId is sent, but defensive handling at * v1.0; future enhancement could track resultId state for * "diagnostics-haven't-changed" optimization) * - kind: "full" → items mapped to ContextAtlas Diagnostic[] * with severity remap via mapDiagnosticSeverity + 1-indexed * line conversion * * Roslyn diagnostic substrate richness (CS error codes, codeDescription * URIs to Microsoft docs) not preserved in adapter response — Diagnostic * contract per types.ts has only severity/message/path/line/column. * Future v1.x candidate per ADR-22 §"Diagnostic substrate richness": * extend Diagnostic with optional `code` + `codeDescription` fields * for richer downstream consumption. */ export declare function buildDiagnosticsFromResponse(response: DocumentDiagnosticReport | null, relPath: string): Diagnostic[]; /** * Parse a C# class/interface/struct declaration line and extract the * `extends` + `implements` lists from the `: A, B, C` clause. * * C# inheritance syntax: `[modifiers] class|interface|struct|record * Name[] [: Base, IFace1, IFace2] [where ...] { ... }`. * Base class (if present) is always the FIRST item; all subsequent * items are interfaces. For interface declarations, ALL items in the * `:` clause are parent interfaces (interfaces can extend multiple * interfaces). * * **I-prefix heuristic for class first-item disambiguation** * (ADR-22 §Limitations). For class/struct/record (not interface), * the first item after `:` may be either a base class or a single * interface. C# has no syntactic distinction; semantic info (which * the source line lacks) is needed. The adapter uses the .NET * convention `I[A-Z]...` as the interface heuristic: * * - First item matches `/^I[A-Z]/` → treated as interface (implements) * - First item doesn't match → treated as base class (extends) * * Edge cases (documented as v1.1.0 Limitation; v1.2+ may upgrade * via typeDefinition semantic query): * - Base class starting with I+Uppercase (e.g., `IdentityUser`) → * incorrectly classified as interface * - Interface NOT following I-prefix convention (rare in real * C# code) → incorrectly classified as base class * * Generic type parameters (``, ``) are stripped * from extracted names for canonical identity (matches ADR-14 gopls * generic-handling precedent). Where clauses (`where T : new()`) and * opening braces terminate the parse. * * Returns: `{ extends, implements }` — both string[]. */ export declare function parseCsharpClassDeclaration(line: string, targetName: string, isInterface: boolean): { extends: string[]; implements: string[]; }; /** * Extract a type name from an LSP Location pointing at a type * declaration site. Used by getTypeInfo's usedByTypes resolution to * convert textDocument/implementation Location[] responses into * type-name strings. * * Reads the file at loc.uri, finds the line at loc.range.start.line, * and extracts the identifier following `class|interface|struct| * record` keyword on that line. * * Returns null if: * - File not readable * - Line doesn't contain a type declaration keyword * - Identifier extraction fails (malformed source) * * Generic-stripped for canonical identity (matches * parseCsharpClassDeclaration generic-handling). */ export declare function extractTypeNameFromLocation(loc: LspLocation): string | null; /** * Construct a C# Reference-ID per ADR-01 format: `ref:cs::`. * Path is workspace-relative forward-slash-separated; line is * 1-indexed (human-readable). Exported for testability of ID format * separate from full findReferences flow. */ export declare function buildReferenceId(relPath: string, line: number): ReferenceId; export { LANG_CODES }; //# sourceMappingURL=csharp.d.ts.map