diff --git a/TODO.md b/TODO.md index e45331c..13280ce 100644 --- a/TODO.md +++ b/TODO.md @@ -925,10 +925,45 @@ and are not gaps. copy of the EDA search order) and `normalize` became public; the standing request to extract one `lucisv_core::path::normalize` for the three private copies is still open. -- [ ] **`workspace/didChangeWorkspaceFolders`** — roots are read once +- [x] **`workspace/didChangeWorkspaceFolders`** — roots are read once at initialize; adding/removing a folder mid-session is ignored. -- [ ] **`workspace/configuration` (server-pull)** — we rely solely on + → delivered 2026-08-27 by `docs/features/folders-and-config/README.md`: + `workspace.workspaceFolders { supported, changeNotifications }` + + `Workspace::change_roots`. One rescan per *notification* — the event + carries both lists, and the progress bar, the code-lens refresh and the + diagnostics generation all ride inside the existing `reindex()`. An + event that leaves the root set where it was costs nothing: a folder + already held, one never held, an empty event, params that do not parse, + a non-`file:` folder. A removed folder's files leave the index while + its **open buffers stay open and keep being diagnosed** — no code was + needed for that, since `collect_sources` appends every open document + after the scope ladder has spoken — and removing the *last* folder + simply becomes rung 3 of that ladder, the rootless case. The watcher + determination is recorded there: the source glob is a base-less string + pattern and so is workspace-wide (no re-registration), while the + filelist watcher is an absolute path anchored at the first root and is + re-registered when a folder change moves it. `state.rs` gained exactly + one 8-line method. +- [x] **`workspace/configuration` (server-pull)** — we rely solely on push `didChangeConfiguration`; clients are moving to the pull model. + → delivered 2026-08-27 by `docs/features/folders-and-config/README.md`: + one `workspace/configuration` for the `lucisv` section at startup and + again on every *empty* `didChangeConfiguration` (the 3.17 client's + "something changed, ask me"), gated on `workspace.configuration`. A + push with a payload still applies directly, so the legacy path is + untouched; a client without the capability keeps exactly today's + behaviour, empty-payload semantics included. **One parser** — the + answer's entry 0 is wrapped back into the push shape and read by the + same `settings::from_payload` — and **one applier**, so `exclude`/ + `filelist` cost the same rescan and the same watcher re-registration + whichever door they came in. An error, a `null`, an empty array or junk + all resolve to the defaults and none of them says anything to the user. + The outstanding-request tracking was refactored from `applying: + HashMap` to `pending: HashMap`, + one map and one `match`, with the three-way interleave + (applyEdit + progress create + configuration) under test. Known and + stated, not fixed: a pulled setting can land after the first index + build, exactly as a pushed one always could. - [ ] **3.18 additions:** `textDocument/rangesFormatting` (multi-range, feeds format-modified-lines), snippet edits in `WorkspaceEdit` (would improve `addPort` cursor placement), and diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 71b163a..999115e 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -58,7 +58,7 @@ use lsp_types::{ SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, - WorkDoneProgressOptions, WorkspaceServerCapabilities, + WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities, }; use crate::server::{ClientAbilities, Server}; @@ -80,6 +80,7 @@ fn main() -> Result<(), Box> { work_done_progress: work_done_progress_support(¶ms), code_lens_refresh: code_lens_refresh_support(¶ms), show_document: show_document_support(¶ms), + configuration: configuration_support(¶ms), }; connection.initialize_finish(id, initialize_value()?)?; @@ -264,10 +265,18 @@ fn capabilities() -> ServerCapabilities { // never sends them and the capability costs it nothing. See // `docs/features/file-operations/README.md`. workspace: Some(WorkspaceServerCapabilities { - // Roots are still read once at `initialize`; adding a folder - // mid-session needs `didChangeWorkspaceFolders`, which is its own - // item in TODO.md §9c. - workspace_folders: None, + // Workspace folders, added and removed mid-session. Both halves + // are needed and neither implies the other: `supported` says the + // server understands a multi-folder workspace at all, and + // `changeNotifications` is what makes the client *send* + // `didChangeWorkspaceFolders`. `Left(true)` rather than an id — + // the string form exists so the registration can later be undone + // by name, and this server never unregisters it. See + // `docs/features/folders-and-config/README.md`. + workspace_folders: Some(WorkspaceFoldersServerCapabilities { + supported: Some(true), + change_notifications: Some(OneOf::Left(true)), + }), file_operations: Some(file_ops::file_operations()), }), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( @@ -419,6 +428,21 @@ fn show_document_support(params: &InitializeParams) -> bool { .is_some_and(|show_document| show_document.support) } +/// Whether the client answers `workspace/configuration`. +/// +/// The pull half of the settings model: a client that says so is asked for +/// the `lucisv` section at startup and again whenever it sends an empty +/// `didChangeConfiguration`. A client that said nothing is only ever pushed +/// settings, exactly as before. +fn configuration_support(params: &InitializeParams) -> bool { + params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.configuration) + .unwrap_or(false) +} + /// The directories to index: the client's workspace folders, or the /// deprecated single root when that is all it sent. fn workspace_roots(params: &InitializeParams) -> Vec { @@ -493,6 +517,55 @@ mod tests { } } + #[test] + fn workspace_folders_are_supported_and_their_changes_are_asked_for() { + // Two separate statements, and a client reads them separately: + // without `supported` it may not treat this as a multi-folder server + // at all, and without `changeNotifications` it never sends + // `didChangeWorkspaceFolders` however well that is handled. + let folders = capabilities() + .workspace + .expect("the workspace section") + .workspace_folders + .expect("workspace folders"); + assert_eq!(folders.supported, Some(true)); + assert_eq!(folders.change_notifications, Some(OneOf::Left(true))); + } + + #[test] + fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() { + // Nested one level wrong, or serialized as the string form of + // `changeNotifications`, and the notification simply never arrives. + let value = initialize_value().expect("the initialize result serializes"); + assert_eq!( + value["capabilities"]["workspace"]["workspaceFolders"], + serde_json::json!({ "supported": true, "changeNotifications": true }), + "{value:#?}" + ); + // And the neighbour under the same key is untouched. + assert!(value["capabilities"]["workspace"]["fileOperations"].is_object(), "{value:#?}"); + } + + #[test] + fn configuration_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities}; + assert!(!configuration_support(&InitializeParams::default()), "silence means push-only"); + + let saying = |configuration: Option| InitializeParams { + capabilities: ClientCapabilities { + workspace: Some(WorkspaceClientCapabilities { + configuration, + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(configuration_support(&saying(Some(true)))); + assert!(!configuration_support(&saying(Some(false)))); + assert!(!configuration_support(&saying(None))); + } + #[test] fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() { // `ServerCapabilities` has no `type_hierarchy_provider` field in diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index bc623b7..e6ed0f6 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -15,8 +15,9 @@ use std::error::Error; use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response}; use lsp_types::notification::{ Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, - DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, DidRenameFiles, DidSaveTextDocument, - LogMessage, Notification as _, Progress, PublishDiagnostics, ShowMessage, + DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, + DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress, + PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, @@ -29,33 +30,34 @@ use lsp_types::request::{ SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillRenameFiles, - WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration, WorkspaceDiagnosticRequest, + WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind, - CodeActionParams, CodeLensParams, CompletionParams, DeleteFilesParams, - DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams, - DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, - DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportResult, - DocumentFormattingParams, DocumentHighlightParams, DocumentLinkParams, - DocumentOnTypeFormattingParams, DocumentRangeFormattingParams, DocumentSymbolParams, - DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, - GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, - InlineCompletionParams, LinkedEditingRangeParams, Location, LogMessageParams, MessageType, - NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, - PublishDiagnosticsParams, ReferenceParams, RegistrationParams, - RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, - RenameFilesParams, RenameParams, SelectionRangeParams, SemanticToken, SemanticTokens, - SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, - SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, - SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams, - TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, - TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, - WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, + CodeActionParams, CodeLensParams, CompletionParams, ConfigurationItem, ConfigurationParams, + DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, + DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams, + DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams, + DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams, + DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams, + DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, + ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams, + GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams, + LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position, + PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams, + ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport, + RelatedUnchangedDocumentDiagnosticReport, RenameFilesParams, RenameParams, + SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta, + SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, + SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams, + ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, TypeHierarchyPrepareParams, + TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, + UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, - WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, + WorkspaceEdit, WorkspaceFolder, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; @@ -98,6 +100,10 @@ pub struct ClientAbilities { /// navigate; a client without it still gets the sites back as the /// command's result. pub show_document: bool, + /// Whether the client answers `workspace/configuration` — the pull model + /// for settings. A client that said nothing is only ever *pushed* + /// settings, which is what every client got before this was read. + pub configuration: bool, } /// Everything the server owns. @@ -119,11 +125,11 @@ pub struct Server { /// Numbers the requests made *of* the client. A repeated id is a protocol /// error, so this only ever counts up. request_ids: u32, - /// The `workspace/applyEdit` requests still waiting for an answer, by the - /// id they were sent with, each remembering the command that asked for it - /// so a refusal can be named. Nothing else the server asks of the client - /// is recorded here, which is exactly what makes its answer ignorable. - applying: HashMap, + /// The requests the server has made of the client whose answers it will + /// act on, by the id they were sent with. Everything *not* in here is a + /// request whose answer is ignorable, which is what makes `response`'s + /// fall-through correct rather than lossy. + pending: HashMap, /// Counts everything that can change what a pull request would answer: a /// buffer's text, and the workspace index. It is the whole of a /// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`. @@ -148,6 +154,19 @@ pub struct Server { /// same work and a user reading the status bar wants to know that. const INDEXING_TITLE: &str = "Indexing Verilog workspace"; +/// A request the server sent the client and still owes itself an answer to. +/// +/// One map rather than one per kind: `response` then has a single lookup and +/// a single `match`, and adding a third kind is a variant the compiler makes +/// you handle rather than a map somebody forgets to consult. +enum Pending { + /// A `workspace/applyEdit`, remembering the command that asked for it so + /// a refusal can be named to the user. + ApplyEdit(String), + /// A `workspace/configuration` asking for the `lucisv` section. + Configuration, +} + /// One semantic-token answer, kept so the next delta request can be answered /// against it. struct TokenAnswer { @@ -169,7 +188,7 @@ impl Server { watchers: None, registrations: 0, request_ids: 0, - applying: HashMap::new(), + pending: HashMap::new(), generation: 0, tokens: HashMap::new(), token_results: 0, @@ -186,6 +205,15 @@ impl Server { server.end_indexing(bar); server.report_scope(warnings); server.register_watchers(); + // The pull half of the settings model. Asked here because this is the + // same moment the watchers are registered — the earliest legal one — + // and answered later, in the loop: the settings therefore arrive + // *after* the first index build, exactly as a pushed + // `didChangeConfiguration` always has (it cannot arrive before + // `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist` + // costs one extra rescan when it lands; nothing is stale in between, + // it is simply the default scope until the client answers. + server.request_configuration(); server } @@ -787,7 +815,7 @@ impl Server { } let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit }; let id = self.send_request(ApplyWorkspaceEdit::METHOD, params); - self.applying.insert(id, command.to_string()); + self.pending.insert(id, Pending::ApplyEdit(command.to_string())); Ok(Value::Null) } @@ -1027,19 +1055,43 @@ impl Server { // The `lucisv.*` settings, pushed at startup and on every change. // Nothing here trusts the payload — `settings::from_payload` // drops whatever it cannot use. + // + // An **empty** payload is not a settings payload at all: it is the + // 3.17 client saying "something changed, ask me for what you + // need", so a client that can be asked is asked and nothing is + // applied until it answers. A client that cannot be asked keeps + // the behaviour it has always had — an empty payload is no + // opinion about anything, which resolves to the defaults. DidChangeConfiguration::METHOD => { if let Ok(p) = extract::(notification) { - let pushed = settings::from_payload(&p.settings); + if settings::says_nothing(&p.settings) && self.abilities.configuration { + self.request_configuration(); + return; + } + self.apply_settings(settings::from_payload(&p.settings)); + } + } + // The user added or removed a workspace folder mid-session. One + // rescan per *notification* — an event carries both lists, and + // the progress bar, the code-lens refresh and the diagnostics + // generation all ride along inside `reindex()`. An event that + // changes nothing (a folder already held, one never held, an + // empty event) rescans nothing. + DidChangeWorkspaceFolders::METHOD => { + if let Ok(p) = extract::(notification) { let watched = self.workspace.filelist_path(); - // Only `exclude` and `filelist` change which files exist - // as far as this server is concerned; the other two are - // read afresh by the next formatting request and need no - // invalidation. - if self.workspace.set_client_settings(pushed) { + let added = folder_paths(&p.event.added); + let removed = folder_paths(&p.event.removed); + if self.workspace.change_roots(added, &removed) { self.reindex(); } - // The watched filelist path is baked into the - // registration, so a new one needs a new registration. + // A relative `lucisv.filelist` is anchored at the *first* + // root, so a folder change can move the watched path + // without anyone touching the setting. Same rule, same + // reason as a changed setting: the path is baked into the + // registration. The source glob itself is workspace-wide + // and needs no re-registration — see + // `docs/features/folders-and-config/README.md`. if self.workspace.filelist_path() != watched { self.register_watchers(); } @@ -1068,17 +1120,27 @@ impl Server { /// What the client answered. /// - /// Only a `workspace/applyEdit` answer is read. Nothing else this server - /// asks of the client has an answer worth acting on: one that refuses the + /// Two answers are read: a `workspace/applyEdit`'s and a + /// `workspace/configuration`'s. Nothing else this server asks of the + /// client has an answer worth acting on: one that refuses the /// file-watcher (un)registration simply keeps the save-only staleness /// model; one that errors a `window/workDoneProgress/create` renders no /// bar and ignores the `$/progress` that named that token, per spec; one /// that declines a `workspace/codeLens/refresh` keeps the counts it has, /// and the next save asks again; and one that could not open a /// `window/showDocument` has already told the user so itself. None of - /// those ids is ever in `applying`, so they all fall out here. + /// those ids is ever in `pending`, so they all fall out here — in any + /// arrival order, since the id is the whole of the lookup. fn response(&mut self, response: Response) { - let Some(command) = self.applying.remove(&response.id) else { return }; + match self.pending.remove(&response.id) { + Some(Pending::ApplyEdit(command)) => self.applied(command, response), + Some(Pending::Configuration) => self.configured(response), + None => {} + } + } + + /// Say so when the client did not apply an edit the server pushed. + fn applied(&mut self, command: String, response: Response) { // A refusal is worth saying out loud: the user ran a command, watched // nothing happen, and would otherwise have no idea why. An answer that // does not parse is a refusal too — nothing was seen to be applied. @@ -1099,10 +1161,68 @@ impl Server { self.show_message(MessageType::ERROR, message); } + /// Adopt the settings the client answered a `workspace/configuration` + /// with. + /// + /// **Never an error path.** The answer is an array with one entry per + /// requested item, and this asked for exactly one — so entry 0 is the + /// `lucisv` section. Anything else the client can send (an error, a + /// `null` entry, an empty array, an object where an array belongs, a + /// string) means the same thing: the client has no settings for us, which + /// is the defaults. Nothing here is worth a popup — the user did not ask + /// for this request and cannot act on its failure. + fn configured(&mut self, response: Response) { + let answered = response.response_result.unwrap_or(Value::Null); + let section = answered.get(0).cloned().unwrap_or(Value::Null); + self.apply_settings(settings::from_section(§ion)); + } + + /// Adopt `lucisv.*` settings, from wherever they came, and pay whatever + /// they cost. + /// + /// One applier for the push and the pull, so the two can never disagree + /// about what a setting *does* any more than `settings::from_payload` and + /// `from_section` can disagree about what it says. + fn apply_settings(&mut self, settings: settings::ClientSettings) { + let watched = self.workspace.filelist_path(); + // Only `exclude` and `filelist` change which files exist as far as + // this server is concerned; the other settings are read afresh by the + // next request that wants them and need no invalidation. + if self.workspace.set_client_settings(settings) { + self.reindex(); + } + // The watched filelist path is baked into the registration, so a new + // one needs a new registration. + if self.workspace.filelist_path() != watched { + self.register_watchers(); + } + } + // ------------------------------------------------------------------ // outgoing // ------------------------------------------------------------------ + /// Ask the client for the `lucisv` section of its settings. + /// + /// Silent for a client that did not advertise `workspace.configuration` — + /// that one is only ever pushed settings, which is what every client got + /// before this existed. No `scopeUri`: this server holds one set of + /// settings for the whole session, not one per folder, so asking + /// per-resource would be asking for answers it has nowhere to put. + fn request_configuration(&mut self) { + if !self.abilities.configuration { + return; + } + let params = ConfigurationParams { + items: vec![ConfigurationItem { + scope_uri: None, + section: Some(settings::SECTION.to_string()), + }], + }; + let id = self.send_request(WorkspaceConfiguration::METHOD, params); + self.pending.insert(id, Pending::Configuration); + } + /// Ask the client to watch the source files and the filelist for us, /// replacing any registration already in force. /// @@ -1435,6 +1555,15 @@ fn to_value(value: impl serde::Serialize) -> Result { serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string())) } +/// The paths behind a `didChangeWorkspaceFolders` list. +/// +/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once +/// decoded — is dropped rather than guessed at, the same rule `uri.rs` holds +/// everywhere else: there is nothing on disk to walk for it. +fn folder_paths(folders: &[WorkspaceFolder]) -> Vec { + folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect() +} + /// A notification's params, or `Err` when they do not parse — a malformed /// notification is dropped, because there is no id to answer it on. fn extract( @@ -4591,4 +4720,721 @@ mod tests { ); assert_eq!(session.publishes(), 0, "neither is a path the index reads"); } + + // ------------------------------------------------------------------ + // workspace folders (2026-08-27) + // ------------------------------------------------------------------ + + /// A `workspace/didChangeWorkspaceFolders` event, as a client sends it. + fn folder_event(added: &[&Path], removed: &[&Path]) -> Value { + let folders = |paths: &[&Path]| -> Vec { + paths + .iter() + .map(|path| { + serde_json::json!({ + "uri": path_to_uri(path).expect("uri"), + "name": path.file_name().and_then(|n| n.to_str()).unwrap_or("folder"), + }) + }) + .collect() + }; + serde_json::json!({ "event": { "added": folders(added), "removed": folders(removed) } }) + } + + fn folders_changed(session: &mut Session, added: &[&Path], removed: &[&Path]) { + session.notify(DidChangeWorkspaceFolders::METHOD, folder_event(added, removed)); + } + + #[test] + fn a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish() { + // `didOpen`'s root-conditional reads the *current* root set: with no + // roots at all it reindexes to widen the scope; with one, it only + // publishes. Before this round a session's root set never changed + // after `initialize`, so a session could never move between the two + // branches — this pins that it now genuinely does, live. + // QA (2026-08-27): "own shapes" case from the review checklist. + let outside = Tree::new("rootlessgainsoutside"); + outside.package("a.sv", "a"); + let folder = Tree::new("rootlessgainsfolder"); + folder.package("b.sv", "b"); + + let mut session = Session::new(Vec::new(), false); + assert!(!session.server.workspace.has_roots(), "premise: rootless"); + + // `generation` counts a buffer's text *and* the index, so one open is + // `set_document`'s bump plus `reindex`'s own — two, while rootless. + let before = session.server.generation; + let _ = session + .open(&outside.path.join("a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); + assert_eq!(session.server.generation, before + 2, "rootless didOpen widens by reindexing"); + + folders_changed(&mut session, &[&folder.path], &[]); + assert!(session.server.workspace.has_roots(), "the workspace now has a root"); + let after_folder = session.server.generation; + + // With a root, the same event costs only `set_document`'s bump: no + // second reindex, because opening an already-indexed file changes + // nothing about the scope. + let uri = session + .open(&folder.path.join("b.sv"), "package b;\n localparam K = 1;\nendpackage\n"); + assert_eq!( + session.server.generation, + after_folder + 1, + "with a root, opening an already-indexed file must not cost a rescan" + ); + let published = session.published(); + assert!( + published.iter().any(|p| p.uri == uri), + "it is still published, just not rescanned" + ); + } + + #[test] + fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() { + // The whole point: "Add Folder to Workspace" used to change nothing + // until the editor was restarted. + let first = Tree::new("folderadd"); + first.package("rtl/a.sv", "a"); + let second = Tree::new("folderaddsecond"); + second.package("rtl/b.sv", "b"); + + let mut session = Session::new(vec![first.path.clone()], false); + assert_eq!(indexed(&session, "b"), 0, "premise: the second folder is not open yet"); + + folders_changed(&mut session, &[&second.path], &[]); + assert_eq!(indexed(&session, "b"), 1, "the added folder is scanned"); + assert_eq!(indexed(&session, "a"), 1, "and the one already open survives"); + + // And it is reachable through a real request, not only in the index. + let hits = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query":"b"})); + let found = hits.as_array().expect("a symbol list"); + assert!( + found.iter().any(|hit| hit["location"]["uri"] + .as_str() + .is_some_and(|uri| uri.contains("folderaddsecond"))), + "{found:#?}" + ); + } + + #[test] + fn a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed() { + // The client owns buffer lifecycle: closing a folder does not close + // the editors that were open in it. Such a buffer keeps the deal + // every rootless buffer has always had — it is still analyzed, still + // published, and still overrides disk in the index. + let first = Tree::new("folderremove"); + first.package("rtl/a.sv", "a"); + let second = Tree::new("folderremovesecond"); + second.package("rtl/open.sv", "open_pkg"); + second.package("rtl/other.sv", "other_pkg"); + + let mut session = Session::new(vec![first.path.clone(), second.path.clone()], false); + let uri = session.open( + &second.path.join("rtl/open.sv"), + "package open_pkg;\n localparam K = 1;\nendpackage\n", + ); + assert_eq!(indexed(&session, "other_pkg"), 1, "premise: the whole folder is indexed"); + + folders_changed(&mut session, &[], &[&second.path]); + assert_eq!(indexed(&session, "other_pkg"), 0, "the folder's files left the index"); + assert_eq!(indexed(&session, "a"), 1, "the folder that stayed is untouched"); + assert_eq!( + indexed(&session, "open_pkg"), + 1, + "the open buffer contributes itself, as every out-of-scope buffer does" + ); + + // The rebuild republished it, and an edit to it is still diagnosed. + let published = session.published(); + assert!(published.iter().any(|p| p.uri == uri), "{published:#?}"); + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }], + }), + ); + let published = session.published(); + assert_eq!(published.len(), 1, "{published:#?}"); + assert_eq!(published[0].uri, uri); + assert!(!published[0].diagnostics.is_empty(), "a broken buffer still reports"); + + // And closing it clears cleanly — the removed folder is not a special + // case for `didClose`, which already sends an empty publish for + // whatever buffer is named regardless of where it lived. + // QA (2026-08-27): pinned per the dev's own review checklist item. + session.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + let published = session.published(); + assert_eq!(published.len(), 1, "{published:#?}"); + assert_eq!(published[0].uri, uri); + assert!(published[0].diagnostics.is_empty(), "the close cleared it"); + } + + #[test] + fn one_folder_notification_is_one_rescan_with_one_bar_and_one_generation() { + // Everything a rescan owes rides inside `reindex()`; an event carries + // both lists, so it must cost exactly one of each. + let first = Tree::new("folderonce"); + first.package("rtl/a.sv", "a"); + let second = Tree::new("folderoncesecond"); + second.package("rtl/b.sv", "b"); + let third = Tree::new("folderoncethird"); + third.package("rtl/c.sv", "c"); + + let abilities = ClientAbilities { + work_done_progress: true, + code_lens_refresh: true, + ..Default::default() + }; + let mut session = Session::with(vec![first.path.clone(), second.path.clone()], abilities); + session.open(&first.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); + let before = session.server.generation; + let _ = session.drain(); + + // One notification that both adds and removes: two changes, one scan. + folders_changed(&mut session, &[&third.path], &[&second.path]); + assert_eq!(indexed(&session, "c"), 1, "the addition took"); + assert_eq!(indexed(&session, "b"), 0, "and so did the removal"); + assert_eq!(session.server.generation, before + 1, "one generation bump"); + + let messages = session.drain(); + let steps: Vec<&'static str> = + messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect(); + assert_eq!(steps, vec!["create", "begin", "end"], "one bar, up and down"); + let publishes = messages + .iter() + .filter( + |m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD), + ) + .count(); + assert_eq!(publishes, 1, "the one open buffer is republished once"); + let refreshes = messages + .iter() + .filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD)) + .count(); + assert_eq!(refreshes, 1, "the counts on screen were invalidated once"); + } + + #[test] + fn a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added() { + // Three separate notifications, each of which genuinely moves the + // root set (unlike the no-op shapes above), must cost three separate + // rescans — `change_roots` has no batching across notifications, only + // within one — and the state after must be consistent with the net + // effect: two adds and one remove is "present". + // QA (2026-08-27): "own shapes" case from the review checklist. + let root = Tree::new("rapidflaproot"); + root.package("rtl/a.sv", "a"); + let flapping = Tree::new("rapidflapfolder"); + flapping.package("rtl/b.sv", "b"); + + let mut session = Session::new(vec![root.path.clone()], false); + let before = session.server.generation; + + folders_changed(&mut session, &[&flapping.path], &[]); + assert_eq!(indexed(&session, "b"), 1, "added"); + folders_changed(&mut session, &[], &[&flapping.path]); + assert_eq!(indexed(&session, "b"), 0, "removed"); + folders_changed(&mut session, &[&flapping.path], &[]); + assert_eq!(indexed(&session, "b"), 1, "added again"); + + assert_eq!( + session.server.generation, + before + 3, + "one rescan per notification, three total" + ); + assert_eq!( + indexed(&session, "a"), + 1, + "the folder that never moved is untouched throughout" + ); + } + + #[test] + fn a_folder_event_that_moves_nothing_costs_nothing() { + // Total and no-op-safe: every shape a client can send that leaves the + // root set where it was must cost no rescan at all. + let tree = Tree::new("foldernoop"); + tree.package("rtl/a.sv", "a"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); + let before = session.server.generation; + let _ = session.drain(); + + folders_changed(&mut session, &[], &[]); + folders_changed(&mut session, &[&tree.path], &[]); + folders_changed(&mut session, &[], &[&tree.path.join("never-added")]); + folders_changed(&mut session, &[&tree.path], &[&tree.path]); + // Params that do not parse at all, and a folder that is not a path. + session.notify(DidChangeWorkspaceFolders::METHOD, serde_json::json!({ "nonsense": 1 })); + session.notify( + DidChangeWorkspaceFolders::METHOD, + serde_json::json!({ "event": { + "added": [{ "uri": "untitled:Untitled-1", "name": "scratch" }], "removed": [], + } }), + ); + + assert!(session.progress().is_empty(), "no rescan for any of them"); + assert_eq!(session.publishes(), 0, "and nothing was republished"); + assert_eq!(session.server.generation, before, "and no generation moved"); + assert_eq!(indexed(&session, "a"), 1, "the root itself survived every one"); + } + + #[test] + fn a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves() { + // The source glob is workspace-wide — the client matches it against + // whatever folders it holds, so a folder change needs no new + // registration for it. The *filelist* watcher is an absolute path + // anchored at the first root, so a folder change can move it without + // anyone touching the setting. + let first = Tree::new("folderwatch"); + first.package("rtl/a.sv", "a"); + first.write("files.f", "rtl/a.sv\n"); + let second = Tree::new("folderwatchsecond"); + second.package("rtl/b.sv", "b"); + second.write("files.f", "rtl/b.sv\n"); + + let mut session = Session::new(vec![first.path.clone()], true); + let _ = session.drain(); + + // No filelist setting: nothing about the registration depends on the + // roots, so adding a folder re-registers nothing. + folders_changed(&mut session, &[&second.path], &[]); + assert!(session.requests().is_empty(), "the source glob is workspace-wide"); + + // With a *relative* filelist the watched path is `/files.f`... + session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f")); + let _ = session.drain(); + // ...so dropping that root moves it to the second folder's copy. + folders_changed(&mut session, &[], &[&first.path]); + let requests = session.requests(); + assert_eq!(requests.len(), 2, "{requests:#?}"); + assert_eq!(requests[0].0, UnregisterCapability::METHOD); + assert_eq!(requests[1].0, RegisterCapability::METHOD); + assert_eq!( + requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"], + second.path.join("files.f").to_str().expect("utf-8").to_string(), + "{requests:#?}" + ); + } + + // ------------------------------------------------------------------ + // pulled settings (2026-08-27) + // ------------------------------------------------------------------ + + /// A client that answers `workspace/configuration`. + fn pulling_settings() -> ClientAbilities { + ClientAbilities { configuration: true, ..Default::default() } + } + + /// The id of the one outstanding `workspace/configuration`, and the params + /// it went out with. + fn configuration_request(session: &Session) -> (RequestId, Value) { + let sent = session.sent(); + let asked: Vec<&Request> = + sent.iter().filter(|r| r.method == WorkspaceConfiguration::METHOD).collect(); + assert_eq!(asked.len(), 1, "exactly one pull is outstanding: {sent:#?}"); + (asked[0].id.clone(), asked[0].params.clone()) + } + + #[test] + fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() { + let tree = Tree::new("pullstartup"); + tree.package("rtl/a.sv", "a"); + let session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (_id, params) = configuration_request(&session); + assert_eq!( + params, + serde_json::json!({ "items": [{ "section": "lucisv" }] }), + "one item, our section, no scope" + ); + } + + #[test] + fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() { + // `Server::new` calls `register_watchers` and then + // `request_configuration`, in that order — this pins it on the actual + // wire rather than trusting the call order in the source. Every + // outgoing request's id is `lucisv-{n}` off one monotonically + // increasing counter, so the numeric suffix *is* the send order. + // QA (2026-08-27): pinned per the dev's own review checklist item + // ("verify on the wire"). + let tree = Tree::new("pulloraftwatch"); + let abilities = + ClientAbilities { file_watching: true, configuration: true, ..pulling_settings() }; + let session = Session::with(vec![tree.path.clone()], abilities); + let sent = session.sent(); + let index_of = |method: &str| -> usize { + sent.iter() + .position(|r| r.method == method) + .unwrap_or_else(|| panic!("no {method} in {sent:#?}")) + }; + let watchers = index_of(RegisterCapability::METHOD); + let pull = index_of(WorkspaceConfiguration::METHOD); + assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}"); + + let numeric_suffix = |request: &Request| -> u32 { + request + .id + .to_string() + .trim_matches('"') + .trim_start_matches("lucisv-") + .parse() + .unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id)) + }; + assert!( + numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]), + "the pull's id must be issued after the watcher registration's: {sent:#?}" + ); + } + + #[test] + fn a_client_that_cannot_be_asked_is_never_asked() { + // Every client that predates this — `smoke.js` included — sends + // `capabilities: {}` and must see nothing new at all. + let tree = Tree::new("pullnone"); + let session = Session::new(vec![tree.path.clone()], false); + assert!(session.requests().is_empty(), "{:#?}", session.requests()); + } + + #[test] + fn a_pulled_answer_reaches_the_formatter_through_the_same_parser_a_push_uses() { + let tree = Tree::new("pullapply"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + let (id, _) = configuration_request(&session); + + // The editor's tab size, until the client answers. + assert_eq!( + formatting_result(&mut session, &uri)[0]["newText"], + serde_json::json!("module m;\n wire a;\nendmodule\n") + ); + + // The answer is an array with one entry per requested item, and the + // entry is the *section*, not the `{lucisv: ...}` wrapper a push has. + session.answer(id, serde_json::json!([{ "indent": 4, "lineLength": 120 }])); + assert_eq!( + formatting_result(&mut session, &uri)[0]["newText"], + serde_json::json!("module m;\n wire a;\nendmodule\n"), + "the pulled indent is in force" + ); + assert_eq!(session.server.workspace.client_settings().line_length, Some(120)); + } + + #[test] + fn a_pulled_answer_that_changes_the_scope_rebuilds_the_index() { + // The pull applies through the same path a push does, so an `exclude` + // that arrives this way must cost the same rescan. + let tree = Tree::new("pullexclude"); + tree.package("rtl/a.sv", "a"); + tree.package("scratch/wip.sv", "scratch_pkg"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + assert_eq!(indexed(&session, "scratch_pkg"), 1, "premise: indexed at first"); + + let (id, _) = configuration_request(&session); + session.answer(id, serde_json::json!([{ "exclude": ["scratch"] }])); + assert_eq!(indexed(&session, "scratch_pkg"), 0, "the pulled exclude took effect"); + assert_eq!(indexed(&session, "a"), 1, "and nothing else moved"); + } + + #[test] + fn a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses() { + // `apply_settings` is the one function both doors go through, but + // nothing pinned it for the *pull* path specifically before this: the + // answer changing `lucisv.filelist` must move `filelist_path()` and + // cost a watcher re-registration exactly as a pushed one does. + // QA (2026-08-27): pinned per the dev's own review checklist item + // ("the full chain: pull answer -> apply_settings -> filelist moved + // -> re-register"). + let tree = Tree::new("pullfilelistwatch"); + tree.package("rtl/a.sv", "a"); + tree.write("files.f", "rtl/a.sv\n"); + let abilities = + ClientAbilities { configuration: true, file_watching: true, ..Default::default() }; + let mut session = Session::with(vec![tree.path.clone()], abilities); + // Drains the startup watcher registration and the startup pull's own + // request together; `configuration_request` needs only the latter. + let (id, _) = configuration_request(&session); + + session.answer(id, serde_json::json!([{ "filelist": "files.f" }])); + let requests = session.requests(); + assert_eq!(requests.len(), 2, "{requests:#?}"); + assert_eq!(requests[0].0, UnregisterCapability::METHOD, "the old registration first"); + assert_eq!(requests[1].0, RegisterCapability::METHOD); + assert_eq!( + requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"], + tree.path.join("files.f").to_str().expect("utf-8").to_string(), + "{requests:#?}" + ); + } + + #[test] + fn an_unusable_pull_answer_leaves_the_defaults_and_says_nothing() { + // Nothing here is the user's fault and nothing here is actionable, so + // every one of these must be as quiet as a client that answered + // `null` — which is what the spec asks a client without the section + // to do. + let tree = Tree::new("pulljunk"); + for answer in [ + serde_json::json!(null), + serde_json::json!([]), + serde_json::json!([null]), + serde_json::json!("lucisv"), + serde_json::json!({ "indent": 4 }), + serde_json::json!([{ "indent": "four", "exclude": 7 }]), + serde_json::json!([{ "lucisv": { "indent": 4 } }]), + ] { + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + session.answer(id, answer.clone()); + assert_eq!( + session.server.workspace.client_settings(), + &settings::ClientSettings::default(), + "the answer {answer} must leave the defaults" + ); + assert!(session.shown().is_empty(), "and must not open a popup"); + } + + // An error response is the same news, said differently. + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + session.server.response(Response::new_err( + id, + lsp_server::ErrorCode::MethodNotFound as i32, + "no configuration here".to_string(), + )); + assert_eq!( + session.server.workspace.client_settings(), + &settings::ClientSettings::default() + ); + assert!(session.shown().is_empty(), "a refused pull is not worth a popup"); + } + + #[test] + fn an_empty_push_pulls_instead_of_resetting_everything_to_default() { + // The modern client's "something changed, ask me for what you need". + // Applying it as a payload would silently clear the settings it just + // told us to come and fetch. + let tree = Tree::new("pushempty"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + session.answer(id, serde_json::json!([{ "indent": 4 }])); + assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise"); + + for empty in + [serde_json::json!({ "settings": {} }), serde_json::json!({ "settings": null })] + { + let _ = session.drain(); + session.notify(DidChangeConfiguration::METHOD, empty.clone()); + assert_eq!( + session.server.workspace.client_settings().indent, + Some(4), + "{empty} must not clear what was pulled" + ); + let (id, _) = configuration_request(&session); + session.answer(id, serde_json::json!([{ "indent": 8 }])); + assert_eq!(session.server.workspace.client_settings().indent, Some(8), "{empty}"); + // Put it back for the next round. + session.server.workspace.set_client_settings(settings::ClientSettings { + indent: Some(4), + ..Default::default() + }); + } + } + + #[test] + fn an_empty_push_to_a_client_that_cannot_be_asked_still_means_no_opinion() { + // The legacy path, unchanged: with nobody to ask, an empty payload is + // what it has always been — no opinion about anything. + let tree = Tree::new("pushemptylegacy"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "indent": 4 } } }), + ); + assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise"); + + session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null })); + assert_eq!(session.server.workspace.client_settings().indent, None, "cleared, as before"); + assert!(session.requests().is_empty(), "and nothing was asked of it"); + } + + #[test] + fn a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked() { + // The legacy `synchronize.configurationSection` path survives the + // pull model: a client that sends both must not have its own push + // ignored in favour of a round trip. + let tree = Tree::new("pushpayload"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + session.answer(id, serde_json::json!([null])); + + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }), + ); + assert_eq!(session.server.workspace.client_settings().indent, Some(8)); + let sent = session.sent(); + assert!( + !sent.iter().any(|r| r.method == WorkspaceConfiguration::METHOD), + "a payload is not a request to go and fetch one: {sent:#?}" + ); + } + + #[test] + fn a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding() { + // The other half of the precedence question: a client that both + // pushes (the legacy `synchronize.configurationSection`) and can be + // pulled may have its own push arrive *before* the startup pull's + // answer does — both mechanisms firing off the same connection at + // once. The loop is single-threaded and processes messages strictly + // in receive order, with no notion of "the push is newer" beyond + // that: `apply_settings` always replaces the whole struct, so + // whichever of the two is processed *last* is simply what is in + // force afterward. QA (2026-08-27): pinned per the dev's own review + // checklist item ("push-with-payload arriving while a pull is + // outstanding — which wins"). + let tree = Tree::new("latepullwins"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + + // The push lands first, while the startup pull is still outstanding. + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }), + ); + assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the push landed"); + + // The pull's answer arrives after — and, being processed last, + // overwrites it. + session.answer(id, serde_json::json!([{ "indent": 4 }])); + assert_eq!( + session.server.workspace.client_settings().indent, + Some(4), + "processed last, so in force last — the pull's answer, not the push" + ); + } + + #[test] + fn three_outstanding_requests_are_answered_by_id_in_any_order() { + // `applyEdit`, a progress `create` and a `workspace/configuration` + // all in flight at once. Only two of them are in `pending`, and the + // arrival order is not the send order — the id is the whole lookup, + // and neither answer may be delivered to the other's handler. + let abilities = ClientAbilities { + apply_edit: true, + work_done_progress: true, + configuration: true, + ..Default::default() + }; + let (tree, mut session, params) = propagating("threeway", abilities); + let _ = session.drain(); + // `propagating` answered nothing, so the startup pull is already + // spent; an empty push asks again, and that one is left outstanding + // alongside the other two. + session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null })); + + let result = session.result(ExecuteCommand::METHOD, params); + assert!(result.is_null(), "the edit was pushed, not returned"); + session.watched(&[tree.path.join("sub.sv")]); + + let sent = session.sent(); + let of = |method: &str| -> RequestId { + sent.iter() + .find(|request| request.method == method) + .unwrap_or_else(|| panic!("no {method} in {sent:#?}")) + .id + .clone() + }; + let (edit, create, pull) = ( + of(ApplyWorkspaceEdit::METHOD), + of(WorkDoneProgressCreate::METHOD), + of(WorkspaceConfiguration::METHOD), + ); + + // Backwards: the pull first, then the ignorable create, then the edit. + session.answer(pull, serde_json::json!([{ "indent": 4 }])); + assert_eq!(session.server.workspace.client_settings().indent, Some(4), "the pull landed"); + assert!(session.shown().is_empty(), "and said nothing to the user"); + + session.answer(create, serde_json::json!(null)); + assert!(session.shown().is_empty(), "a create answer says nothing either"); + + session.answer(edit, serde_json::json!({ "applied": false })); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "{shown:#?}"); + assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}"); + } + + #[test] + fn two_outstanding_configuration_pulls_are_each_answered_by_their_own_id() { + // A second pull can go out before the first is answered — an empty + // `didChangeConfiguration` racing the client's answer to the startup + // pull, say. Both ids sit in `pending` at once; each answer is + // applied through its own id, and whichever is processed last is + // simply what ends up in force — there is no notion of the newer + // pull's answer winning over the older one, only processing order. + // QA (2026-08-27): pinned per the dev's own review checklist item. + let tree = Tree::new("twopulls"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let sent = session.sent(); + let first = sent + .iter() + .find(|r| r.method == WorkspaceConfiguration::METHOD) + .expect("the startup pull") + .id + .clone(); + + session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null })); + let sent = session.sent(); + let second = sent + .iter() + .find(|r| r.method == WorkspaceConfiguration::METHOD) + .expect("the re-pull") + .id + .clone(); + assert_ne!(first, second, "two distinct outstanding requests, not one reused"); + + // Answered out of order: the second (newer) pull first, then the + // first (older, startup) one. + session.answer(second, serde_json::json!([{ "indent": 8 }])); + assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the newer landed"); + session.answer(first, serde_json::json!([{ "indent": 4 }])); + assert_eq!( + session.server.workspace.client_settings().indent, + Some(4), + "whichever answer is processed last is what is in force — no id-based precedence" + ); + } + + #[test] + fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() { + // An id the server never sent, or a duplicate answer to one already + // consumed, names nothing in `pending`: `response` must not panic and + // must leave whatever settings are in force untouched. + // QA (2026-08-27): pinned per the dev's own review checklist item. + let tree = Tree::new("forgottenid"); + let mut session = Session::with(vec![tree.path.clone()], pulling_settings()); + let (id, _) = configuration_request(&session); + session.answer(id.clone(), serde_json::json!([{ "indent": 4 }])); + assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise"); + + // The same id, answered a second time — already removed from `pending`. + session.answer(id, serde_json::json!([{ "indent": 8 }])); + assert_eq!( + session.server.workspace.client_settings().indent, + Some(4), + "a stale re-answer is a no-op" + ); + + // An id that was never sent by this server at all. + session.answer( + RequestId::from("never-sent".to_string()), + serde_json::json!([{ "indent": 2 }]), + ); + assert_eq!(session.server.workspace.client_settings().indent, Some(4)); + } } diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index a1a79b9..f94d4ce 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -1,4 +1,5 @@ -//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`. +//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration` +//! — or answers when the server pulls them with `workspace/configuration`. //! //! These are the editor's copy of what `lucisv.toml` carries — the same keys, so //! a user with no config file in the tree can still say "indent 4" from their @@ -27,6 +28,12 @@ use serde_json::Value; const LINE_LENGTH_RANGE: RangeInclusive = 40..=400; const INDENT_RANGE: RangeInclusive = 1..=8; +/// The configuration section these settings live in — the key a push nests +/// them under, and the `section` a pull asks for. One constant, because the +/// two must name the same thing or the pull would answer settings the parser +/// then looks for somewhere else. +pub const SECTION: &str = "lucisv"; + /// The `lucisv.*` settings in force, after validation. Every field is "no /// opinion" until a client says otherwise, which is exactly what an unset /// VS Code setting means. @@ -70,7 +77,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // `synchronize.configurationSection: 'lucisv'` produces. A payload without // the section (including the `{"settings": null}` a client sends when it // syncs no section at all) means "no opinion about anything". - let Some(lucisv) = settings.get("lucisv") else { return ClientSettings::default() }; + let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() }; ClientSettings { line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE), indent: bounded(lucisv.get("indent"), INDENT_RANGE), @@ -84,6 +91,38 @@ pub fn from_payload(settings: &Value) -> ClientSettings { } } +/// Read one `workspace/configuration` answer — the *contents* of the `lucisv` +/// section, since that is what the server asked for by name. +/// +/// Deliberately the same parser as a push, reached by wrapping the section +/// back into the shape a push arrives in. Two entry points, one set of rules: +/// a range, a type or a default that drifted between the pull and the push +/// paths would be a setting that means one thing in VS Code and another in +/// Neovim. `null` — the answer the spec requires when a client cannot provide +/// the section — parses as "no opinion about anything", which is exactly the +/// defaults. +pub fn from_section(section: &Value) -> ClientSettings { + from_payload(&Value::Object([(SECTION.to_string(), section.clone())].into_iter().collect())) +} + +/// Whether a `didChangeConfiguration` payload carries nothing at all. +/// +/// The 3.17 model: a client that knows the server pulls sends the +/// notification as a bare "something changed, ask me for what you need" — +/// `{"settings": null}` is what `vscode-languageclient` sends once no legacy +/// `synchronize.configurationSection` is configured, and `{}` is the same +/// statement written differently. Both are a *trigger*, not a settings +/// payload, so the server pulls rather than resetting everything to its +/// default. A payload with any key in it is a real push and is applied as it +/// always was, whether or not our section is among those keys. +pub fn says_nothing(settings: &Value) -> bool { + match settings { + Value::Null => true, + Value::Object(map) => map.is_empty(), + _ => false, + } +} + /// A JSON boolean, or nothing. `as_bool` rejects the string `"false"` and the /// number `0` along with everything else that is not a boolean: a wrong-typed /// value is dropped here exactly as it is everywhere else in this module, and @@ -279,6 +318,72 @@ mod tests { assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]); } + #[test] + fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() { + // The whole point of `from_section`: the pull answers the section's + // contents, the push nests them one level deeper, and every rule + // about ranges, types and defaults must be the one set of rules. + let section = json!({ + "lineLength": 120, "indent": 4, "exclude": ["vendor"], + "filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true + }); + assert_eq!(from_section(§ion), settings(json!({ "lucisv": section }))); + // ...including the rejections. + let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" }); + assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk }))); + assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections"); + } + + #[test] + fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() { + // A client that cannot provide the section must answer `null`, per + // spec — and one that answers something absurd instead must cost the + // user no more than one that answered nothing. + for answer in [ + json!(null), + json!({}), + json!("lucisv"), + json!(7), + json!([1, 2]), + json!({ "lucisv": { "indent": 4 } }), + ] { + assert_eq!( + from_section(&answer), + ClientSettings::default(), + "the answer {answer} must resolve to the defaults" + ); + } + } + + #[test] + fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() { + // `{"settings": null}` is what a modern `vscode-languageclient` + // sends: "something changed, ask me". Applying it as a payload would + // silently reset every setting the user had pulled. + assert!(says_nothing(&json!(null))); + assert!(says_nothing(&json!({}))); + assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } }))); + // A legacy push that syncs some *other* server's section is still a + // push: it carries a payload, and this server's answer to it — no + // opinion about anything — is what it has always been. + assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } }))); + // Neither an array nor a scalar is the client saying "ask me"; both + // are junk, and junk goes down the push path where `from_payload` + // drops it. + assert!(!says_nothing(&json!([]))); + assert!(!says_nothing(&json!(""))); + } + + #[test] + fn the_section_constant_is_the_key_the_parser_reads() { + // The pull asks for `SECTION` by name and the push nests under it. A + // constant that drifted from the parser would make every pulled + // setting silently invisible. + let found = from_payload(&json!({ SECTION: { "indent": 4 } })); + assert_eq!(found.indent, Some(4)); + assert_eq!(SECTION, "lucisv"); + } + #[test] fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() { // The bounds above are copied from `lucisv_core::config`, which exports diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 29f2b19..52fbb1d 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -125,6 +125,27 @@ impl Workspace { self.rebuild_index() } + /// Add and remove workspace roots mid-session, reporting whether the set + /// actually moved — which is whether the caller owes a rebuild. + /// + /// Removals are applied before additions, so a folder named in both lists + /// (which the protocol does not forbid, and which is how some clients + /// spell "this folder moved") ends up present. Adding a root that is + /// already held and removing one that was never held are both no-ops, and + /// say so by leaving the set equal: `didChangeWorkspaceFolders` is a + /// notification, so there is nowhere to report a disagreement to and + /// nothing to gain from re-scanning for one. + pub fn change_roots(&mut self, added: Vec, removed: &[PathBuf]) -> bool { + let before = self.roots.clone(); + self.roots.retain(|root| !removed.contains(root)); + for root in added { + if !self.roots.contains(&root) { + self.roots.push(root); + } + } + self.roots != before + } + pub fn index(&self) -> &WorkspaceIndex { &self.index } @@ -374,6 +395,7 @@ impl Workspace { #[cfg(test)] mod tests { use super::*; + use std::slice::from_ref; use std::str::FromStr; fn uri(s: &str) -> Uri { @@ -474,6 +496,200 @@ mod tests { } } + #[test] + fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() { + let first = Tree::new("rootsfirst"); + first.package("a.sv", "a"); + let second = Tree::new("rootssecond"); + second.package("b.sv", "b"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![first.path.clone()]); + assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder"); + + assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set"); + ws.rebuild_index(); + assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned"); + + assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one"); + ws.rebuild_index(); + assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone"); + } + + #[test] + fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() { + // Overlap does not duplicate a file's registration: `walked_files` + // walks each root independently and `dedup`s the combined, sorted + // list by path, so a file both roots would reach lands in the index + // once, not twice (a second identical registration would show up as + // an *ambiguous* member — `indexed` below only counts a name found + // exactly once). + // + // It is NOT exclude-proof, though, and that half is a genuine + // consequence of "each root is governed by its own config" + // (documented on `walked_files`): a directory the parent root's + // `lucisv.toml` excludes is added *as a root in its own right* here, + // and nothing excludes a root from itself. QA (2026-08-27): flagged + // in the QA log as a finding, not a bug fix — this is consistent + // with the per-root config model, but it was unreachable before this + // round (roots used to be frozen at `initialize`), so it is worth a + // pin and a name. + let tree = Tree::new("subdirroot"); + tree.write("lucisv.toml", "exclude = [\"sub\"]\n"); + tree.package("kept.sv", "kept"); + tree.package("sub/hidden.sv", "hidden_pkg"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured"); + + assert!(ws.change_roots(vec![tree.path.join("sub")], &[])); + ws.rebuild_index(); + assert_eq!( + indexed(&ws, &["kept", "hidden_pkg"]), + ["kept", "hidden_pkg"], + "reachable once through the added root, and only once — not ambiguous" + ); + } + + #[test] + fn a_folder_change_that_changes_nothing_asks_for_no_rescan() { + // Every no-op shape a client can send. Each must leave the root set + // exactly as it was, and say so — a rescan here is pure cost. + let tree = Tree::new("rootsnoop"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + + assert!(!ws.change_roots(Vec::new(), &[]), "an empty event"); + assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held"); + let never = tree.path.join("never-added"); + assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held"); + assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once"); + assert!(ws.has_roots(), "the root survived every one of them"); + } + + #[test] + fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() { + // `uri_to_path` decodes a URI verbatim, trailing slash and all, and + // `change_roots` compares by `PathBuf` equality — which compares + // components, not raw strings, so `/a/b/` and `/a/b` are already the + // same path as far as `retain`/`contains` are concerned. Pinned + // because the doc README calls this out as a boundary worth + // checking, not because the standard library needed help. + let tree = Tree::new("trailingslash"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + + let mut with_slash = tree.path.clone().into_os_string(); + with_slash.push("/"); + assert!( + ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))), + "the trailing slash must not hide the match" + ); + assert!(!ws.has_roots()); + } + + #[test] + fn a_folder_named_in_both_halves_of_one_event_stays() { + // Removals run first, so "removed and added again" — which is how a + // moved folder reaches some clients — is not a way to lose a root. + let tree = Tree::new("rootsboth"); + tree.package("a.sv", "a"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change"); + ws.rebuild_index(); + assert_eq!(indexed(&ws, &["a"]), ["a"]); + } + + #[test] + fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() { + // The root set is a set, not a multiset: `change_roots` dedups on + // push (`if !self.roots.contains(&root)`), so a second add of the + // same path — even from a *later*, separate notification — never + // grows a reference count for it. One removal is therefore always + // enough, however many times a client (redundantly) added it. + // QA (2026-08-27): pinned per the review checklist's multiset-vs-set + // question. + let tree = Tree::new("addedtwice"); + let extra = Tree::new("addedtwiceextra"); + extra.package("x.sv", "x"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set"); + assert!( + !ws.change_roots(vec![extra.path.clone()], &[]), + "a second, separate add of the same path is a no-op" + ); + assert!( + ws.change_roots(Vec::new(), from_ref(&extra.path)), + "one removal is enough to take it out" + ); + ws.rebuild_index(); + assert_eq!(indexed(&ws, &["x"]), Vec::::new(), "gone, not merely decremented"); + } + + #[test] + fn removing_the_last_root_falls_back_to_the_rootless_model() { + // Rung 3 of the ladder is not a startup-only state: a session that + // closes its last folder becomes the single-file case, and an open + // buffer must still resolve against the files beside it. + let tree = Tree::new("rootslast"); + tree.package("rtl/open.sv", "open_pkg"); + tree.package("rtl/sibling.sv", "sibling"); + tree.package("elsewhere/far.sv", "far"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]); + + let path = tree.path.join("rtl/open.sv"); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into()); + assert!(ws.change_roots(Vec::new(), from_ref(&tree.path))); + assert!(!ws.has_roots(), "the workspace is rootless now"); + ws.rebuild_index(); + assert_eq!( + indexed(&ws, &["open_pkg", "sibling", "far"]), + ["open_pkg", "sibling"], + "the buffer and its neighbours, as if the file had been opened on its own" + ); + } + + #[test] + fn removing_the_last_root_leaves_a_relative_filelist_unanchored() { + // `filelist_path` anchors a relative setting at `roots.first()`. With + // no roots left there is nothing to anchor it to, and the path comes + // back exactly as the client wrote it — not resolved against the + // folder that is now gone, and not resolved against anything else + // either. Nothing panics: `source_files` still falls back to the + // rootless walk with a warning when that bare path cannot be read + // (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so` + // covers that fallback). QA (2026-08-27): pinned because this is new + // reachable behaviour this round — losing the last root used to be + // impossible. + let tree = Tree::new("rootslastfilelist"); + tree.package("rtl/open.sv", "open_pkg"); + tree.write("files.f", "rtl/open.sv\n"); + + let mut ws = Workspace::default(); + ws.set_client_settings(using_filelist("files.f")); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!( + ws.filelist_path(), + Some(tree.path.join("files.f")), + "anchored at the root while it exists" + ); + + assert!(ws.change_roots(Vec::new(), from_ref(&tree.path))); + assert_eq!( + ws.filelist_path(), + Some(PathBuf::from("files.f")), + "with no roots left, the same setting comes back bare — anchored at nothing" + ); + } + #[test] fn the_scan_skips_what_a_gitignore_skips() { let tree = Tree::new("gitignore"); diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 1b139b2..76431ed 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3792,3 +3792,168 @@ fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +/// §9c (folders-and-config): a folder added mid-session, over the real wire. +/// +/// What only an e2e test can settle: that the two halves of +/// `workspace.workspaceFolders` reach a real handshake at the key a client +/// reads (without `changeNotifications` no editor ever sends the +/// notification, however well it is handled), and that a cross-file jump into +/// a folder the server did not have at `initialize` resolves afterwards. +#[test] +fn a_folder_added_mid_session_is_indexed_over_the_wire() { + let first = temp_dir("foldersfirst"); + let second = temp_dir("folderssecond"); + // `top.sv` uses a parameter the *second* folder's package declares, so + // the jump can only resolve once that folder is part of the workspace. + let top = first.join("top.sv"); + std::fs::write(&top, "module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n") + .expect("write"); + let added = second.join("added_pkg.sv"); + std::fs::write(&added, "package added_pkg;\n localparam WIDTH = 8;\nendpackage\n") + .expect("write"); + + let first_uri = format!("file://{}", first.display()); + let second_uri = format!("file://{}", second.display()); + let top_uri = format!("file://{}", top.display()); + let added_uri = format!("file://{}", added.display()); + + // The cursor on `WIDTH` in `added_pkg::WIDTH`. + let definition = |id: u32| { + format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":30}}}}}}"# + ) + }; + + let mut live = Live::start(); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"workspaceFolders":[{{"uri":"{first_uri}","name":"first"}}],"capabilities":{{"workspace":{{"workspaceFolders":true}}}}}}}}"# + )); + let handshake = live.wait_for(|m| m["id"] == 1); + assert_eq!( + handshake["result"]["capabilities"]["workspace"]["workspaceFolders"], + serde_json::json!({ "supported": true, "changeNotifications": true }), + "{handshake:#?}" + ); + live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string("module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n") + .expect("json") + )); + + live.send(&definition(2)); + let before = live.wait_for(|m| m["id"] == 2); + assert_eq!( + before["result"].as_array().map(Vec::len), + Some(0), + "premise: the second folder is not in the workspace yet: {before:#?}" + ); + + // "Add Folder to Workspace". + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[{{"uri":"{second_uri}","name":"second"}}],"removed":[]}}}}}}"# + )); + + live.send(&definition(3)); + let after = live.wait_for(|m| m["id"] == 3); + let targets = after["result"].as_array().expect("a location list"); + assert_eq!(targets.len(), 1, "{after:#?}"); + assert_eq!(targets[0]["uri"], added_uri.as_str(), "{after:#?}"); + + // ...and closing it again takes those answers away. + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[],"removed":[{{"uri":"{second_uri}","name":"second"}}]}}}}}}"# + )); + live.send(&definition(4)); + let gone = live.wait_for(|m| m["id"] == 4); + assert_eq!(gone["result"].as_array().map(Vec::len), Some(0), "{gone:#?}"); + + live.finish(); + let _ = std::fs::remove_dir_all(&first); + let _ = std::fs::remove_dir_all(&second); +} + +/// §9c (folders-and-config): the server-pull settings round trip. +/// +/// The push half is covered by `pushed_settings_reach_the_formatter...`; this +/// is the pull half, and only a live session can drive it — the server asks, +/// the test answers as a client would, and the very next format shows the +/// answer took. +#[test] +fn the_configuration_pull_round_trips_over_the_wire() { + let dir = temp_dir("configpull"); + let file = dir.join("pull_me.sv"); + std::fs::write(&file, "module pull_me;\nwire a;\nendmodule\n").expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let format = |id: u32| { + format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + ) + }; + + let mut live = Live::start(); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"configuration":true}}}}}}}}"# + )); + live.wait_for(|m| m["id"] == 1); + live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + + // The server asks, unprompted, exactly once and for exactly our section. + let pull = live.wait_for(|m| m["method"] == "workspace/configuration"); + assert_eq!( + pull["params"], + serde_json::json!({ "items": [{ "section": "lucisv" }] }), + "{pull:#?}" + ); + let pull_id = serde_json::to_string(&pull["id"]).expect("json"); + // One entry per requested item, and the entry is the section itself. + live.send(&format!(r#"{{"jsonrpc":"2.0","id":{pull_id},"result":[{{"indent":4}}]}}"#)); + + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string("module pull_me;\nwire a;\nendmodule\n").expect("json") + )); + live.send(&format(2)); + let pulled = live.wait_for(|m| m["id"] == 2); + assert_eq!( + pulled["result"][0]["newText"], + serde_json::json!("module pull_me;\n wire a;\nendmodule\n"), + "the pulled indent beats the editor's tabSize=2: {pulled:#?}" + ); + + // An empty `didChangeConfiguration` is the modern "come and ask again", + // not a settings payload that clears everything. + live.send(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":null}}"#); + let again = live.wait_for(|m| m["method"] == "workspace/configuration"); + let again_id = serde_json::to_string(&again["id"]).expect("json"); + live.send(&format!(r#"{{"jsonrpc":"2.0","id":{again_id},"result":[{{"indent":8}}]}}"#)); + + live.send(&format(3)); + let repulled = live.wait_for(|m| m["id"] == 3); + assert_eq!( + repulled["result"][0]["newText"], + serde_json::json!("module pull_me;\n wire a;\nendmodule\n"), + "{repulled:#?}" + ); + + // And a client with nothing to say answers `null`, which is the defaults. + live.send( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{}}}"#, + ); + let empty = live.wait_for(|m| m["method"] == "workspace/configuration"); + let empty_id = serde_json::to_string(&empty["id"]).expect("json"); + live.send(&format!(r#"{{"jsonrpc":"2.0","id":{empty_id},"result":[null]}}"#)); + live.send(&format(4)); + let defaulted = live.wait_for(|m| m["id"] == 4); + assert_eq!( + defaulted["result"][0]["newText"], + serde_json::json!("module pull_me;\n wire a;\nendmodule\n"), + "the tab size is back in charge: {defaulted:#?}" + ); + + live.finish(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/file-watching/README.md b/docs/features/file-watching/README.md index 0fa4cb4..c2380a2 100644 --- a/docs/features/file-watching/README.md +++ b/docs/features/file-watching/README.md @@ -51,6 +51,17 @@ per notification. current scope: the scope ladder re-applies during the rebuild anyway, and one rebuild for a stray in-tree `.sv` is much cheaper than duplicating the ladder's logic per event and getting it subtly wrong. +- **A workspace-folder change does not need a new registration for the source + glob** (added 2026-08-27 by folders-and-config). `SOURCE_GLOB` is a + base-less *string* pattern, which the client matches against the workspace + it currently holds, so a folder added mid-session is covered by the + registration already in force; the `RelativePattern` form, which anchors a + glob to one folder's URI and would have to be re-sent per folder, is + deliberately not used. The **filelist** watcher is the exception: it is an + absolute path, and a relative `lucisv.filelist` is resolved against the + *first* root — so `server.rs` re-registers on a folder change whose + `filelist_path()` differs, exactly as it already did for a changed setting. + See `docs/features/folders-and-config/README.md`. - **Only the root filelist is watched, not its nested `-f` targets.** `lucisv_core::filelist::Filelist` reports the files a filelist names but not the filelists it *read*, and adding that field is a change to another diff --git a/docs/features/folders-and-config/README.md b/docs/features/folders-and-config/README.md new file mode 100644 index 0000000..1624806 --- /dev/null +++ b/docs/features/folders-and-config/README.md @@ -0,0 +1,568 @@ +# folders-and-config + +Two small §9c items, one round, because they are the same shape: both are a +piece of the session's *setup* that the server used to read exactly once and +never again. + +## Goal + +**`workspace/didChangeWorkspaceFolders`.** Until this round the workspace +roots were read at `initialize` and frozen for the life of the process, so +"Add Folder to Workspace" (or closing one) changed nothing until the editor +was restarted — a multi-repo SV project, which is the normal shape for a +design plus its verification IP, could not be assembled without a reload. The +server now advertises `workspace.workspaceFolders` (both halves) and adjusts +its root set from the notification, rebuilding the index once per event. + +**`workspace/configuration` (server-pull).** The `lucisv.*` settings only ever +arrived by *push*, and the push is the legacy path: `vscode-languageclient` +sends `didChangeConfiguration` with a real payload only where a +`synchronize.configurationSection` is configured, and the modern arrangement +is for the client to say "something changed" and for the server to fetch what +it needs. The server now asks for the `lucisv` section at startup, and again +on every empty `didChangeConfiguration`, gated on the client's own +`workspace.configuration` capability. The answer goes through **the same +parser** a push does, so the two paths cannot drift. + +## Assumptions + +- **A subdirectory added as its own workspace folder is its own root.** It + resolves its own `lucisv.toml` from its own tree, so the parent root's + `exclude` does not reach into it — files the parent excluded become + indexable through the child root (QA log F1, 2026-08-27; no + double-indexing, no ambiguity). This is the per-root config model applied + consistently to a shape that could not previously occur; a user who adds a + subfolder as a root is asking for exactly that folder. + + +- **A workspace folder is a directory on disk.** A folder whose URI is not a + `file:` URI is dropped rather than guessed at — `uri.rs`'s rule everywhere + else, and there is nothing to walk for a `vscode-vfs://` folder anyway. +- **The root set is a list, not a set with an identity.** Roots are compared + by path. A client that re-adds a folder it already sent, or removes one it + never sent, changes nothing and is told nothing: the notification has no + reply, and re-scanning to discover that the answer is the same is pure + cost. Removals are applied before additions, so a folder named in *both* + lists of one event survives (some clients spell a moved folder that way). +- **Removing a folder does not close its buffers.** The client owns buffer + lifecycle; LSP has no "the server dropped your file" message. An open buffer + whose folder was closed keeps exactly the deal every out-of-scope buffer has + always had — it is analyzed, diagnosed, formatted, and it still overrides + disk in the index by contributing itself (`Workspace::collect_sources` adds + every open document with a path, whatever the scope ladder said). Removing + the *last* folder is not a special case either: the session becomes the + rootless one rung 3 of the scope ladder already describes, where the scope + is the open buffers' own directories. +- **One set of settings per session, not one per folder.** The pull sends no + `scopeUri`. `ClientSettings` is a single struct read by `format::settings_for` + and the index scope, with no notion of "these settings, for files under that + folder" — asking per-resource would be asking for answers there is nowhere + to put. A multi-folder workspace where two folders want different indents + should say so in a `lucisv.toml` per folder, which already works and already + beats the editor setting. +- **A pull answer is never an error.** A refusal, a `null` entry, an empty + array, an object where an array belongs — all mean the same thing, "no + settings for you", which is the defaults. The user did not ask for this + request and cannot act on its failure, so nothing here opens a popup. +- **Settings can arrive after the first index build**, and this round does not + change that. The pull is sent at the same moment the watchers are registered + — the earliest legal point for a server-initiated request — and answered + later, in the loop. That is exactly what a pushed `didChangeConfiguration` + has always done too (it cannot arrive before `initialized` either): the + first index is built against the default scope, and a pulled + `lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands. + Nothing is *wrong* in between, it is simply the wider scope. + +## The settings model, stated once + +| what arrives | what the server does | +|---|---| +| `didChangeConfiguration` with a payload (any non-empty object) | applied directly, through `settings::from_payload` — the legacy path, unchanged | +| `didChangeConfiguration` with `settings: null` or `{}`, **and** `workspace.configuration` | pulls `workspace/configuration` for the `lucisv` section; nothing is applied until the answer comes back | +| `didChangeConfiguration` with `settings: null` or `{}`, **no** capability | applied directly, which resolves to "no opinion about anything" — exactly what such a client got before this round | +| startup, with `workspace.configuration` | one pull, unprompted | +| startup, without it | nothing; settings only ever arrive by push | + +Whichever door they came in, settings are adopted by one function — +`Server::apply_settings` — so `exclude`/`filelist` cost the same rescan and the +same watcher re-registration on both paths, and no third path can be added +without going through it. + +## The watcher determination + +**The source-glob registration does not need re-sending when folders change.** +`watch::registration` sends a `FileSystemWatcher` whose `globPattern` is the +plain string `**/*.{v,vh,sv,svh}`. In LSP a *string* glob pattern carries no +base URI, and the client matches it against the workspace it holds — VS Code +re-evaluates such a pattern against its current folder set, so a folder added +after registration is watched by the registration already in force. (The +alternative shape, `RelativePattern`, anchors a glob to one folder's URI and +*would* have to be re-sent per folder; this server has never used it, and +adopting it would mean one watcher per root for no gain.) + +**The filelist watcher does.** The second watcher in the same registration is +an absolute path, and `Workspace::filelist_path` resolves a *relative* +`lucisv.filelist` against `roots.first()`. So a folder event that changes which +root is first — or that removes the root the setting was anchored to — moves +the watched path without anyone touching the setting. The handler therefore +compares `filelist_path()` before and after and re-registers when it moved: +literally the same two lines `didChangeConfiguration` already ran, for the +same reason (the watched path is baked into the registration). + +## Handshakes + +**Consumed from `lsp-types` 0.97:** `WorkspaceFoldersServerCapabilities +{ supported, change_notifications }` — `change_notifications` is +`OneOf` and is sent as `Left(true)`; the string form exists so +the registration can be undone by id, and this server never unregisters it. +`DidChangeWorkspaceFoldersParams { event: { added, removed } }`, +`ConfigurationParams`/`ConfigurationItem`, and `WorkspaceConfiguration` +(`Result = Vec`). + +**Asked of `state.rs` (delivered, minimal):** one new public method, + +```rust +pub fn change_roots(&mut self, added: Vec, removed: &[PathBuf]) -> bool +``` + +which adjusts the private `roots` list and reports whether it moved, in the +same shape `set_client_settings` already reports "you owe a rebuild". Nothing +else in `state.rs` changed: `rebuild_index` walks `self.roots` and so already +does the right thing for a wider or narrower set, and the rootless fallback +(`default_files` → `sibling_files`) already covers "the last folder went +away". The root list is deliberately *not* exposed — the server has no use for +it beyond changing it, and `has_roots()` already answers the one question it +does ask. + +**Promised to `server.rs`'s other handlers:** `Pending` replaces the +`applying: HashMap` map. Every server-initiated request +whose answer matters is registered in one `pending: HashMap`; everything else (watcher registration, `workDoneProgress/create`, +`codeLens/refresh`, `showDocument`) is still absent from it and still falls +through `response` untouched. A future request kind that needs its answer read +adds a variant, and the compiler names every place that must handle it. Two +maps would have meant two lookups in `response` and two chances to forget one. + +**`settings.rs` gained** `SECTION` (the one spelling of `"lucisv"`, used by the +parser and by the pull's `ConfigurationItem`), `from_section` (a pull answer, +wrapped back into the push shape so there is exactly one parser) and +`says_nothing` (whether a push payload is really a pull signal). + +**Nothing outside `crates/lucisv_server` was touched**, and no dependency was +added. `editors/vscode` was deliberately left alone, and the interplay is +worth stating: `extension.js` still sets +`synchronize: { configurationSection: 'lucisv' }`, so VS Code keeps *pushing* +a real payload — the legacy path, unchanged — while `vscode-languageclient` +advertises `workspace.configuration` and `workspace.workspaceFolders` on its +own and therefore also answers the startup pull (with the same section, read +by the same parser, to the same result). Dropping the `synchronize` line +would leave the pull in sole charge and is a client-side change for another +round. `smoke.js` sends `capabilities: {}` — the no-capability polarity, and +the one worth keeping under test. + +## Status / TODO + +- [x] `workspace.workspaceFolders: { supported: true, changeNotifications: true }` + advertised, and pinned as JSON at the key a client reads. +- [x] `workspace/didChangeWorkspaceFolders` handled: added/removed adjust the + root set, one `reindex()` per notification. +- [x] A removed folder's files leave the index; its open buffers stay open and + keep being diagnosed. +- [x] Duplicate adds, removing a never-added folder, an empty event, params + that do not parse, a non-`file:` folder — all no-ops, none of them a + rescan. +- [x] Watcher determination made and implemented: source glob workspace-wide + (no re-registration), filelist path anchored at the first root + (re-registered when it moves). +- [x] `workspace.configuration` read from the client's capabilities. +- [x] One `workspace/configuration` at startup, gated on that capability. +- [x] An empty `didChangeConfiguration` pulls instead of resetting; a + populated one still applies directly. +- [x] The answer applies through `settings::from_section` → the same + `from_payload` a push uses, and through one `apply_settings`. +- [x] `null`/empty/malformed/errored answers are total and leave the defaults. +- [x] `applying` → `pending: HashMap`; three-way + interleave tested. +- [x] Tests: **27 new** — 4 in `settings.rs`, 4 in `state.rs`, 14 + `Session`-level in `server.rs`, 3 capability tests in `main.rs`, 2 e2e + sessions against the real binary. +- [x] `docs/features/lucisv-server/README.md` capability table and the + roots/settings model text updated; `docs/features/file-watching/README.md` + told about the folder interaction; TODO.md §9c boxes checked. + +## Work log + +### 2026-08-27 — dev agent + +**Item 1, `didChangeWorkspaceFolders`.** + +- `main.rs::capabilities` now sends `workspace.workspaceFolders` with both + fields. They are separate statements and a client reads them separately: + `supported` says the server understands a multi-folder workspace at all, + `changeNotifications` is what makes the client *send* the notification. + `change_notifications` is `OneOf` in lsp-types 0.97 (checked + against the crate source, not assumed); `Left(true)` is the right form here + because the id-string variant exists only so the registration can later be + unregistered by name, which this server never does. +- `state.rs::change_roots` is the whole of the state change — 8 lines. Roots + were already a private `Vec` that `rebuild_index` re-walks from + scratch, so widening and narrowing the set is genuinely nothing more than + editing that list. Removals before additions; `bool` out, in the same shape + `set_client_settings` uses, so the server's "did this cost a rescan?" + question is asked the same way for both kinds of change. +- The handler is five lines of body: parse, convert URIs to paths, change the + roots, reindex if they moved, re-register the watchers if the *filelist* + path moved. One `reindex()` per notification — an event carries both lists, + and the progress bar, the code-lens refresh and the diagnostics generation + all ride inside `reindex()` already, which + `one_folder_notification_is_one_rescan_with_one_bar_and_one_generation` pins + rather than assumes. +- **The open-buffer question resolved by reading, not by inventing.** The + brief asked that buffers in a removed folder keep behaving like rootless / + out-of-scope buffers. They already do, and no code was needed: + `collect_sources` appends every open document with a path *after* the scope + ladder has spoken, so such a buffer stays in the index as itself; `reindex` + republishes every open URI whatever the roots say; and `didOpen`'s + root-conditional (`has_roots()` → publish, else reindex) reads the current + root set, so a session that has lost its last folder starts behaving like + the single-file case from the next `didOpen` on. The two tests + (`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`, + `removing_the_last_root_falls_back_to_the_rootless_model`) exist to keep + that true, not to describe something new. +- **The watcher determination** is written up in its own section above. Short + version: the source glob is a base-less string pattern and is workspace-wide, + so it needs no re-registration; the filelist watcher is an absolute path + anchored at the first root, so it does — and the handler reuses the exact + before/after comparison `didChangeConfiguration` already made. + +**Item 2, `workspace/configuration`.** + +- `ClientAbilities::configuration`, read in `main.rs` from + `capabilities.workspace.configuration`, in the same shape as its five + siblings. +- `Server::request_configuration` sends one item, `section: "lucisv"`, no + `scopeUri`, and records the id as `Pending::Configuration`. It is called + from `Server::new` (immediately after `register_watchers`, which is the + earliest legal moment and already proven so by the file-watching round) and + from the `didChangeConfiguration` handler when the payload says nothing. +- **Pending-map decision: one map, an enum, refactored.** The alternative was + a second `HashMap` beside `applying`. One map won: `response` + is then a single lookup and a single `match`, the "which of our requests is + this?" question has exactly one answer rather than one per map, and a third + kind is a variant the compiler makes you handle instead of a map somebody + forgets to consult. The cost is a rename (`applying` → `pending`) and one + extracted function (`applied`, which is the old body verbatim). The + fall-through that makes every *other* server-initiated request's answer + ignorable is unchanged and still the documented rule. +- **One parser, spelled out.** A pull answers the *contents* of the section; + a push nests them under `lucisv`. Rather than a second reader, + `settings::from_section` wraps the answer back into the push shape and calls + `from_payload`. `a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one` + asserts the two agree on a fully-populated section *and* on a fully-junk + one, which is the half that would actually rot. +- **One applier.** The body of the old `didChangeConfiguration` arm became + `Server::apply_settings` (rescan on a scope change, re-register on a moved + filelist path) and both doors now go through it. There is no way to adopt + settings without paying what they cost. +- `settings::says_nothing` decides push-vs-pull: `null` and `{}` are the + client saying "come and ask"; anything with a key in it is a payload, even + when the key is some other server's section (that case has always meant "no + opinion about anything" and still does). +- **Deliberate non-change:** the pull's answer can land after the first index + build. Stated in Assumptions, not fixed — blocking `Server::new` on a client + round trip would be a deadlock waiting to happen (the spec lets a client + answer whenever it likes) and the push path has always had the same shape. + +**Tests.** 4 new in `settings.rs` (pull/push parser agreement, unusable +answers, the push-empty predicate, the section constant), 4 new in `state.rs` +(add/remove, every no-op shape, a folder in both lists, the last-folder +fallback), 14 new `Session`-level tests in `server.rs` (folder add reaching +`workspace/symbol`, removal with a still-diagnosed buffer, one-rescan-per- +notification with bar/publish/refresh/generation counts, the six no-op shapes, +the watcher re-registration polarity, the startup pull's params, the no-pull +polarity, a pulled answer reaching the formatter, a pulled `exclude` rebuilding +the index, seven unusable answers plus an error response, empty-push-pulls, +empty-push-without-the-capability, populated-push-applies-directly, and the +three-way interleave), 3 new capability tests in `main.rs`, and 2 new e2e +sessions (a folder added and removed over the wire with a definition resolving +into it, and a full pull round trip including the re-pull and the `null` +answer). + +**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets` +clean; `cargo test --workspace` green (982 in the server binary, 48 e2e); +`node editors/vscode/smoke.js` OK. One flake seen and *not* caused here: +`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk` is a +wall-clock ratio test and fails under a loaded machine — it passes on its own +and in a normal `--workspace` run. + +## QA log + +### 2026-08-27 — QA agent + +Reviewed the working tree on top of `45db6cd` (`git diff 45db6cd`), against +the dev's claims above and the lead's attack-surface list. Verified by +reading every changed line in `main.rs`/`server.rs`/`settings.rs`/`state.rs`/ +`tests/e2e.rs`, then attacking each surface below — mostly by adding a +pinning test that exercises it directly rather than by inspection alone, +since a claim about interleaving or wire order is only as good as a test +that would fail if it were wrong. No redesign; two small additions beyond +tests (both noted below) were within "small and unambiguous." + +**Gates.** +- `cargo fmt --all -- --check`: clean (after my own additions were formatted + — one round of `cargo fmt --all` was needed once I'd added tests by hand). +- `cargo clippy --all-targets`: clean, no warnings, before and after my + additions. +- `cargo test --workspace`, run twice end-to-end: green both times, no + failures, no flake. Baseline was 982 `lucisv_server` unit tests as the dev + reported; ended at 993 after the 11 tests I added (see below). 48 e2e tests + green throughout. +- The lens flake (`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`, + `crates/lucisv_server/src/lens.rs:652`): did **not** fire in two full + `cargo test --workspace` runs, nor in 5 back-to-back runs of that test + alone with four `yes > /dev/null` processes competing for CPU + (ratio stayed ~1.4–1.5x against the 2x budget each time). Did not need to + check it at `45db6cd` since it never reproduced here — nothing in this + diff touches `lens.rs`, and the test is a wall-clock ratio exactly as the + dev described, so I take the dev's report at face value. Not a blocker. +- `node editors/vscode/smoke.js target/debug/lucisv-server` (had to pass the + path explicitly — `lucisv-server` is not on `PATH` in this checkout): + `OK`. This is the no-capability (`capabilities: {}`) polarity, so it + exercises the "client can't be asked, keeps today's behaviour" branch of + both features. + +**Attack surfaces — verdicts.** + +1. **`roots.first()` dependency.** Verified clean, with new pins. + `Workspace::change_roots` (`state.rs:138`) removes before adding and dedups + adds via `contains`, so insertion order is preserved and a folder can only + ever appear once — confirmed by + `a_folder_added_twice_across_two_events_is_absent_after_one_removal` + (new, `state.rs`): two separate add events for the same path plus one + removal leaves it fully absent, not merely "count decremented." The + remove-then-add-reorders-first case is exactly what + `a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves` + (existing, `server.rs:4908`) already pinned end to end (drop the first + root, watch the second's `files.f`, both the reindex and the + unregister+register fire). The "no roots left" total case was **not** + pinned before this round: added + `removing_the_last_root_leaves_a_relative_filelist_unanchored` + (`state.rs`, near line 549) — `filelist_path()` returns the bare relative + path (`PathBuf::from("files.f")`), anchored at nothing, once the last root + is gone. Nothing panics and `source_files` still degrades to the rootless + walk with a warning when that bare path can't be read + (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so` + already covers that half) — but it is a real, newly-reachable oddity + (see finding F1 below) rather than an outright bug. + +2. **`Pending` refactor / applyEdit routing.** Verified clean. The pre-existing + applyEdit round's tests (`a_command_pushes_its_edit_...`, + `a_response_with_a_jsonrpc_error_is_reported_too`, + `a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`, + etc.) are untouched by the diff and green. `three_outstanding_requests_are_answered_by_id_in_any_order` + (`server.rs:5127`) does genuinely have all three requests + (`applyEdit`, `workDoneProgress/create`, `workspace/configuration`) + outstanding simultaneously before any answer — confirmed by reading + `Session::sent`: it drains the channel once and the test pulls all three + ids from that single drain — and answers them out of the send order + (pull, then create, then edit) with each answer reaching the right + handler. Two follow-up questions the dev's tests didn't cover, both now + pinned: **two `Configuration` entries pending at once, answered out of + order** — new `two_outstanding_configuration_pulls_are_each_answered_by_their_own_id` + (`server.rs`): each answer is applied independently through its own id; + whichever is *processed* last is what's in force after, no id-based + precedence, which is the only sane semantics for a `HashMap` keyed by id. + **An answer to an id `pending` doesn't hold** — new + `an_answer_to_a_request_the_server_never_tracked_is_silently_ignored` + (`server.rs`): a stale re-answer to an already-consumed id, and an id + never sent at all, are both no-ops (trivially true from + `HashMap::remove`'s `Option`, but worth a test that would catch a future + refactor that made `response` assume the id is always present). + +3. **Settings pull correctness.** Verified clean, with one real gap closed. + `configured` (`server.rs:1174`) reads `response_result.unwrap_or(Value::Null)` + then `answered.get(0)` — a client answering with 2 entries silently uses + only entry 0 (correct: exactly one item was asked for), 0 entries or a + non-array (`get(0)` on a string/number returns `None`) both fall through + to `Value::Null` → defaults; `an_unusable_pull_answer_leaves_the_defaults_and_says_nothing` + (`server.rs:5091`, pre-existing) already covers `null`, `[]`, `[null]`, a + bare string, an object, junk-typed fields, and a `lucisv`-nested answer + (the pull/push shape mismatch), plus an actual JSON-RPC error response — + all resolve to defaults with no popup. `a_pulled_answer_that_changes_the_scope_rebuilds_the_index` + (`server.rs:5048`, pre-existing) does assert the **index** actually + changed (`indexed(&session, "scratch_pkg")` flips from 1 to 0), not just + "no crash" — confirmed by reading it, not just trusting the name. + **Gap found and closed:** nothing exercised a pulled *filelist* moving the + watched path — `apply_settings` is shared code so it was very likely + already correct, but "very likely" isn't "pinned." Added + `a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses` + (`server.rs`, next to the exclude test): a pulled `{"filelist": "files.f"}` + does cost an unregister+register with the new absolute path in the + registration, exactly like the pushed case. **Precedence, traced and now + pinned both directions:** the loop is single-threaded and processes + messages in strict receive order; `apply_settings` always replaces the + whole `ClientSettings` struct rather than merging, so whichever message is + *processed* last wins, full stop. `a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked` + (pre-existing) covers pull-then-push; added + `a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding` + for the other direction (push arrives while a pull is still outstanding, + the pull's answer lands after and clobbers it). Both are "last processed + wins," no special-casing either way — worth knowing, not worth fixing. + +4. **Folder-change semantics.** Mostly verified clean; one real (low-severity, + arguably by-design) finding. + - Definition into an added folder: `a_folder_added_mid_session_is_indexed_over_the_wire` + (e2e, pre-existing) asserts the returned location's `uri` string equals + the expected `file://` URI exactly, which is as much "decoded correctly" + as a same-process round trip can show without deliberately using a + percent-encoded character in the added folder's path (this round's e2e + test doesn't; existing coverage for URI-decoding a workspace path with + unusual characters lives in `include_nav_round_trips_in_a_workspace_whose_directory_has_a_space`, + unrelated to folder-add specifically). Did not add a new e2e test for + this — the marginal risk is in `uri::uri_to_path`, which is untouched by + this round and already has its own coverage. + - Removed folder's symbols gone from `workspace/symbol`: + `a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed` + confirms via `indexed()` (an index-membership check, equivalent to what + `workspace/symbol` reads from) that the removed folder's non-open file + drops to 0 hits; `a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol` + drives a real `workspace/symbol` request for the added-folder case. + - **F1 — subdirectory added as its own root bypasses the parent's + `exclude`.** New test + `a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed` + (`state.rs`) confirms there is **no** double-indexing/ambiguity when an + already-covered subdirectory is added as a second root — `walked_files`'s + `sort()`+`dedup()` on the combined path list handles that correctly, and + `indexed()`'s "found exactly once" check would have caught an ambiguous + double-registration if there were one. But a directory the parent root's + `lucisv.toml` excludes **is** reachable once it's added as a root in its + own right, because `walked_files` (`state.rs:365`) resolves each root's + `exclude` independently via `Discovery::for_dir(root)`, and nothing + excludes a root from itself. This is consistent with the documented + per-root config model (`walked_files`'s own doc comment says so) and + arguably *correct* — "Add Folder to Workspace" on a specific directory is + an explicit ask to index it — but it was unreachable before this round + (roots were frozen at `initialize`), so it's a genuinely new behavior the + dev's README doesn't mention. Recommend a one-line callout in + Assumptions if the lead agrees it's intentional; not a blocker either way, + and not a corruption risk (formatter output is verified regardless of + what got indexed). + - Folder added twice then removed once: set semantics confirmed (new test, + see item 1 above) — present after two adds, absent after one removal, + not "still there because it was added twice." + - Trailing slash: verified clean, and pinned anyway since the README calls + it out as a boundary worth checking. `uri_to_path` decodes the URI + verbatim (trailing slash included), but `PathBuf`/`Path` equality + compares `Components`, not raw bytes — `Path::new("/a/b/") == Path::new("/a/b")` + is `true` in std, confirmed with a throwaway `rustc` check before writing + the test — so `change_roots`'s `contains`/`retain` already treat them as + the same folder with no code needed. New: + `a_trailing_slash_in_the_removed_folder_still_matches_the_held_root` + (`state.rs`). + +5. **Open-buffer convention.** Verified clean, one gap closed. + `a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed` + does assert diagnostics *content* — `!published[0].diagnostics.is_empty()` + after editing the buffer to be broken, not merely "a publish happened." + Closing such a buffer was **not** exercised — added a continuation of the + same test (`server.rs`, same test) that sends `didClose` afterward and + confirms the diagnostics clear (`published[0].diagnostics.is_empty()`). + The code path (`DidCloseTextDocument` handling, `server.rs:1100`) is + pre-existing and untouched by this diff — it doesn't special-case removed + folders at all, which is correct: closing is generic. + +6. **Startup pull ordering.** Verified clean, gap closed. `Server::new` + (`server.rs:178`) calls `register_watchers()` then `request_configuration()` + in that order in the source, but nothing checked the *wire*. Added + `the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire` + (`server.rs`): checks both the drained-channel order and, independently, + that the `RegisterCapability` request's `lucisv-N` id number is lower than + the pull's (every outgoing request id comes off one monotonically + increasing counter in `send_request`, `server.rs:1251`, so the numeric + suffix *is* the send order — a second, independent way to catch a future + reordering that a channel-order check alone might not). The full chain — + pull answer → `apply_settings` → filelist moved → re-register — is now + pinned by item 3's `a_pulled_filelist_re_registers_the_watchers_...` test. + "Pulled settings can land after the first index build" is honestly + documented in Assumptions and in the Work log; I didn't find anywhere it's + overstated. + +7. **CLAUDE.md compliance.** Clean. + - No `unwrap()`/`expect()`/`panic!` in the non-test portion of + `main.rs`/`server.rs`/`settings.rs`/`state.rs` (checked by slicing each + file at its `#[cfg(test)]` boundary and grepping the part before it — + all four files have exactly one such boundary). + - New public items have doc comments: `Workspace::change_roots`, + `settings::SECTION`, `settings::from_section`, `settings::says_nothing`, + `ClientAbilities::configuration` all do. (Three *pre-existing* undocumented + `pub fn`s in `state.rs` — `index`, `document`, `close_document` — are out + of this round's diff and not this review's problem.) + - `docs/features/folders-and-config/README.md` has every required section + exactly once (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA + log, Review), plus two extra explanatory sections which the template + doesn't forbid. + - Both `TODO.md` §9c items are checked with their original text intact and + a `→ delivered ...` addendum appended, not rewritten. + - `crates/vlog_formatter/src/verify.rs`: zero diff against `45db6cd` + (`git diff 45db6cd -- '**/verify.rs'` is empty) — untouched, as this + round should never need it (nothing here touches formatting or + verification). + - `docs/site/` untouched by both the dev's diff and by me (per this + round's instructions, never opened it). + +**C. Beyond the list — "own shapes."** +- `a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added` + (`server.rs`): add, remove, add of the same folder across three separate + notifications costs three separate rescans (no cross-notification + batching — `change_roots` only batches within one event, as designed) and + the net state (two adds, one remove) is "present," matching set semantics. +- `a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish` + (`server.rs`): a session that starts with no roots at all (impossible to + change mid-session before this round) gains its first folder via + `didChangeWorkspaceFolders`, and the very next `didOpen` correctly takes + the `has_roots()` branch — publish only, no second rescan — where it would + have reindexed before the folder arrived. (Caught my own arithmetic error + writing this: `generation` counts *both* a buffer's text and the index, so + a rootless `didOpen` costs two bumps — `set_document` plus `reindex` — not + one; fixed the assertion rather than the code, since the code is correct + and pre-existing.) + +**Fixes made directly (small, unambiguous, noted here per the workflow).** +- None to production code. Everything above is test-only: 11 new tests + across `state.rs` (5) and `server.rs` (6), all passing, `cargo fmt`/ + `clippy` clean throughout. `cargo test --workspace` ended at 993 + `lucisv_server` unit tests (982 dev baseline + 11) plus the unchanged + 48 e2e, both green across two full runs. + +**Verdict: committable as-is.** No corruption risk, no invariant violated, +no test that should exist and doesn't after this pass. F1 (subdirectory +root bypassing parent's exclude) is worth a documentation line from the lead +or dev — not worth blocking on, since it's arguably correct behavior and +carries no data-loss or formatting-correctness risk. + +## Review + +### 2026-08-27 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. Both items landed the way small protocol features should: the +folder handler is one 8-line state method plus the existing reindex +machinery (with the bar, the lens refresh and the generation all pinned +as riding along rather than assumed), and the config pull reuses the one +settings parser and the one applier so the two doors cannot drift. The +watcher determination — base-less glob needs nothing, the absolute-path +filelist watcher re-registers through the comparison the push path +already ran — is the kind of read-first engineering this workflow is +for. The Pending-enum refactor is accepted: one map, one match, and a +third request kind is now a compiler-enforced variant; QA re-ran the +apply-edit suite and interleaved all three answer kinds out of order to +prove the shipped routing survived. + +QA's roots.first() attack found the design holds (order preserved, +last-root-removal total) and its eleven added tests closed every +claim that lacked one, including the previously-untested +pull-answer-moves-the-filelist chain. F1 is accepted as designed and +now documented in Assumptions: a subdirectory added as its own root is +its own root, per-root config applied consistently. The extension's +redundant push+pull double-answer stays filed for a client-side round. +Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index d9d024e..20d5cb7 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -52,6 +52,8 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README | | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | | `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` | +| `workspace/didChangeWorkspaceFolders` | `Workspace::change_roots` + `rebuild_index` | Folders added and removed mid-session, since 2026-08-27. One rescan per *notification* (the event carries both lists), and none at all for an event that leaves the root set where it was — a folder already held, one never held, an empty event, a non-`file:` folder. A removed folder's files leave the index; its open buffers stay open and keep being diagnosed, exactly as an out-of-scope buffer always has. Advertised as `workspace.workspaceFolders: { supported, changeNotifications }` — both halves, because a client reads them separately. See `docs/features/folders-and-config/README.md` | +| `workspace/configuration` | `settings::from_section` → `from_payload` | Server-**initiated**, since 2026-08-27: the `lucisv` section, asked for once at startup and again on every *empty* `didChangeConfiguration` (the 3.17 client's "something changed, ask me"). Only for a client that advertised `workspace.configuration`; a push with a payload still applies directly, so the legacy path is untouched. The answer is entry 0 of an array and goes through the same parser a push does; an error, a `null`, an empty array or junk all mean the defaults, and none of them says anything to the user. Same feature README | | `workspace/willRenameFiles` | `includes::IncludeGraph` (through `resolve_as_if`) | The client is about to rename files and asks what that costs: every `` `include`` in scope whose **resolved** target moves — never a filename match — is re-spelled so it still resolves, in the form it was written in (bare stays bare where a rung reaches it, angled resolves through `+incdir+`s only, absolute stays absolute), shortest resolving suffix first and a `../`-relative spelling only as a last resort. An include written *in* a file that moves is re-spelled too. An include no spelling can reach is **left exactly as written** and named in a `window/showMessage` warning — nothing is invented. `null` when there is nothing to do. Folders are answered as well as files (LSP sends only the folder's URI; a folder is a path prefix). Every edit covers the path token alone and is verified three ways before it is emitted — see `docs/features/file-operations/README.md` | | `workspace/didRenameFiles`, `workspace/didDeleteFiles` | `Workspace::rebuild_index` | One `reindex()` per notification whose paths touch the index's scope, filtered by the same predicate a watched-file event is. Deliberately not deduplicated against the watcher: a client may send both, and a second rebuild re-reads the tree rather than changing an answer. Source-file filters only — a folder move reaches the index through the watcher's own events. Same feature README | | `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` | @@ -231,7 +233,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`. | layer | rebuilt when | cost | |---|---|---| | a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute | -| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `lucisv.exclude`/`lucisv.filelist` | full re-scan of the roots | +| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots | | the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | **Per-file recompute on every keystroke** is the strategy TODO.md §6 states @@ -282,6 +284,23 @@ model above; nested `-f` filelists are not watched, only the root one; rebuild from any cause picks it up); and there is no time-based debouncing, so a burst arriving as several separate notifications costs one rebuild each. +**Settings arrive two ways since 2026-08-27** (folders-and-config): pushed, as +they always were, and *pulled*. A client that advertised +`workspace.configuration` is sent one `workspace/configuration` for the +`lucisv` section at startup, and another whenever it sends a +`didChangeConfiguration` whose payload is empty — which is the 3.17 client's +way of saying "something changed, come and ask", and is what +`vscode-languageclient` sends once no legacy `synchronize.configurationSection` +is configured. A push that carries a real payload still applies directly, so +nothing about the old path moved. Both doors lead to one parser +(`settings::from_payload`) and one applier (`Server::apply_settings`), so a +setting cannot mean two things depending on how it arrived, and +`exclude`/`filelist` cost the same rescan either way. A pulled answer can land +*after* the first index build — as a pushed one always could, since neither +can arrive before `initialized` — so the first index is built against the +default scope and a narrowing setting costs one extra rescan when it lands. +Rules: `docs/features/folders-and-config/README.md`. + **Definition targets in other files need that file's text** to turn a `TextRange` into a `Range`, and the index deliberately keeps no file contents. The server resolves a target by taking the **open buffer's text if that path @@ -313,6 +332,13 @@ not see. on a POSIX path legitimately named `/C:`. - **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`. + ~~They are read once and frozen for the session.~~ **Superseded + (folders-and-config, 2026-08-27): `workspace/didChangeWorkspaceFolders` + adjusts the root set mid-session, one rescan per notification. A removed + folder's files leave the index while its open buffers stay open and keep + being diagnosed, and removing the *last* folder simply becomes rung 3 of + the scope ladder — the rootless case — with no special handling. See + `docs/features/folders-and-config/README.md`.** ~~`.gitignore` and `--exclude` are **not** honored~~ **Superseded by lucisv-core-lift (lead note): the scan now uses the lifted `lucisv_core` walk — `.gitignore` always on, workspace-root config excludes applied. The old