diff --git a/docs/plans/DEBUGGING-PLAN.md b/docs/plans/DEBUGGING-PLAN.md index e7af0d4d..bd262691 100644 --- a/docs/plans/DEBUGGING-PLAN.md +++ b/docs/plans/DEBUGGING-PLAN.md @@ -138,8 +138,7 @@ are green. *an unbuilt project resolves to nothing or to a real file, and to MSBuild once built* - [x] Run C# file-based apps with `dotnet run --file ` (never the positional form) and debug them via `dotnet build --artifacts-path `. `launch-run.ts:47` - `runArgs`, `launch-run.ts:131` `buildFileBasedApp`, `launch-run.ts:152` - `fileBasedAssembly`; tests `run-debug-scripts.test.ts` *a file-based .cs runs via dotnet + `runArgs`, `launch-run.ts` `buildFileBasedApp` (launches MSBuild's `TargetPath`); tests `run-debug-scripts.test.ts` *a file-based .cs runs via dotnet run --file, never the positional form* and *debugging a file-based .cs launches the artifacts-path assembly* - [x] Run `.fsx` with `dotnet fsi --exec`; refuse `.fsx` debugging with a named message. diff --git a/docs/plans/DIAGNOSTICS-STATIC-ANALYZERS-PLAN.md b/docs/plans/DIAGNOSTICS-STATIC-ANALYZERS-PLAN.md index 83659ddc..fa6ec177 100644 --- a/docs/plans/DIAGNOSTICS-STATIC-ANALYZERS-PLAN.md +++ b/docs/plans/DIAGNOSTICS-STATIC-ANALYZERS-PLAN.md @@ -137,14 +137,14 @@ Implements the cross-language part of [ANALYZERS-REFERENCE-MODEL]. - [ ] Define a shared metadata identity DTO for C# and F# public symbols. - [ ] Count C# references to F# public symbols through project-reference metadata. - [ ] Count F# references to C# public symbols through project-reference metadata. -- [ ] Suppress diagnostics when cross-language identity is ambiguous. -- [ ] Full-stack test: C# calls public F# function, F# symbol is not reported. -- [ ] Full-stack test: F# calls public C# method, C# symbol is not reported. -- [ ] Full-stack test: ambiguous metadata identity suppresses instead of reporting +- [x] Suppress diagnostics when cross-language identity is ambiguous — `CrossLanguageReferences` (Common) marks every project the other language references; both analyzers report no unused public code there (#617). +- [x] Full-stack test: C# calls public F# function, F# symbol is not reported — `configuration_live.rs` `a_public_fsharp_function_only_csharp_calls_is_not_dead_in_a_monorepo`. +- [x] Full-stack test: F# calls public C# method, C# symbol is not reported — `configuration_live.rs` `a_public_csharp_type_only_fsharp_uses_is_not_dead_in_a_monorepo`. +- [x] Full-stack test: ambiguous metadata identity suppresses instead of reporting a false positive. -## Phase 6: Editor Experience And Follow-Up Actions (P1) - +## Phase 6: Editor Experience And Follow-Up Actions (P1) — both tests above: the + unused public symbol of a cross-language-referenced project is not reported either. - [ ] VS Code e2e test: monorepo static diagnostics appear in Problems for unopened files after `workspace/diagnostic`. - [ ] VS Code e2e test: changing `repository_kind` triggers @@ -194,4 +194,4 @@ Implements the cross-language part of [ANALYZERS-REFERENCE-MODEL]. - [ ] Share metadata identity between C# and F# indexes. - [ ] Count C# to F# and F# to C# references. -- [ ] Suppress ambiguous cross-language cases. +- [x] Suppress ambiguous cross-language cases (see the matching phase row). diff --git a/docs/specs/DIAGNOSTICS-STATIC-ANALYZERS-SPEC.md b/docs/specs/DIAGNOSTICS-STATIC-ANALYZERS-SPEC.md index 5c64db85..23188bb6 100644 --- a/docs/specs/DIAGNOSTICS-STATIC-ANALYZERS-SPEC.md +++ b/docs/specs/DIAGNOSTICS-STATIC-ANALYZERS-SPEC.md @@ -243,5 +243,5 @@ The analyzer must prefer silence over false positives: - If the workspace is not explicitly configured as a monorepo, return no unused-public-code diagnostics. - If a project is unloaded or failed to load, return no unused-public-code diagnostics for symbols that could be referenced by that project. -- If cross-language identity cannot be proven for a symbol, do not report it as unused. +- If cross-language identity cannot be proven for a symbol, do not report it as unused. Until metadata identity is shared between the compilers, every project the other language references — a C# project an F# project references, or the reverse — reports no unused public code at all; private and internal code is still judged (#617). Implemented by `SharpLsp.Sidecar.Common.Solutions.CrossLanguageReferences`. - If the analyzer cannot distinguish a framework entry point from ordinary public API, suppress the diagnostic and emit structured trace logging for future rule tuning. diff --git a/docs/specs/SHARPLSP-SPEC.md b/docs/specs/SHARPLSP-SPEC.md index e0e6ad49..dd924aeb 100644 --- a/docs/specs/SHARPLSP-SPEC.md +++ b/docs/specs/SHARPLSP-SPEC.md @@ -162,7 +162,7 @@ A design-time build writes generated files under the project's `obj/ lspClient, explorer: (): SolutionExplorerProvider | undefined => explorerProvider, }; @@ -100,6 +100,7 @@ interface DeploymentResult { // console where users do not see them — that is the failure mode this prevents. export async function activate(context: ExtensionContext): Promise { log.info('SharpLsp activating…'); + explorerDeps.memory = context.workspaceState; log.info(`File log: ${log.logFilePath()}`); try { return await activateInner(context); @@ -417,7 +418,7 @@ function registerCommands(context: ExtensionContext): void { [CMD_SHOW_TRACE]: () => { log.trace().show(); }, - [CMD_SELECT_SOLUTION]: solutions.selectAndLoad, + [CMD_SELECT_SOLUTION]: solutions.pickAndLoad, [CMD_OPEN_SOLUTION]: async (solutionPath: string) => { await solutions.load({ path: solutionPath, name: '' }); }, diff --git a/src/editors/vscode/src/solution-load.ts b/src/editors/vscode/src/solution-load.ts index 98c135bc..600e47d6 100644 --- a/src/editors/vscode/src/solution-load.ts +++ b/src/editors/vscode/src/solution-load.ts @@ -3,7 +3,8 @@ * work from, and the debounced tree refresh that follows source or solution * file changes. Implements [SE-SOLUTION] and [SE-LOADING-FEEDBACK]. */ -import { type ExtensionContext, window, workspace } from 'vscode'; +import * as fs from 'node:fs'; +import { type ExtensionContext, type Memento, window, workspace } from 'vscode'; import { type LanguageClient } from 'vscode-languageclient/node'; import { VIEW_SOLUTION_EXPLORER } from './constants.js'; import * as log from './log.js'; @@ -16,12 +17,16 @@ import { getErrorMessage } from './utils.js'; export interface SolutionLoaderDeps { readonly client: () => LanguageClient | undefined; readonly explorer: () => SolutionExplorerProvider | undefined; + /** Per-workspace storage that outlives a window reload; absent until activation. */ + readonly memory?: Memento; } /** Solution selection and loading bound to one extension activation. */ export interface SolutionLoader { - /** Select a solution (auto or user-picked) and load it into the explorer. */ + /** Reopen the remembered solution, else select one (auto or user-picked) and load it. */ readonly selectAndLoad: () => Promise; + /** Always ask which solution to load: the user is switching on purpose. */ + readonly pickAndLoad: () => Promise; /** Load a solution into the explorer tree AND the LSP sidecar. */ readonly load: (selected: solution.SolutionSelection) => Promise; /** Re-fetch workspace symbols when source or solution files change. */ @@ -31,6 +36,27 @@ export interface SolutionLoader { const REFRESH_DEBOUNCE_MS = 1_000; const RELEVANT_LANGUAGES = new Set(['csharp', 'fsharp']); const SOLUTION_FILE_GLOB = '**/*.{sln,slnx}'; +/** The workspace-storage key holding the solution last loaded in this workspace. */ +const REMEMBERED_SOLUTION = 'sharplsp.solution'; + +/** The remembered solution while its file still exists; a deleted one is forgotten. */ +function remembered(memory: Memento | undefined): solution.SolutionSelection | undefined { + const stored = memory?.get(REMEMBERED_SOLUTION); + if (stored === undefined || !fs.existsSync(stored)) return undefined; + return solution.toSolutionSelections([stored])[0]; +} + +/** The configured solution; a server that cannot answer leaves the choice open. */ +async function configured( + client: LanguageClient | undefined, +): Promise { + try { + return await solution.configuredSolution(client); + } catch (err: unknown) { + log.warn(`Configured solution not read: ${getErrorMessage(err)}`); + return undefined; + } +} /** Build the loader; selection generations make a superseded pick a no-op. */ export function solutionLoader(deps: SolutionLoaderDeps): SolutionLoader { @@ -61,12 +87,26 @@ export function solutionLoader(deps: SolutionLoaderDeps): SolutionLoader { try { await reloadSidecars(deps.client(), selected.path); await deps.explorer()?.loadSolution(selected.path); + await deps.memory?.update(REMEMBERED_SOLUTION, selected.path); } finally { sharedState.endLoadPhase(phase); } }; + // `csharp.solution_path` settles the choice, then what this workspace last + // loaded; only a workspace with neither is asked. + // [SHARPLSP-ARCHITECTURE-PROJECTS-SOLUTION-PATH] const selectAndLoad = async (): Promise => { + const known = (await configured(deps.client())) ?? remembered(deps.memory); + if (known === undefined) { + await pickAndLoad(); + return; + } + log.info(`Opening the configured or remembered solution: ${known.path}`); + await load(known); + }; + + const pickAndLoad = async (): Promise => { const started = ++generation; const initialSolution = sharedState.solutionPath.value; // [SE-LOADING-FEEDBACK]: `window.withProgress` puts a native progress bar in @@ -113,7 +153,7 @@ export function solutionLoader(deps: SolutionLoaderDeps): SolutionLoader { log.traceInfo(`Solution file watcher active: ${SOLUTION_FILE_GLOB}`); }; - return { selectAndLoad, load, wireRefresh }; + return { selectAndLoad, pickAndLoad, load, wireRefresh }; } /** Scan the workspace; a failed scan must still clear the discovery phase. */ diff --git a/src/editors/vscode/src/solution.ts b/src/editors/vscode/src/solution.ts index 4d9b2b6f..a6ebe0b0 100644 --- a/src/editors/vscode/src/solution.ts +++ b/src/editors/vscode/src/solution.ts @@ -1,5 +1,7 @@ -import { fileNameOf } from './paths'; +import * as fs from 'node:fs'; +import { fileNameOf, isAbsolutePath, joinPath } from './paths'; import { CancellationTokenSource, workspace, window } from 'vscode'; +import { type LanguageClient } from 'vscode-languageclient/node'; import * as log from './log.js'; /** Result of solution discovery. */ @@ -10,6 +12,36 @@ export interface SolutionSelection { readonly name: string; } +/** The part of the server's effective configuration that names the solution. */ +interface SolutionConfiguration { + readonly csharp?: { readonly solution_path?: string }; +} + +/** + * The solution `csharp.solution_path` names (sharplsp.toml or an editor + * setting), when its file exists. The server already opened it, so the + * extension shows that one and never asks which of the workspace's solutions to + * load. A stale entry is no choice: the picker follows, as discovery follows on + * the server. Implements [SHARPLSP-ARCHITECTURE-PROJECTS-SOLUTION-PATH]. + */ +export async function configuredSolution( + client: LanguageClient | undefined, +): Promise { + // The server resolves a relative entry against ITS root: the client's folder. + const folder = client?.clientOptions.workspaceFolder ?? workspace.workspaceFolders?.[0]; + const root = folder?.uri.fsPath; + if (client === undefined || root === undefined) return undefined; + const resolved = await client.sendRequest('sharplsp/configuration', {}); + const configured = resolved.csharp?.solution_path ?? ''; + if (configured === '') return undefined; + const file = isAbsolutePath(configured) ? configured : joinPath(root, configured); + if (!fs.existsSync(file)) { + log.warn('csharp.solution_path names no existing file; asking which solution to load'); + return undefined; + } + return toSolutionSelections([file])[0]; +} + /** Discover .sln/.slnx files in the workspace and let the user pick if needed. */ export async function selectSolution(): Promise { const solutions = await findSolutions(); diff --git a/src/editors/vscode/src/test/suite/debug-test-expecto-e2e.test.ts b/src/editors/vscode/src/test/suite/debug-test-expecto-e2e.test.ts index 867a920c..5cb26920 100644 --- a/src/editors/vscode/src/test/suite/debug-test-expecto-e2e.test.ts +++ b/src/editors/vscode/src/test/suite/debug-test-expecto-e2e.test.ts @@ -17,7 +17,12 @@ import { stopInTestSource, useDebugTestFixture, } from './debug-test-harness'; -import { assertHandshakeOrder, type TestDebugFixture } from './debug-test-kit'; +import { + assertHandshakeOrder, + assertNoTerminalLeft, + type TestDebugFixture, +} from './debug-test-kit'; +import { TEST_DEBUG_TERMINAL_NAME } from '../../test-debug'; import { EXPECTO_ALL, EXPECTO_NESTED, EXPECTO_PASSING, EXPECTO_SOURCE } from './expecto-fixture'; import { DebugSessionRecorder } from './run-debug-kit'; import { deepEq, eq, neq } from './test-helpers'; @@ -96,5 +101,7 @@ suite('Debug an Expecto test — a breakpoint inside a testCase lambda', () => { eq(sessions.ours.length, 1, 'yet a real session attached and ran it'); deepEq(stubs.log.errorMessages, [], 'and nothing was reported as an error'); assertSessionEnded(recorder, 'the nested Expecto case'); + // Run to the END: the `dotnet test` run itself settles and closes its terminal. + await assertNoTerminalLeft(TEST_DEBUG_TERMINAL_NAME, 'the nested case run settled'); }); }); diff --git a/src/editors/vscode/src/test/suite/debug-test-harness.ts b/src/editors/vscode/src/test/suite/debug-test-harness.ts index 88036694..ed52a789 100644 --- a/src/editors/vscode/src/test/suite/debug-test-harness.ts +++ b/src/editors/vscode/src/test/suite/debug-test-harness.ts @@ -23,6 +23,7 @@ import { assertStopReason, topFrame, type Frame } from './debug-drive-kit'; import { assertBoundAtLines, useArmedRecorders } from './debug-suite-kit'; import { assertHandshakeOrder, + assertNoTerminalLeft, assertOneTestSession, breakpointAt, disposeDebugTestFixture, @@ -32,6 +33,7 @@ import { type FixtureRunner, type TestDebugFixture, } from './debug-test-kit'; +import { TEST_DEBUG_TERMINAL_NAME } from '../../test-debug'; import { DebugSessionRecorder, type ObservedSession } from './run-debug-kit'; import { activateTestExplorer, @@ -71,7 +73,13 @@ export function useDebugTestFixture( suiteTeardown(async function () { this.timeout(FIXTURE_BUILD_MS); - await disposeDebugTestFixture(fixture); + try { + // A debug run outlives its session by the `dotnet test` wrap-up; deleting + // the project under it strands that run and its terminal in the NEXT suite. + await assertNoTerminalLeft(TEST_DEBUG_TERMINAL_NAME, 'every debug run settled first'); + } finally { + await disposeDebugTestFixture(fixture); + } }); return useArmedRecorders(() => ({ fixture }), 'debug-test'); diff --git a/src/editors/vscode/src/test/suite/solution-configured.test.ts b/src/editors/vscode/src/test/suite/solution-configured.test.ts new file mode 100644 index 00000000..0f2cb447 --- /dev/null +++ b/src/editors/vscode/src/test/suite/solution-configured.test.ts @@ -0,0 +1,97 @@ +/** + * `csharp.solution_path` settles which solution a workspace opens. The server + * opens it before any document; the extension must show the SAME one and never + * ask which of the workspace's solutions to load. Asking anyway let one wrong + * pick point the Solution Explorer and the Test Explorer at a fixture solution + * while the server had the real one open — an empty Testing view. + * Implements [SHARPLSP-ARCHITECTURE-PROJECTS-SOLUTION-PATH], [SE-SOLUTION]. + */ +import * as assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { configuredSolution, findSolutions } from '../../solution.js'; +import { + activation, + assertSameFiles, + configurationClient, + NO_COMPILERS as BASE, + WorkspaceMemory, +} from './solution-loader-kit'; +import { removeDirRecursive } from './test-helpers'; +import { DEBUG_TEST_MS } from './test-timeouts'; +import { installUiStubs, type UiStubs } from './ui-stubs'; + +suite('A configured solution is loaded without asking [SE-SOLUTION]', () => { + let stubs: UiStubs; + setup(() => { + stubs = installUiStubs(); + }); + teardown(() => { + stubs.restore(); + }); + + test('csharp.solution_path beats the picker and a remembered pick; a stale one does neither', async function () { + this.timeout(DEBUG_TEST_MS); + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sharplsp-solution-')); + const toml = path.join(root, 'sharplsp.toml'); + const app = path.join(root, 'app', 'App.sln'); + const other = path.join(root, 'other', 'Other.slnx'); + for (const file of [app, other]) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, ''); + } + fs.writeFileSync(toml, BASE); + const client = configurationClient(root); + // Every pick is dismissed, so each time a loader asks it lands here. + const asked: unknown[] = []; + try { + await client.start(); + assert.ok((await findSolutions()).length >= 2, 'the premise: several solutions to ask about'); + + // 1 — nothing configured: the user is asked, and dismissing loads nothing. + const unconfigured: string[] = []; + assert.strictEqual(await configuredSolution(client), undefined, 'no setting, no choice'); + await activation(new WorkspaceMemory(), unconfigured, client, asked).selectAndLoad(); + assert.strictEqual(asked.length, 1, 'an unconfigured workspace asks once'); + assert.deepStrictEqual(unconfigured, [], 'a dismissed pick loads nothing'); + + // 2 — a relative entry resolves against the server's root; nobody is asked. + fs.writeFileSync(toml, `${BASE}solution_path = "app/App.sln"\n`); + const memory = new WorkspaceMemory(); + const configured: string[] = []; + const selection = await configuredSolution(client); + assertSameFiles([selection?.path], [app], 'the relative entry is the file under the root'); + assert.strictEqual(selection?.name, 'App.sln', 'named by its own file'); + await activation(memory, configured, client, asked).selectAndLoad(); + assert.strictEqual(asked.length, 1, 'a configured workspace never asks'); + assertSameFiles(configured, [app], 'the configured solution is the one loaded'); + + // 3 — an absolute entry that moves the setting beats what step 2 remembered. + fs.writeFileSync(toml, `${BASE}solution_path = ${JSON.stringify(other)}\n`); + const moved: string[] = []; + await activation(memory, moved, client, asked).selectAndLoad(); + assert.strictEqual(asked.length, 1, 'a moved setting never asks either'); + assert.deepStrictEqual(moved, [other], 'the setting wins over the remembered solution'); + assert.strictEqual((await configuredSolution(client))?.name, 'Other.slnx'); + + // 4 — a stale entry is no choice: the remembered solution, else the picker. + fs.writeFileSync(toml, `${BASE}solution_path = "gone/Gone.sln"\n`); + const stale: string[] = []; + assert.strictEqual( + await configuredSolution(client), + undefined, + 'a missing file is no choice', + ); + await activation(memory, stale, client, asked).selectAndLoad(); + assert.deepStrictEqual(stale, [other], 'the remembered solution stands in'); + assert.strictEqual(asked.length, 1, 'and still nobody is asked'); + await activation(new WorkspaceMemory(), stale, client, asked).selectAndLoad(); + assert.strictEqual(asked.length, 2, 'with nothing remembered the user is asked again'); + assert.deepStrictEqual(stale, [other], 'and a dismissed pick loads nothing more'); + } finally { + if (client.isRunning()) await client.stop(); + removeDirRecursive(root); + } + }); +}); diff --git a/src/editors/vscode/src/test/suite/solution-loader-kit.ts b/src/editors/vscode/src/test/suite/solution-loader-kit.ts new file mode 100644 index 00000000..8158ae02 --- /dev/null +++ b/src/editors/vscode/src/test/suite/solution-loader-kit.ts @@ -0,0 +1,87 @@ +/** + * One extension activation's solution loader over stand-ins for what outlives + * it (workspace storage) and what it drives (the Solution Explorer), shared by + * the suites that pin which solution an activation loads. [SE-SOLUTION] + */ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import type { LanguageClient } from 'vscode-languageclient/node'; +import { SharpLspClient } from '../../client'; +import { samePath } from '../../paths'; +import { type SolutionLoader, solutionLoader } from '../../solution-load.js'; +import type { SolutionExplorerProvider } from '../../tree.js'; +import { fakeFolder } from './run-debug-kit'; +import { findSharpLspBinary } from './test-helpers'; + +/** No compiler: a client that only answers which solution `sharplsp.toml` configures. */ +export const NO_COMPILERS = '[fsharp]\nenabled = false\n[csharp]\nenabled = false\n'; + +/** + * `actual` names exactly the files `expected` does, in order, under the product's + * own path identity: VS Code spells a Windows drive `c:`, the OS spells it `C:`. + * [SHARPLSP-ARCHITECTURE-PATHS] + */ +export function assertSameFiles( + actual: readonly (string | undefined)[], + expected: readonly string[], + why: string, +): void { + assert.strictEqual(actual.length, expected.length, `${why}: ${actual.join(', ')}`); + expected.forEach((file, at) => { + const seen = actual[at]; + assert.ok(seen !== undefined && samePath(seen, file), `${why}: ${String(seen)} is not ${file}`); + }); +} + +/** A real server rooted at `root`, so `sharplsp/configuration` reads ITS `sharplsp.toml`. */ +export function configurationClient(root: string): SharpLspClient { + const binary = findSharpLspBinary(); + assert.ok(binary, 'Test host must resolve a staged sharplsp binary'); + const outputChannel = vscode.window.createOutputChannel('Solution test', { log: true }); + return new SharpLspClient( + 'solution-test', + 'Solution test', + { command: binary, options: { cwd: root } }, + { documentSelector: [], workspaceFolder: fakeFolder(root), outputChannel }, + ); +} + +/** Workspace storage that outlives one activation, as `context.workspaceState` does. */ +export class WorkspaceMemory implements vscode.Memento { + private readonly values = new Map(); + public keys(): readonly string[] { + return [...this.values.keys()]; + } + public get(key: string, fallback?: T): T | undefined { + return this.values.has(key) ? (this.values.get(key) as T) : fallback; + } + public update(key: string, value: unknown): Thenable { + if (value === undefined) this.values.delete(key); + else this.values.set(key, value); + return Promise.resolve(); + } +} + +/** + * One activation's loader, recording in `loaded` what it hands the Solution + * Explorer and in `dismissed` each picker THIS loader showed and saw dismissed — + * a count no other activation's picker (the live extension's own) can reach. + */ +export function activation( + memory: vscode.Memento, + loaded: string[], + client?: LanguageClient, + dismissed: unknown[] = [], +): SolutionLoader { + const explorer = { + loadSolution: (solutionPath: string) => { + loaded.push(solutionPath); + return Promise.resolve(); + }, + // A dismissed pick falls back to solution buttons in the tree; nothing loads. + showSolutionPicker: (offered: unknown) => { + dismissed.push(offered); + }, + } as unknown as SolutionExplorerProvider; + return solutionLoader({ client: () => client, explorer: () => explorer, memory }); +} diff --git a/src/editors/vscode/src/test/suite/solution-memory.test.ts b/src/editors/vscode/src/test/suite/solution-memory.test.ts new file mode 100644 index 00000000..1f42e972 --- /dev/null +++ b/src/editors/vscode/src/test/suite/solution-memory.test.ts @@ -0,0 +1,56 @@ +/** + * The solution a user picks is remembered per workspace, so reloading the window + * reopens it instead of asking again. A repo holding many solutions (fixtures, + * samples, the real one) otherwise re-prompts on every reload, and one wrong + * pick silently empties the Solution Explorer and the Test Explorer. + * Implements [SE-SOLUTION]. + */ +import * as assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { findSolutions, type SolutionSelection } from '../../solution.js'; +import { activation, WorkspaceMemory } from './solution-loader-kit'; +import { installUiStubs, type UiStubs } from './ui-stubs'; + +/** The pick a user would make that is NOT the first offered. */ +function notFirst(offered: readonly SolutionSelection[]): SolutionSelection { + const picked = offered.at(-1); + assert.ok(picked !== undefined && offered.length >= 2, 'the premise: several solutions'); + return picked; +} + +suite('Solution memory across window reloads [SE-SOLUTION]', () => { + let stubs: UiStubs; + setup(() => { + stubs = installUiStubs(); + }); + teardown(() => { + stubs.restore(); + }); + + test('a reload reopens the solution the user picked instead of asking again', async () => { + const memory = new WorkspaceMemory(); + const offered = await findSolutions(); + const picked = notFirst(offered); + + // 1 — first open: several solutions, so the user is asked and picks one. + const firstLoads: string[] = []; + stubs.queuePick((items) => items.find((item) => labelOf(item) === picked.name)); + await activation(memory, firstLoads).selectAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 1, 'the first open asks once'); + assert.deepStrictEqual(firstLoads, [picked.path], 'the picked solution is the one loaded'); + assert.ok(fs.existsSync(picked.path), 'the picked solution is a real file'); + + // 2 — the window reloads: a NEW activation over the SAME workspace storage. + const reloadLoads: string[] = []; + await activation(memory, reloadLoads).selectAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 1, 'a reload never asks again'); + assert.deepStrictEqual(reloadLoads, [picked.path], 'the reload reopens the same solution'); + assert.strictEqual(path.basename(reloadLoads[0] ?? ''), picked.name, 'by its own file'); + }); +}); + +/** The label of a QuickPick item the solution picker offers. */ +function labelOf(item: unknown): string | undefined { + return (item as { readonly label?: string }).label; +} diff --git a/src/editors/vscode/src/test/suite/test-explorer-solution-choice.test.ts b/src/editors/vscode/src/test/suite/test-explorer-solution-choice.test.ts new file mode 100644 index 00000000..c24d0749 --- /dev/null +++ b/src/editors/vscode/src/test/suite/test-explorer-solution-choice.test.ts @@ -0,0 +1,226 @@ +/** + * The Testing view shows the tests of the solution the loader CHOSE — never a + * stale one, never nothing. One user journey over two real solutions (an F# + * xUnit one and a C# xUnit one) drives the REAL solution loader into the REAL + * Solution Explorer and Test Explorer: a pick, a window reload, a configured + * `csharp.solution_path`, a stale one, a deliberate switch and a dismissed pick. + * After each, the tree holds EXACTLY that solution's tests, under its assembly. + * Implements [SE-SOLUTION], [SHARPLSP-ARCHITECTURE-PROJECTS-SOLUTION-PATH], + * [TEST-DISCOVERY-FQN]. + */ +import * as assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as vscode from 'vscode'; +import type { SharpLspExtensionApi } from '../../extension.js'; +import { type SolutionLoader, solutionLoader } from '../../solution-load.js'; +import type { SharpLspClient } from '../../client'; +import { createSolution, projectXml, warmDiscovery, writeProject } from './dotnet-project-kit'; +import { + assertSameFiles, + configurationClient, + NO_COMPILERS, + WorkspaceMemory, +} from './solution-loader-kit'; +import { + activateTestExplorer, + clearTestTree, + collectLeafIds, + DISCOVERY_SETTLE_MS, + pollForIds, + teardownFixtureSolution, +} from './test-explorer-kit'; +import { assertExactLeafSet, assertSoleAssemblyRoot } from './test-explorer-assert-kit'; +import { removeDirRecursive } from './test-helpers'; +import { DOTNET_CLI_MS, FIXTURE_BUILD_MS } from './test-timeouts'; +import { CS, FS_FIXTURE, XUNIT_PAIR_IDS } from './test-explorer-xunit-pair'; +import { installUiStubs, type UiStubs } from './ui-stubs'; +import type { FixtureProject } from './test-explorer-fixtures'; + +/** The F# solution's tests (listed first: F# leads) and the C# solution's. */ +const FS_TESTS = XUNIT_PAIR_IDS.filter((id) => id.startsWith('Fs.')); +const CS_TESTS = XUNIT_PAIR_IDS.filter((id) => id.startsWith('Cs.')); +/** The workspace-storage key the loader remembers the solution under. */ +const REMEMBERED = 'sharplsp.solution'; + +/** One fixture solution: its file, its single test project and its tests. */ +interface Fixture { + readonly sln: string; + readonly project: string; + readonly tests: readonly string[]; +} + +async function fixtureSolution( + root: string, + name: string, + fixture: FixtureProject, + tests: readonly string[], +): Promise { + const dir = path.join(root, name, fixture.projectName); + const projectDir = writeProject( + dir, + fixture.projectFileName, + // F# compiles in declared order, so its one source is listed; C# globs its own. + projectXml( + fixture.packages, + ...(fixture.language === 'fsharp' ? [fixture.sourceFileName] : []), + ), + fixture.sourceFileName, + fixture.source, + ); + const sln = await createSolution(path.join(root, name), name, [projectDir]); + await warmDiscovery(sln, root); + return { sln, project: fixture.projectName, tests }; +} + +/** The QuickPick item a user clicks for `sln`, shaped as the picker offers it. */ +function pickOf(sln: string): () => unknown { + return () => ({ + label: path.basename(sln), + description: sln, + solution: { path: sln, name: path.basename(sln) }, + }); +} + +suite('Test Explorer follows the solution the loader chooses [SE-SOLUTION]', () => { + let api: SharpLspExtensionApi; + let root: string; + let fsharp: Fixture, csharp: Fixture; + let stubs: UiStubs; + let client: SharpLspClient; + + suiteSetup(async function () { + this.timeout(FIXTURE_BUILD_MS); + api = await activateTestExplorer(); + root = fs.mkdtempSync(path.join(os.tmpdir(), 'sharplsp-choice-')); + fs.writeFileSync(path.join(root, 'sharplsp.toml'), NO_COMPILERS); + fsharp = await fixtureSolution(root, 'FsSuite', FS_FIXTURE, FS_TESTS); + csharp = await fixtureSolution(root, 'CsSuite', CS, CS_TESTS); + client = configurationClient(root); + await client.start(); + // The user opens the Testing view: that, not a load, engages discovery. + await vscode.commands.executeCommand('workbench.view.testing.focus'); + await api.testController.activateAndDiscover(); + await api.testController.whenIdle(); + }); + + setup(() => { + stubs = installUiStubs(); + }); + + teardown(() => { + stubs.restore(); + }); + + suiteTeardown(async function () { + this.timeout(DOTNET_CLI_MS); + if (client.isRunning()) await client.stop(); + await teardownFixtureSolution(api, root, removeDirRecursive); + }); + + /** A fresh activation over `memory`, driving the live explorer and Test Explorer. */ + const activation = (memory: WorkspaceMemory, withClient = false): SolutionLoader => + solutionLoader({ + client: () => (withClient ? client : undefined), + explorer: () => api.explorerProvider, + memory, + }); + + /** Settle discovery, then assert the tree is EXACTLY `shown` with none of `hidden`. */ + async function assertShows(shown: Fixture, hidden: Fixture, why: string): Promise { + const ids = await pollForIds( + api.testController, + (seen) => + shown.tests.every((id) => seen.includes(id)) && + !hidden.tests.some((id) => seen.includes(id)), + ); + await api.testController.whenIdle(); + assert.ok(ids.length > 0, `${why}: the Testing view is never left empty`); + assertExactLeafSet(api.testController, shown.tests, why); + assertSoleAssemblyRoot(api.testController, shown.project, why); + for (const stale of hidden.tests) { + assert.ok( + !collectLeafIds(api.testController.items).includes(stale), + `${why}: no stale ${stale}`, + ); + } + } + + /** + * The window reloads: nothing is loaded, so the Testing view holds no test of + * either solution — at most the row explaining the folder's several projects. + */ + async function reloadWindow(): Promise { + await clearTestTree(api); + const leaves = collectLeafIds(api.testController.items); + for (const id of [...fsharp.tests, ...csharp.tests]) { + assert.ok(!leaves.includes(id), `a reload starts with no ${id}`); + } + assert.deepStrictEqual( + leaves.filter((id) => !id.startsWith('discovery-error:')), + [], + 'a reload starts with explanation rows only, never a test', + ); + } + + function setConfigured(entry: string): void { + fs.writeFileSync( + path.join(root, 'sharplsp.toml'), + `${NO_COMPILERS}solution_path = ${JSON.stringify(entry)}\n`, + ); + } + + test('pick, reload, configure, go stale, switch and dismiss: the tree is always the chosen solution', async function () { + this.timeout(FIXTURE_BUILD_MS * 2); + const memory = new WorkspaceMemory(); + await reloadWindow(); + + // 1 — first open: the user picks the F# solution; its tests, and only those, appear. + stubs.queuePick(pickOf(fsharp.sln)); + await activation(memory).pickAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 1, 'the first open asks once'); + assert.strictEqual(memory.get(REMEMBERED), fsharp.sln, 'the pick is remembered'); + await assertShows(fsharp, csharp, 'the picked F# solution'); + + // 2 — the window reloads: the remembered F# solution comes back without asking. + await reloadWindow(); + await activation(memory).selectAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 1, 'a reload never asks'); + await assertShows(fsharp, csharp, 'the remembered F# solution after a reload'); + + // 3 — sharplsp.toml names the C# solution: it beats the remembered F# one, unasked. + setConfigured(path.relative(root, csharp.sln)); + await reloadWindow(); + await activation(memory, true).selectAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 1, 'a configured solution never asks'); + assertSameFiles([memory.get(REMEMBERED)], [csharp.sln], 'and becomes the remembered one'); + await assertShows(csharp, fsharp, 'the configured C# solution'); + + // 4 — the configured file is gone: the remembered C# solution stands in, unasked. + setConfigured('Gone/Gone.sln'); + await reloadWindow(); + await activation(memory, true).selectAndLoad(); + assert.strictEqual( + stubs.log.quickPickItems.length, + 1, + 'a stale setting with a memory never asks', + ); + await assertShows(csharp, fsharp, 'the remembered C# solution behind a stale setting'); + + // 5 — Select Solution switches to F# on purpose: C#'s tests leave, F#'s arrive. + stubs.queuePick(pickOf(fsharp.sln)); + await activation(memory, true).pickAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 2, 'Select Solution always asks'); + assert.strictEqual(memory.get(REMEMBERED), fsharp.sln, 'the switch is remembered'); + await assertShows(fsharp, csharp, 'a deliberate switch from C# to F#'); + + // 6 — Select Solution again, dismissed: the F# tests stay; the view never empties. + stubs.queuePick(undefined); + await activation(memory, true).pickAndLoad(); + assert.strictEqual(stubs.log.quickPickItems.length, 3, 'the dismissed picker was shown'); + await new Promise((resolve) => setTimeout(resolve, DISCOVERY_SETTLE_MS)); + assert.strictEqual(memory.get(REMEMBERED), fsharp.sln, 'a dismissal forgets nothing'); + await assertShows(fsharp, csharp, 'a dismissed pick keeps the loaded solution'); + }); +}); diff --git a/src/editors/vscode/test-chunks.json b/src/editors/vscode/test-chunks.json index 80fe0ed2..1afe3145 100644 --- a/src/editors/vscode/test-chunks.json +++ b/src/editors/vscode/test-chunks.json @@ -160,6 +160,7 @@ "test-explorer-e2e.test.js", "test-explorer-refusals.test.js", "test-explorer-reactive.test.js", + "test-explorer-solution-choice.test.js", "test-explorer-multitarget.test.js", "test-explorer-windows.test.js", "test-explorer-parsers.test.js", @@ -240,6 +241,8 @@ "solution-explorer-namespaces.test.js", "solution-explorer-add-fsharp-file.test.js", "solution-explorer-linked-sources.test.js", + "solution-memory.test.js", + "solution-configured.test.js", "csharp-reference-import.test.js", "context-menus.test.js", "project-deps-watcher-e2e.test.js", diff --git a/src/sharplsp/tests/e2e_modules/configuration_live.rs b/src/sharplsp/tests/e2e_modules/configuration_live.rs index eed75830..98cea740 100644 --- a/src/sharplsp/tests/e2e_modules/configuration_live.rs +++ b/src/sharplsp/tests/e2e_modules/configuration_live.rs @@ -152,7 +152,13 @@ fn a_public_fsharp_value_another_project_uses_is_not_dead_in_a_monorepo() { /// Write `/.proj` with `properties` and `items`, and its one /// source `.` (`cs` or `fs`; F# lists it in compile order); returns the source. -fn write_project(root: &Path, name: &str, ext: &str, settings: [&str; 2], source: &str) -> PathBuf { +pub(super) fn write_project( + root: &Path, + name: &str, + ext: &str, + settings: [&str; 2], + source: &str, +) -> PathBuf { let [properties, items] = settings; let project = root.join(name); std::fs::create_dir_all(&project).expect("project directory"); @@ -195,13 +201,13 @@ fn dead_code_workspace() -> (tempfile::TempDir, PathBuf) { } /// Replace the workspace's `sharplsp.toml`. -fn write_configuration(root: &Path, text: &str) { +pub(super) fn write_configuration(root: &Path, text: &str) { std::fs::write(root.join("sharplsp.toml"), text).expect("write the workspace configuration"); } /// A real server over the dead-code workspace, with every message it sent. -struct LiveSession { - client: LspClient, +pub(super) struct LiveSession { + pub(super) client: LspClient, uri: String, /// The dead-code rule of the source's language: `SLSPF0101` or `SLSPC0101`. code: &'static str, @@ -210,7 +216,7 @@ struct LiveSession { impl LiveSession { /// Start the server with pull diagnostics and wait until the project loads. - fn start(root: &Path, source: &Path, code: &'static str) -> Self { + pub(super) fn start(root: &Path, source: &Path, code: &'static str) -> Self { let mut client = LspClient::spawn_in(Stdio::null(), Some(root)); let initialized = client.initialize_with_capabilities( json!(path_to_file_uri(root)), @@ -261,11 +267,18 @@ impl LiveSession { } /// Pull until exactly `expected` is reported dead, within [`NOTICED`]. - fn await_dead(&mut self, expected: &[(&str, u64)]) { + pub(super) fn await_dead(&mut self, expected: &[(&str, u64)]) { let expected = owned(expected); - self.wait_for(NOTICED, "the new analyzer settings", |session| { - session.dead() == expected - }); + let mut last = Vec::new(); + let deadline = Instant::now() + NOTICED; + while Instant::now() < deadline { + last = self.dead(); + if last == expected { + return; + } + std::thread::sleep(Duration::from_millis(200)); + } + panic!("expected {expected:?} dead; the last pull reported {last:?}"); } /// The restart warning received so far, if any. diff --git a/src/sharplsp/tests/e2e_modules/dead_code_cross_language.rs b/src/sharplsp/tests/e2e_modules/dead_code_cross_language.rs new file mode 100644 index 00000000..fe4cb0d3 --- /dev/null +++ b/src/sharplsp/tests/e2e_modules/dead_code_cross_language.rs @@ -0,0 +1,172 @@ +//! [ANALYZERS-TRUTH] across languages, through the real host and both sidecars: +//! neither compiler sees the other language's callers, so a project the other +//! language references reports no unused PUBLIC code — at open, and as project +//! references are added or removed later. +use super::configuration_live::{write_configuration, write_project, LiveSession}; +use super::*; + +/// [ANALYZERS-TRUTH]: a public F# function that only C# calls is live. +/// FCS sees no C# caller, so the F# analyzer alone would call it dead — in a +/// monorepo, as an ERROR on code the solution uses. +#[test] +fn a_public_fsharp_function_only_csharp_calls_is_not_dead_in_a_monorepo() { + require_dotnet(); + let workspace = tempfile::tempdir().expect("real mixed solution"); + let root = workspace.path(); + let library = write_project( + root, + "Lib", + "fs", + ["Library", ""], + "module Lib.Values\n\nlet used () = 1\n\nlet orphan () = 2\n", + ); + let _app = mixed_app( + root, + "cs", + "fs", + "internal static class Program\n{\n private static int Main() => Lib.Values.used();\n}\n", + true, + ); + write_configuration(root, "[analyzers]\ndead_code = true\nmonorepo = true\n"); + let mut session = LiveSession::start(root, &library, "SLSPF0101"); + + // C#'s call keeps `used` alive. FCS cannot see C# callers, so neither can it + // prove `orphan` unused: [ANALYZERS-TRUTH] prefers silence to a false error. + session.await_dead(&[]); + session.client.shutdown_and_exit(); +} + +/// The other direction: Roslyn sees no F# caller, so a public C# type only F# +/// uses must not be reported dead either. +#[test] +fn a_public_csharp_type_only_fsharp_uses_is_not_dead_in_a_monorepo() { + require_dotnet(); + let workspace = tempfile::tempdir().expect("real mixed solution"); + let root = workspace.path(); + let library = write_project( + root, + "Lib", + "cs", + ["Library", ""], + "namespace Lib;\n\npublic sealed class Used { }\n\npublic sealed class Orphan { }\n", + ); + let _app = mixed_app( + root, + "fs", + "cs", + "module App.Program\n\n[]\nlet main _ =\n Lib.Used() |> ignore\n 0\n", + true, + ); + write_configuration(root, "[analyzers]\ndead_code = true\nmonorepo = true\n"); + let mut session = LiveSession::start(root, &library, "SLSPC0101"); + + // F#'s use keeps `Used` alive; `Orphan` is reported only if the analyzer can + // prove no F# code uses it, which it cannot — so neither is reported. + session.await_dead(&[]); + session.client.shutdown_and_exit(); +} + +/// [ANALYZERS-TRUTH] as the solution changes: a C# project that starts calling an +/// F# library silences that library's public dead code, and one that stops calling +/// it brings the errors back. The F# compiler never reloads for a C# project edit, +/// so it must notice the edited reference itself. +#[test] +fn a_csharp_reference_added_or_removed_later_moves_fsharp_public_dead_code() { + require_dotnet(); + let workspace = tempfile::tempdir().expect("real mixed solution"); + let root = workspace.path(); + let library = write_project( + root, + "Lib", + "fs", + ["Library", ""], + "module Lib.Values\n\nlet used () = 1\n\nlet orphan () = 2\n", + ); + let app = mixed_app( + root, + "cs", + "fs", + "internal static class Program\n{\n private static int Main() => 0;\n}\n", + false, + ); + write_configuration(root, "[analyzers]\ndead_code = true\nmonorepo = true\n"); + let mut session = LiveSession::start(root, &library, "SLSPF0101"); + + // 1. Nothing references the library: both public functions are dead, as errors. + session.await_dead(&[("orphan", 1), ("used", 1)]); + + // 2. The C# app now references and calls it: F# cannot see that caller, so silence. + let _app = mixed_app(root, "cs", "fs", "internal static class Program\n{\n private static int Main() => Lib.Values.used();\n}\n", true); + session.await_dead(&[]); + + // 3. The reference is removed again: the errors come back. + let _app = mixed_app( + root, + "cs", + "fs", + "internal static class Program\n{\n private static int Main() => 0;\n}\n", + false, + ); + session.await_dead(&[("orphan", 1), ("used", 1)]); + assert!(app.exists(), "the app source stayed in place throughout"); + session.client.shutdown_and_exit(); +} + +/// The other direction: an F# project that starts or stops using a C# library moves +/// the library's public dead code, though Roslyn never reloads for an F# project edit. +#[test] +fn an_fsharp_reference_added_or_removed_later_moves_csharp_public_dead_code() { + require_dotnet(); + let workspace = tempfile::tempdir().expect("real mixed solution"); + let root = workspace.path(); + let library = write_project( + root, + "Lib", + "cs", + ["Library", ""], + "namespace Lib;\n\npublic sealed class Used { }\n\npublic sealed class Orphan { }\n", + ); + let fsharp = "module App.Program\n\n[]\nlet main _ = 0\n"; + let _app = mixed_app(root, "fs", "cs", fsharp, false); + write_configuration(root, "[analyzers]\ndead_code = true\nmonorepo = true\n"); + let mut session = LiveSession::start(root, &library, "SLSPC0101"); + + // 1. Nothing references the library: both public types are dead, as errors. + session.await_dead(&[("Orphan", 1), ("Used", 1)]); + + // 2. The F# app now references it: Roslyn cannot see F# callers, so silence. + let _app = mixed_app(root, "fs", "cs", fsharp, true); + session.await_dead(&[]); + + // 3. The reference is removed again: Roslyn reports both types again. + let _app = mixed_app(root, "fs", "cs", fsharp, false); + session.await_dead(&[("Orphan", 1), ("Used", 1)]); + session.client.shutdown_and_exit(); +} + +/// Write the `App` project in `app_ext` with `source`, referencing `Lib` (written in +/// `lib_ext`) when `referenced`, and once the `Mixed.slnx` holding both; returns the source. +fn mixed_app(root: &Path, app_ext: &str, lib_ext: &str, source: &str, referenced: bool) -> PathBuf { + let reference = format!( + r#""# + ); + let items = if referenced { reference.as_str() } else { "" }; + let app = write_project( + root, + "App", + app_ext, + ["Exe", items], + source, + ); + // Written once: a rewritten solution would reload BOTH compilers and hide + // whether the other language noticed the project edit on its own. + let solution = root.join("Mixed.slnx"); + if !solution.exists() { + std::fs::write( + solution, + format!("\n \n \n\n"), + ) + .expect("write the solution"); + } + app +} diff --git a/src/sharplsp/tests/e2e_modules/mod.rs b/src/sharplsp/tests/e2e_modules/mod.rs index 13a5fe1f..f8ad2823 100644 --- a/src/sharplsp/tests/e2e_modules/mod.rs +++ b/src/sharplsp/tests/e2e_modules/mod.rs @@ -54,6 +54,7 @@ pub mod configuration_session; pub mod coverage_boost; pub mod coverage_boost2; pub mod coverage_boost3; +pub mod dead_code_cross_language; pub mod definition; pub mod definition_cross_language; pub mod definition_full_stack; diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/RegexHighlightingTests.cs b/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/RegexHighlightingTests.cs index 987ddfc0..871bd6e1 100644 --- a/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/RegexHighlightingTests.cs +++ b/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/RegexHighlightingTests.cs @@ -183,6 +183,7 @@ private static string Syntax(string pattern) [InlineData(@"[]a][\]][a-z-[aeiou]]x", @"[]a] [\]] [a-z-[aeiou]]")] [InlineData("[a[b]x+", "[a[b] +")] [InlineData("[[]x[a[-[a]]y", "[[] [a[-[a]]")] + [InlineData(@"[\\-[x]]y[a\-[b]z", @"[\\-[x]] [a\-[b]")] [InlineData("(a)(?:b)(?=c)(?!d)(?<=e)(?g)", "( ) (?: ) (?= ) (?! ) (?<= ) (? )")] [InlineData("(?x)(?'m'y)(?i)(?i-m:z)(?#note)", "(? ) (?'m' ) (?i ) (?i-m: ) (?#note)")] [InlineData("a*b+c?d*?e+?f??", "* + ? *? +? ??")] diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/DeadCodeAnalyzer.cs b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/DeadCodeAnalyzer.cs index 50fa8a29..8c831930 100644 --- a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/DeadCodeAnalyzer.cs +++ b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/DeadCodeAnalyzer.cs @@ -23,6 +23,13 @@ namespace SharpLsp.Sidecar.CSharp.Workspace; /// A type is referenced when it or any of its members is referenced — member uses /// (extension calls, static access, generated partials) never name the type. /// +/// +/// How public deadness is judged: only in a , and never for a +/// project the other language references (), whose +/// callers Roslyn cannot see. [ANALYZERS-TRUTH] +/// +internal readonly record struct DeadCodeMode(bool Monorepo, bool SharedAcrossLanguages); + internal static class DeadCodeAnalyzer { /// Diagnostic code for unused C# symbols (see the spec). @@ -32,7 +39,7 @@ internal static class DeadCodeAnalyzer public static async Task> AnalyzeAsync( Document document, SearchScope scope, - bool monorepo, + DeadCodeMode mode, CancellationToken ct ) { @@ -59,7 +66,7 @@ CancellationToken ct continue; } - var diagnostic = await ClassifyAsync(symbol, node, filePath, scope, monorepo, ct) + var diagnostic = await ClassifyAsync(symbol, node, filePath, scope, mode, ct) .ConfigureAwait(false); if (diagnostic is not null) { @@ -150,13 +157,15 @@ private static bool HasDeclaredAttribute(ISymbol member) SyntaxNode node, string filePath, SearchScope scope, - bool monorepo, + DeadCodeMode mode, CancellationToken ct ) { + var monorepo = mode.Monorepo; var isPublic = Visibility(symbol) == true; - // Public symbols are an external API unless the repo is the whole world. - if (isPublic && !monorepo) + // Public symbols are an external API unless the repo is the whole world, and + // unprovable when the other language — whose callers Roslyn cannot see — uses them. + if (isPublic && (!monorepo || mode.SharedAcrossLanguages)) { return null; } diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/RegexPatternTokens.cs b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/RegexPatternTokens.cs index 83315c08..daa40abc 100644 --- a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/RegexPatternTokens.cs +++ b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/RegexPatternTokens.cs @@ -107,10 +107,22 @@ private static int ClassEnd(string pattern, int at) /// /// True when the [ at opens a subtraction (-[…]). Any /// other [ inside a class is a literal member: [a[b] ends at its first ]. + /// The - is escaped only behind an ODD run of backslashes: [\\-[x]] subtracts. /// private static bool OpensSubtraction(string pattern, int at) { - return at > 0 && pattern[at - 1] == '-' && (at < 2 || pattern[at - 2] != '\\'); + return at > 0 && pattern[at - 1] == '-' && BackslashesBefore(pattern, at - 1) % 2 == 0; + } + + /// How many backslashes run immediately before . + private static int BackslashesBefore(string pattern, int at) + { + var start = at; + while (start > 0 && pattern[start - 1] == '\\') + { + start--; + } + return at - start; } /// ( with its prefix: (?:, (?=, (?<name>, inline options; a comment group whole. diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.Diagnostics.cs b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.Diagnostics.cs index 93dd8a10..a3479646 100644 --- a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.Diagnostics.cs +++ b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.Diagnostics.cs @@ -1,6 +1,7 @@ using Microsoft.CodeAnalysis; using Serilog; using SharpLsp.Sidecar.Common; +using SharpLsp.Sidecar.Common.Solutions; using DiagnosticsResult = Outcome.Result< System.Collections.Generic.List, string @@ -18,6 +19,12 @@ internal sealed partial class WorkspaceManager private bool _deadCodeEnabled; private bool _monorepo; + /// + /// The workspace's C# projects an F# project references: Roslyn cannot see their F# + /// callers, so their public symbols are never reported unused (#617). [ANALYZERS-TRUTH] + /// + private CrossLanguageReferences _crossLanguage = CrossLanguageReferences.None; + /// /// Whether project analyzers — the SDK/NuGet analyzers the project references and /// the IDE style analyzers — report beside the compiler diagnostics. Toggled by @@ -41,6 +48,12 @@ public void ConfigureDiagnostics(bool analyzersEnabled) /// Defaults are off so direct test construction never gets dead-code diagnostics /// unless explicitly enabled; the host always configures in production. /// + /// Record which C# projects of F# code references. + private async Task RecordCrossLanguageReferencesAsync(string path, CancellationToken ct) + { + _crossLanguage = await CrossLanguageReferences.OfAsync(path, ct).ConfigureAwait(false); + } + public void ConfigureAnalyzers(bool deadCode, bool monorepo) { _deadCodeEnabled = deadCode; @@ -212,8 +225,9 @@ CancellationToken ct var scope = await SearchScope .OfAsync(document, _activeFrameworks, ct) .ConfigureAwait(false); + var sharedWithFSharp = _crossLanguage.Contains(document.Project.FilePath ?? ""); return await DeadCodeAnalyzer - .AnalyzeAsync(document, scope, _monorepo, ct) + .AnalyzeAsync(document, scope, new DeadCodeMode(_monorepo, sharedWithFSharp), ct) .ConfigureAwait(false); } diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.cs b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.cs index 08189b3a..c84a6d63 100644 --- a/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.cs +++ b/src/sidecars/SharpLsp.Sidecar.CSharp/Workspace/WorkspaceManager.cs @@ -326,6 +326,7 @@ private async Task OpenCoreAsync(string path, CancellationToken ct) var (target, candidates) = +discovered; var standalone = (+discovered).Projects; + await RecordCrossLanguageReferencesAsync(path, ct).ConfigureAwait(false); if (target is null) { diff --git a/src/sidecars/SharpLsp.Sidecar.Common.Tests/CrossLanguageReferencesTests.cs b/src/sidecars/SharpLsp.Sidecar.Common.Tests/CrossLanguageReferencesTests.cs new file mode 100644 index 00000000..6b33379c --- /dev/null +++ b/src/sidecars/SharpLsp.Sidecar.Common.Tests/CrossLanguageReferencesTests.cs @@ -0,0 +1,130 @@ +#pragma warning disable RS1035 // File IO banned for analyzers - tests own temp fixtures +using SharpLsp.Sidecar.Common.Solutions; + +#pragma warning disable CA1515 // Types can be internal + +namespace SharpLsp.Sidecar.Common.Tests; + +/// +/// [ANALYZERS-TRUTH] across languages: which projects the OTHER language references, +/// read from real solution, project and folder targets on disk, and re-read as the +/// referencing project file is edited (#617). +/// +public sealed class CrossLanguageReferencesTests : IDisposable +{ + private readonly string _root = NativePaths.Temp($"sharplsp-crosslang-{Guid.NewGuid():N}"); + private readonly string _fsLib; + private readonly string _csLib; + private readonly string _csApp; + + public CrossLanguageReferencesTests() + { + _ = Directory.CreateDirectory(_root); + _fsLib = Project("FsLib", "FsLib.fsproj"); + _csLib = Project("CsLib", "CsLib.csproj"); + _csApp = Project("CsApp", "CsApp.csproj"); + } + + public void Dispose() + { + try + { + Directory.Delete(_root, true); + } + catch (IOException) { } + } + + [Fact] + public async Task A_reference_from_the_other_language_is_followed_as_the_project_file_is_edited() + { + var solution = Solution( + "", + "", + "" + ); + var references = await CrossLanguageReferences.OfAsync(solution, CancellationToken.None); + + // 1. Nothing references anything: no project is shared. + Assert.False(references.Contains(_fsLib), "an unreferenced F# library is no one's"); + Assert.False(references.Contains(_csLib), "an unreferenced C# library is no one's"); + + // 2. The C# app references BOTH libraries: only the F# one crosses a language. + Rewrite(_csApp, "../FsLib/FsLib.fsproj", "../CsLib/CsLib.csproj"); + Assert.True(references.Contains(_fsLib), "C# now calls into the F# library"); + Assert.False(references.Contains(_csLib), "C# calling C# is Roslyn's own to judge"); + Assert.False(references.Contains(_csApp), "nothing references the app"); + + // 3. The reference is removed again: the F# library is its compiler's alone. + Rewrite(_csApp, "../CsLib/CsLib.csproj"); + Assert.False(references.Contains(_fsLib), "the removed reference is forgotten"); + Assert.False(references.Contains(_csLib), "and the same-language one never counted"); + } + + [Fact] + public async Task Folders_and_project_files_are_targets_and_nothing_else_is() + { + Rewrite(_csApp, "../FsLib/FsLib.fsproj"); + var folder = await CrossLanguageReferences.OfAsync(_root, CancellationToken.None); + Assert.True(folder.Contains(_fsLib), "a folder holds every project beneath it"); + Assert.False(folder.Contains(_csApp), "and the app is referenced by none"); + + var file = await CrossLanguageReferences.OfAsync(_csApp, CancellationToken.None); + Assert.True(file.Contains(_fsLib), "a project file is its own workspace"); + + var missing = NativePaths.Resolve(_root, "Gone.csproj"); + Assert.False( + (await CrossLanguageReferences.OfAsync(missing, CancellationToken.None)).Contains( + _fsLib + ), + "a missing target has no projects" + ); + Assert.False( + CrossLanguageReferences.None.Contains(_fsLib), + "no workspace references nothing" + ); + } + + [Fact] + public async Task A_solution_that_cannot_be_read_has_no_projects() + { + Rewrite(_csApp, "../FsLib/FsLib.fsproj"); + var broken = NativePaths.Resolve(_root, "Broken.slnx"); + await File.WriteAllTextAsync(broken, ""); + return path; + } + + private string Solution(params string[] projects) + { + var path = NativePaths.Resolve(_root, "Mixed.slnx"); + File.WriteAllText(path, $"{string.Concat(projects)}"); + return path; + } + + /// Rewrite to reference , as a later edit. + private static void Rewrite(string project, params string[] includes) + { + var items = string.Concat( + includes.Select(include => $"") + ); + var previous = File.GetLastWriteTimeUtc(project); + File.WriteAllText( + project, + $"{items}" + ); + // A coarse filesystem clock must still see an edit. + File.SetLastWriteTimeUtc(project, previous.AddSeconds(2)); + } +} diff --git a/src/sidecars/SharpLsp.Sidecar.Common/Solutions/CrossLanguageReferences.cs b/src/sidecars/SharpLsp.Sidecar.Common/Solutions/CrossLanguageReferences.cs new file mode 100644 index 00000000..c8fa4813 --- /dev/null +++ b/src/sidecars/SharpLsp.Sidecar.Common/Solutions/CrossLanguageReferences.cs @@ -0,0 +1,87 @@ +using System.Collections.Concurrent; + +namespace SharpLsp.Sidecar.Common.Solutions; + +/// +/// The projects of a workspace that a project in the OTHER .NET language references: a +/// C# project an F# project calls into, or an F# project a C# project calls into. +/// +/// Neither compiler sees the other language's callers, so neither dead-code analyzer can +/// prove a public symbol of such a project unused: [ANALYZERS-TRUTH] prefers silence to a +/// false error, so these projects report no unused PUBLIC code (#617). Private and +/// internal code stays the declaring compiler's to judge. +/// +/// A compiler never reloads for the other language's project edits, so each project's +/// references are re-read whenever its file has been written since they were last read. +/// +public sealed class CrossLanguageReferences +{ + private readonly IReadOnlyList _projects; + private readonly ConcurrentDictionary _read = new(NativePaths.Comparer); + + private CrossLanguageReferences(IReadOnlyList projects) + { + _projects = projects; + } + + /// No workspace: nothing is referenced across languages. + public static CrossLanguageReferences None { get; } = new([]); + + /// The projects of — a solution, a project file or a folder. + public static async Task OfAsync(string target, CancellationToken ct) + { + return new(await ProjectsOfAsync(target, ct).ConfigureAwait(false)); + } + + /// True when a project of the other language references now. + public bool Contains(string project) + { + return _projects.Any(referencing => + IsFSharp(referencing) != IsFSharp(project) + && ReferencesOf(referencing).Contains(project, NativePaths.Comparer) + ); + } + + /// The projects references, re-read when its file changed. + private IReadOnlyList ReferencesOf(string project) + { + var written = File.GetLastWriteTimeUtc(project); + return _read + .AddOrUpdate( + project, + _ => new(written, ProjectReferences.ReadReferencedProjects(project)), + (_, known) => + known.Written == written + ? known + : new(written, ProjectReferences.ReadReferencedProjects(project)) + ) + .Referenced; + } + + private static bool IsFSharp(string project) + { + return NativePaths.HasExtension(project, ".fsproj"); + } + + /// The project files a target holds, in both languages. + private static async Task> ProjectsOfAsync( + string target, + CancellationToken ct + ) + { + if (SolutionFileReader.IsSolutionFile(target)) + { + var read = await SolutionFileReader.ReadAsync(target, ct).ConfigureAwait(false); + return read.Match>( + solution => [.. solution.Projects.Select(project => project.Path)], + _ => [] + ); + } + return Directory.Exists(target) ? NativePaths.WorkspaceFiles(target, ".csproj", ".fsproj") + : File.Exists(target) ? [target] + : []; + } + + /// A project's references as of the write time they were read at. + private sealed record Read(DateTime Written, IReadOnlyList Referenced); +} diff --git a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpAnalyzers.fs b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpAnalyzers.fs index 4563e2ea..c1149baa 100644 --- a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpAnalyzers.fs +++ b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpAnalyzers.fs @@ -28,14 +28,18 @@ type AnalyzerConfig = DeadCodeEnabled: bool /// Whether the workspace is the entire world (monorepo). When true, unused /// public symbols are dead-code errors; when false they are skipped. - Monorepo: bool } + Monorepo: bool + /// Whether the declaring project is referenced from C#, whose callers FCS cannot + /// see: its public symbols can never be proven unused (#617). [ANALYZERS-TRUTH] + SharedAcrossLanguages: bool } /// Conservative defaults: dead-code on, monorepo off (public API preserved). - static member Default = { DeadCodeEnabled = true; Monorepo = false } + static member Default = + { DeadCodeEnabled = true; Monorepo = false; SharedAcrossLanguages = false } /// Build a config from the wire flags the host pushes via `analyzers/configure`. static member Create(deadCode: bool, monorepo: bool) = - { DeadCodeEnabled = deadCode; Monorepo = monorepo } + { DeadCodeEnabled = deadCode; Monorepo = monorepo; SharedAcrossLanguages = false } /// Stable identity for a declaration site, used to test whether a symbol is /// referenced anywhere. Two uses of the same symbol share a declaration range. @@ -88,8 +92,9 @@ let private classifyDead match symbol with | :? FSharpMemberOrFunctionOrValue as mfv when isDeadCodeCandidate mfv -> let isPublic = mfv.Accessibility.IsPublic - // Public symbols are only dead when the monorepo is the whole world. - if isPublic && not config.Monorepo then + // Public symbols are only dead when the monorepo is the whole world, and never + // provably so when C# — whose callers FCS cannot see — references the project. + if isPublic && (not config.Monorepo || config.SharedAcrossLanguages) then None else let severity = if config.Monorepo then "Error" else "Warning" @@ -157,6 +162,11 @@ let deadCodeInFile (workspace: FSharpWorkspace.FSharpWorkspaceState) (config: An else let scope = FSharpWorkspace.queryScope workspace filePath let projects = if config.Monorepo then scope else List.truncate 1 scope + let shared = + scope + |> List.tryHead + |> Option.exists (fun own -> workspace.CrossLanguage.Contains own.ProjectFileName) + let config = { config with SharedAcrossLanguages = shared } let! checkedProjects = FSharpWorkspace.checkAllWithCancellation workspace projects ct let uses = checkedProjects |> Seq.collect _.GetAllUsesOfAllSymbols() |> Array.ofSeq return deadCodeDiagnosticsForFile config uses filePath diff --git a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspace.fs b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspace.fs index 3524b09f..2e4100b6 100644 --- a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspace.fs +++ b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspace.fs @@ -11,6 +11,7 @@ open FSharp.Compiler.EditorServices open FSharp.Compiler.Symbols open FSharp.Compiler.Text open Serilog +open SharpLsp.Sidecar.Common.Solutions open SharpLsp.Sidecar.Common /// Definition result: file path + start line/col + end line/col (0-based). @@ -59,6 +60,9 @@ type FSharpWorkspaceState = /// .fsproj is re-evaluated once, and ownership lookups never spawn MSBuild per /// request. Lazy, so concurrent first lookups share ONE evaluation. [NETFX-PROJECTS-FSHARP] CompileSources: ConcurrentDictionary>>> + /// Which of the workspace's F# projects a C# project references, whose public symbols + /// the dead-code analyzer can never prove unused (#617). [ANALYZERS-TRUTH] + mutable CrossLanguage: CrossLanguageReferences /// Every referenced assembly's public entities, by assembly file: built once, /// rebuilt when that file changes. [SHARPLSP-FEATURES-INTELLIGENCE-COMPLETION-OPEN] Entities: EntityCache @@ -93,6 +97,7 @@ let create () : FSharpWorkspaceState = CSharpBuilds = ConcurrentDictionary(NativePaths.Comparer) CSharpBuffers = ConcurrentDictionary(NativePaths.Comparer) CompileSources = ConcurrentDictionary(NativePaths.Comparer) + CrossLanguage = CrossLanguageReferences.None Entities = EntityCache() } /// The project that compiles `filePath`, if any loaded project does. diff --git a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspaceLoading.fs b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspaceLoading.fs index c10f1e3a..44493ef0 100644 --- a/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspaceLoading.fs +++ b/src/sidecars/SharpLsp.Sidecar.FSharp/FSharpWorkspaceLoading.fs @@ -10,6 +10,7 @@ open System.Threading.Tasks open FSharp.Compiler.CodeAnalysis open Serilog open SharpLsp.Sidecar.Common +open SharpLsp.Sidecar.Common.Solutions open SharpLsp.Sidecar.FSharp.FSharpOwningEpoch open SharpLsp.Sidecar.FSharp.FSharpWorkspace @@ -99,6 +100,13 @@ let private loadDiscoveredProject (state: FSharpWorkspaceState) (discovered: Res return Error message } +/// Record which of `path`'s F# projects a C# project references. [ANALYZERS-TRUTH] +let private recordCrossLanguageReferences (state: FSharpWorkspaceState) (path: string) ct = + task { + let! referenced = CrossLanguageReferences.OfAsync(path, ct) + state.CrossLanguage <- referenced + } + /// Load a project, solution, workspace directory, or self-describing script. let loadProjectWithCancellation (state: FSharpWorkspaceState) (path: string) (ct: CancellationToken) = task { @@ -108,6 +116,7 @@ let loadProjectWithCancellation (state: FSharpWorkspaceState) (path: string) (ct if File.Exists(path) && FSharpProjectLoading.isScriptPath path then return! loadScript state (NativePaths.NormalizeFullPath path) ct else + do! recordCrossLanguageReferences state path ct let! discovered = FSharpProjectLoading.discoverFsprojFiles path ct return! loadDiscoveredProject state discovered true ct with ex -> @@ -134,6 +143,7 @@ let loadWorkspaceWithCancellation (state: FSharpWorkspaceState) path autoRestore if FSharpProjectLoading.isScriptPath path then return! loadProjectWithCancellation state path ct else + do! recordCrossLanguageReferences state path ct let! discovered = FSharpProjectLoading.discoverFsprojFiles path ct match discovered with | Error message -> return Error message