diff --git a/TODO.md b/TODO.md index 045ed4d..3587995 100644 --- a/TODO.md +++ b/TODO.md @@ -703,9 +703,19 @@ and are not gaps. publish — per notification. Advertised as `TextDocumentSyncOptions` with the open/close and `save.includeText: false` values a bare `Kind` already implied, so no client's save behavior moved. -- [ ] **`textDocument/willSaveWaitUntil`** — the protocol-native +- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native format-on-save hook (client-side `editor.formatOnSave` already works; this serves the editors without it). + → `docs/features/will-save-wait-until/README.md`; advertised as + `willSaveWaitUntil: true` (the plain `willSave` notification stays + unadvertised — there is nothing for us in it), and gated on a new + `lucisv.formatOnSave` setting that is **off** by default, so a client + with its own format-on-save never formats twice. On, it is + `textDocument/formatting` with a different trigger: same engine, same + all-or-nothing edit, same `[]` for an already-formatted buffer, and the + settings ladder minus its `tabSize` rung because the request carries no + `FormattingOptions`. Every save reason formats; an unopened buffer and + the off state both answer `null`. - [ ] **Semantic tokens `range` + `full/delta`** — we set `range: None` and no delta, so clients re-request whole-file token sets on every edit. Delta needs `resultId` bookkeeping per buffer. diff --git a/crates/lucisv_server/src/format.rs b/crates/lucisv_server/src/format.rs index 3036e3e..c8ebfac 100644 --- a/crates/lucisv_server/src/format.rs +++ b/crates/lucisv_server/src/format.rs @@ -60,6 +60,20 @@ pub fn settings_for( Settings { config: config_from(&file, client, options), problem } } +/// Resolve the settings governing a buffer for a request that carries no +/// `FormattingOptions`. +/// +/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol +/// simply does not carry one there. So the ladder `settings_for` documents +/// runs with rung 3 missing, which is the same thing `indent_width` does for a +/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in +/// default. Spelled as hard tabs and a zero width because `config_from` takes +/// neither, so nothing is guessed on the user's behalf. +pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings { + let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() }; + settings_for(doc, client, &none) +} + /// Format a buffer. /// /// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an @@ -495,6 +509,31 @@ mod tests { assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default"); } + #[test] + fn a_request_without_options_climbs_the_same_ladder_without_rung_3() { + // What `willSaveWaitUntil` resolves to: the protocol sends no + // `FormattingOptions` with it, so the editor's tab size is simply not + // one of the inputs. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let settings = settings_without_editor_options(doc, &pushed(None, Some(8))); + assert_eq!(settings.config.indent_width, 4, "the config still wins"); + assert_eq!(settings.problem, None); + + // With no config, the pushed setting is the highest rung there is. + let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8))); + assert_eq!(settings.config.indent_width, 8); + assert_eq!(settings.config.max_width, 60); + // And with nothing pushed either, the built-in default — never a + // guess from an option that was not sent. + let settings = settings_without_editor_options(doc, &none()); + assert_eq!(settings.config.indent_width, Config::default().indent_width); + assert_eq!(settings.config.max_width, Config::default().max_width); + } + #[test] fn a_broken_config_leaves_the_pushed_settings_in_charge() { // Nothing from a broken `lucisv.toml` is used, so the next rung down is diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 5247db4..2566a59 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -95,8 +95,14 @@ fn capabilities() -> ServerCapabilities { text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions { open_close: Some(true), change: Some(TextDocumentSyncKind::INCREMENTAL), + // The plain `willSave` notification carries nothing this server + // can act on, so it is left unadvertised; `willSaveWaitUntil` is + // the format-on-save hook, for the editors that have no + // format-on-save of their own. It answers `null` unless + // `lucisv.formatOnSave` is on — see + // `docs/features/will-save-wait-until/README.md`. will_save: None, - will_save_wait_until: None, + will_save_wait_until: Some(true), save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions { include_text: Some(false), })), @@ -322,6 +328,17 @@ mod tests { assert!(caps.diagnostic_provider.is_some()); } + #[test] + fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() { + let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync + else { + panic!("the options form, not a bare kind"); + }; + assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL)); + assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered"); + assert_eq!(options.will_save, None, "the plain notification has nothing for us"); + } + #[test] fn the_diagnostic_options_say_what_this_server_actually_does() { let Some(DiagnosticServerCapabilities::Options(options)) = diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 8f45e2a..fa789fb 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -21,7 +21,7 @@ use lsp_types::request::{ FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, SelectionRangeRequest, SemanticTokensFullRequest, SignatureHelpRequest, - UnregisterCapability, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + UnregisterCapability, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, @@ -38,10 +38,10 @@ use lsp_types::{ RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, - UnregistrationParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, - WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, WorkspaceEdit, - WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse, - WorkspaceUnchangedDocumentDiagnosticReport, + UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkspaceDiagnosticParams, + WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, + WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, + WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; use serde_json::Value; @@ -158,6 +158,10 @@ impl Server { let result = match method.as_str() { Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)), RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)), + // Format-on-save, protocol-native: the client asks before it + // writes, and applies whatever comes back. Opt-in, and the decline + // is the cheap path — see `will_save_wait_until`. + WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)), HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); @@ -427,6 +431,40 @@ impl Server { self.edits(result) } + /// `textDocument/willSaveWaitUntil` — format the buffer the client is + /// about to write, for the editors that have no format-on-save of their + /// own. + /// + /// `null` unless `lucisv.formatOnSave` is on. A capable client sends this + /// before *every* save, so declining has to be the cheap path — and an + /// editor that already formats on save (VS Code's `editor.formatOnSave`, + /// which runs `textDocument/formatting`) would otherwise format twice. + /// + /// When it is on, this is `textDocument/formatting` with a different + /// trigger: the same engine, the same settings ladder, the same + /// all-or-nothing contract — one whole-document edit built from verified + /// output, or no edit at all. The save's `reason` is not read: manual, + /// after-delay and focus-out are all saves, and the user asked for their + /// saves to be formatted. The text is the buffer the server holds, because + /// the request carries none and the client has not written yet. + fn will_save_wait_until( + &mut self, + params: WillSaveTextDocumentParams, + ) -> Result { + if !self.workspace.client_settings().format_on_save { + return Ok(Value::Null); + } + let uri = params.text_document.uri; + let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; + // No `FormattingOptions` on this request — the protocol carries none — + // so the ladder runs without its `tabSize` rung. + let settings = + format::settings_without_editor_options(doc, self.workspace.client_settings()); + let result = format::formatting(doc, &settings.config); + self.warn_about_config(&uri, settings.problem); + self.edits(result) + } + /// Say once per change of a file that its `lucisv.toml` could not be read. fn warn_about_config(&mut self, uri: &Uri, problem: Option) { if let Some(problem) = problem { @@ -1967,4 +2005,307 @@ mod tests { assert_eq!(published.len(), 1); assert!(published[0].diagnostics.is_empty(), "{published:#?}"); } + + // ------------------------------------------------------------------ + // `textDocument/willSaveWaitUntil` + // ------------------------------------------------------------------ + + /// The `lucisv.formatOnSave` push a client makes, on or off. + fn format_on_save(on: bool) -> Value { + serde_json::json!({ "settings": { "lucisv": { "formatOnSave": on } } }) + } + + /// One `willSaveWaitUntil` for a buffer, for the reason given (1 = manual, + /// 2 = after delay, 3 = focus out). + fn will_save(session: &mut Session, uri: &Uri, reason: u8) -> Value { + session.result( + WillSaveWaitUntil::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "reason": reason }), + ) + } + + /// What `textDocument/formatting` answers for the same buffer, asking for + /// the 2-space tab an editor defaults to — which is also the built-in + /// indent, so the two paths resolve to the same settings. + fn formatting_result(session: &mut Session, uri: &Uri) -> Value { + session.result( + Formatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ) + } + + #[test] + fn the_save_hook_declines_until_format_on_save_is_pushed() { + let tree = Tree::new("willsaveoff"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + + // The default: a client that never pushed the setting is answered + // `null`, and told nothing at all. + assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "off by default"); + assert!(session.shown().is_empty(), "a decline is silent"); + + // Pushed on, mid-session, with no restart. + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let edits = will_save(&mut session, &uri, 1); + assert_eq!(edits[0]["newText"], "module m;\n wire a;\nendmodule\n", "{edits:#?}"); + + // And off again: the hook goes back to declining. + session.notify(DidChangeConfiguration::METHOD, format_on_save(false)); + assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "turned back off"); + } + + #[test] + fn toggling_format_on_save_neither_rescans_nor_bumps_the_generation() { + // QA (2026-08-26): `lucisv.formatOnSave` is read afresh by every save, + // like `indent`/`lineLength` already are by every format — it must not + // cost a re-walk of the workspace, and (since a rescan is what bumps + // it) must not move the generation counter a pull-diagnostics client's + // `resultId` is stamped with either. `only_an_exclude_change_asks_for_a_rescan` + // (state.rs) pins the same thing one layer down; this pins it through + // the real notification handler. + let tree = Tree::new("willsavenoreindex"); + tree.package("kept.sv", "kept_pkg"); + let mut session = Session::new(vec![tree.path.clone()], false); + let before = session.server.generation; + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + assert_eq!(session.server.generation, before, "turning it on moved nothing"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(false)); + assert_eq!(session.server.generation, before, "turning it off moved nothing either"); + } + + #[test] + fn the_save_hook_answers_exactly_what_the_formatting_request_answers() { + // The whole contract: this is `textDocument/formatting` with a + // different trigger, so the bytes must be identical — not merely + // equivalent. + let tree = Tree::new("willsavesame"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = + session.open(&tree.path.join("m.sv"), "module m;\nwire a;\n wire b;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + assert_eq!(will_save(&mut session, &uri, 1), formatting_result(&mut session, &uri)); + } + + #[test] + fn every_save_reason_is_a_save() { + // Manual, after-delay and focus-out all format: the user asked for + // their saves to be formatted, and all three write the file. + let tree = Tree::new("willsavereason"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + for reason in [1, 2, 3] { + let edits = will_save(&mut session, &uri, reason); + assert_eq!( + edits[0]["newText"], "module m;\n wire a;\nendmodule\n", + "reason {reason}: {edits:#?}" + ); + } + } + + #[test] + fn the_save_hook_answers_null_for_a_buffer_it_does_not_hold() { + // The request carries no text — the client has not written yet — so a + // buffer the server never saw is one it cannot format. + let tree = Tree::new("willsaveclosed"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + assert_eq!(will_save(&mut session, &uri, 1), Value::Null); + assert!(session.shown().is_empty(), "and nothing is said about it"); + } + + #[test] + fn an_already_formatted_buffer_is_saved_with_no_edits() { + // The same `[]` the formatting request gives for `Ok(None)`: an edit + // that changes nothing still moves the cursor in some editors. + let tree = Tree::new("willsaveclean"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let edits = will_save(&mut session, &uri, 1); + assert_eq!(edits, serde_json::json!([]), "{edits:#?}"); + assert_eq!(edits, formatting_result(&mut session, &uri), "the same as the request's"); + } + + #[test] + fn a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown() { + // CLAUDE.md invariant #1 on the save path: no partial output, ever. + // The message repeats per save on purpose — a save the user asked to + // be formatted, that was not, is worth saying every time it happens. + let tree = Tree::new("willsavebroken"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let _ = session.drain(); + + for save in 1..=2 { + let edits = will_save(&mut session, &uri, 1); + assert_eq!(edits, serde_json::json!([]), "save {save}: no edit at all"); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "save {save}: {shown:#?}"); + assert_eq!(shown[0].0, MessageType::ERROR); + assert!(shown[0].1.starts_with("lucisv: cannot format — "), "{}", shown[0].1); + } + } + + #[test] + fn applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do() { + // The formatter's own idempotency, asserted through this path: the + // buffer the client writes is a fixed point, so a save right after a + // save cannot keep rewriting the file. + let tree = Tree::new("willsaveidempotent"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open( + &tree.path.join("m.sv"), + "module m;\nwire a;\n assign a = 1;\nendmodule\n", + ); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + + let edits = will_save(&mut session, &uri, 1); + let formatted = edits[0]["newText"].as_str().expect("newText").to_string(); + // The client applies the edit and writes; the buffer it holds is what + // the next save asks about. + change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }])); + assert_eq!(buffer(&session, &uri), formatted); + assert_eq!(will_save(&mut session, &uri, 1), serde_json::json!([]), "a fixed point"); + } + + /// What `textDocument/formatting` answers for the given `tabSize`. + fn formatting_with_tab_size(session: &mut Session, uri: &Uri, tab_size: u32) -> Value { + session.result( + Formatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "options": { "tabSize": tab_size, "insertSpaces": true }, + }), + ) + } + + #[test] + fn the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent() { + // QA (2026-08-26): the documented gap in Assumptions/Handshakes, + // constructed for real. No `lucisv.toml`, no `lucisv.indent` pushed, + // and an editor whose tab size is 4: a manual format honors rung 3 + // (the editor's `tabSize`) and indents 4; the save hook has no rung 3 + // to consult at all and falls straight to the built-in default, 2. + let tree = Tree::new("willsavetabgap"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + + let manual = formatting_with_tab_size(&mut session, &uri, 4); + assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}"); + + let saved = will_save(&mut session, &uri, 1); + assert_eq!(saved[0]["newText"], "module m;\n wire a;\nendmodule\n", "{saved:#?}"); + assert_ne!(manual, saved, "the documented gap is real, not just written down"); + } + + #[test] + fn a_lucisv_toml_erases_the_tab_size_gap() { + // QA (2026-08-26): with a checked-in config, rung 1 outranks both the + // editor's `tabSize` and the built-in default, so the two paths agree + // exactly again — no `lucisv.toml`, and this would be the previous + // test. + let tree = Tree::new("willsavetabgapclosed"); + tree.write("lucisv.toml", "indent = 4\n"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + + // A wildly different editor tab size changes nothing: the config wins. + let manual = formatting_with_tab_size(&mut session, &uri, 8); + let saved = will_save(&mut session, &uri, 1); + assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}"); + assert_eq!(manual, saved, "the config makes the two paths agree exactly"); + } + + #[test] + fn a_broken_config_still_saves_with_defaults_and_warns_once() { + // QA (2026-08-26): the interaction attack-surface 4 calls out — + // `formatOnSave` on, the buffer itself fine, but `lucisv.toml` broken. + // The save must not be sacrificed to a typo in a file the user is not + // even editing: it formats with the built-in defaults, and the + // warning follows the same per-file-change dedup a broken config + // already gets everywhere else, so a save loop cannot turn it into + // spam the way the formatter-refusal ERROR deliberately can. + // + // The buffer is already at the built-in default (2-space indent), so + // neither save produces an edit and — crucially — neither save is + // followed by the client-applies-the-edit `didChange` that would + // itself re-arm the warning (`set_document` clears + // `config_warnings`). That is what isolates the dedup this test is + // actually about from the unrelated re-arming a *changed* buffer gets. + let tree = Tree::new("willsavebrokenconfig"); + tree.write("lucisv.toml", "indent = 4\nbogus = 1\n"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let _ = session.drain(); + + let first = will_save(&mut session, &uri, 1); + assert_eq!(first, serde_json::json!([]), "the buffer needed no edit: {first:#?}"); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "{shown:#?}"); + assert_eq!(shown[0].0, MessageType::WARNING); + assert!(shown[0].1.contains("formatting with default settings"), "{}", shown[0].1); + + // A second save of the same still-broken config, with nothing having + // changed the buffer in between, says nothing new. + let second = will_save(&mut session, &uri, 1); + assert_eq!(second, serde_json::json!([]), "{second:#?}"); + assert!(session.shown().is_empty(), "the warning does not repeat per save"); + } + + #[test] + fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save() { + // QA (2026-08-26) finding, not a fix: `warn_about_config`'s dedup is + // keyed on `set_document`, and `set_document` is exactly what runs + // when the client applies a save hook's edit and the resulting + // `didChange` reaches the server (see + // `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`, + // which does this on purpose to model the real sequence). So "warns + // once" (Assumptions, work log) only holds once the buffer stops + // needing edits — a save that *itself* reformats the buffer re-arms + // the same warning for the very next save, because that save is + // preceded by a `didChange` the dedup treats as a fresh state. Two + // back-to-back saves of a buffer that needs reformatting under a + // broken config warn twice, not once; the third (once the buffer is a + // fixed point and no further `didChange` lands) is finally silent. + // This is consistent with the doc comment on `warn_about_config` + // ("once per change of a file") — it is the *save hook's own* prose + // ("warns once") that does not spell out this edge, and a future + // reader relying on literally one warning per broken config should + // know better. + let tree = Tree::new("willsavebrokenconfigrearm"); + tree.write("lucisv.toml", "indent = 4\nbogus = 1\n"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n"); + session.notify(DidChangeConfiguration::METHOD, format_on_save(true)); + let _ = session.drain(); + + let first = will_save(&mut session, &uri, 1); + let formatted = first[0]["newText"].as_str().expect("newText").to_string(); + assert_eq!(formatted, "module m;\n wire a;\nendmodule\n", "{first:#?}"); + assert_eq!(session.shown().len(), 1, "the first save warns"); + + // The client applies the edit and writes, exactly as + // `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` + // does — this is what re-arms the dedup. + change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }])); + let second = will_save(&mut session, &uri, 1); + assert_eq!(second, serde_json::json!([]), "already formatted: {second:#?}"); + assert_eq!(session.shown().len(), 1, "the second save warns again, not zero times"); + + // No further `didChange` follows a no-op save, so the third finally + // stays quiet — the dedup this test is not disputing. + let third = will_save(&mut session, &uri, 1); + assert_eq!(third, serde_json::json!([])); + assert!(session.shown().is_empty(), "only now does the warning stop repeating"); + } } diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index f00c28f..a1a79b9 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -46,6 +46,13 @@ pub struct ClientSettings { /// Unset means on, which is what the VS Code default declares — see /// `docs/features/inline-templates/README.md`. pub inline_templates: Option, + /// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats + /// the buffer. A plain `bool` rather than an `Option`, because unset and + /// off are the same answer here: an editor with a format-on-save of its + /// own already runs `textDocument/formatting` on save, and a server that + /// also formatted would format twice. See + /// `docs/features/will-save-wait-until/README.md`. + pub format_on_save: bool, } /// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload. @@ -70,6 +77,10 @@ pub fn from_payload(settings: &Value) -> ClientSettings { exclude: strings(lucisv.get("exclude")), filelist: path(lucisv.get("filelist")), inline_templates: flag(lucisv.get("inlineTemplates")), + // Anything that is not `true` leaves the hook declining, wrong-typed + // values included: the safe direction for a setting that rewrites the + // user's buffer on every save is the one that does nothing. + format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false), } } @@ -132,7 +143,8 @@ mod tests { "indent": indent, "exclude": exclude, "filelist": "", - "inlineTemplates": true + "inlineTemplates": true, + "formatOnSave": false } }) } @@ -189,6 +201,20 @@ mod tests { } } + #[test] + fn format_on_save_is_off_until_a_client_asks_for_it() { + assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save); + assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save); + // Absence is off: the hook runs on every save of every buffer, and a + // server that formatted uninvited would fight the editor's own + // format-on-save. + assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence"); + for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] { + let found = settings(json!({ "lucisv": { "formatOnSave": bad } })); + assert!(!found.format_on_save, "formatOnSave {bad} must be ignored"); + } + } + #[test] fn a_populated_payload_is_read_whole() { let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"]))); diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 9c0f099..29f2b19 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -572,6 +572,16 @@ mod tests { }), "widths do not move files" ); + // QA (2026-08-26): `format_on_save` is read afresh by + // `will_save_wait_until` exactly as `indent`/`lineLength` are by + // `formatting` — it must not ask for a rescan either, or every + // `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on + // a client that pulls, bump the diagnostics generation along with + // it). + assert!( + !ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }), + "turning the save hook on does not move files either" + ); assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does"); assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not"); assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does"); diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index f55132a..9d20125 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -721,6 +721,73 @@ fn pushed_settings_reach_the_formatter_and_can_change_mid_session() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn the_save_hook_is_advertised_and_formats_only_when_it_is_asked_to() { + // The one thing a unit test cannot check: that the capability really + // reaches the wire, and that a client's `formatOnSave` push really turns + // the hook on for the requests that follow it. + let dir = temp_dir("willsave"); + let file = dir.join("m.sv"); + std::fs::write(&file, UNINDENTED).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let will_save = |id: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/willSaveWaitUntil","params":{{"textDocument":{{"uri":"{uri}"}},"reason":1}}}}"# + )) + }; + let formatted = "module settings_me;\n wire a;\nendmodule\n"; + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(UNINDENTED).expect("json") + )), + // Nothing pushed: the hook declines, so a client that never opted in + // saves exactly what it was going to save. + will_save(2), + frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"formatOnSave":true}}}}"#), + will_save(3), + // The client applies the edit and writes; the buffer it now holds is + // what the next save asks about. + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string(formatted).expect("json") + )), + will_save(4), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let sync = &initialize["result"]["capabilities"]["textDocumentSync"]; + assert_eq!(sync["willSaveWaitUntil"], true, "the hook is advertised: {sync:#?}"); + assert!(sync.get("willSave").is_none(), "the notification is not: {sync:#?}"); + + let declined = messages.iter().find(|m| m["id"] == 2).expect("a response to the first save"); + assert!(declined["result"].is_null(), "off by default: {declined:#?}"); + assert_eq!(new_text(&messages, 3), formatted, "the push turns it on for the next save"); + let again = messages.iter().find(|m| m["id"] == 4).expect("a response to the third save"); + assert_eq!( + again["result"].as_array().expect("an array of edits").len(), + 0, + "a formatted buffer saves with no edits at all: {again:#?}" + ); + assert!( + !messages.iter().any(|m| m["method"] == "window/showMessage"), + "nothing went wrong, so nothing was said: {messages:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_pushed_exclude_rebuilds_the_index_mid_session() { // The one link a unit test cannot check: that the notification handler diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 451f3e4..d3254e1 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -18,6 +18,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. |---|---|---| | `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed | | `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) | +| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` | | `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | | `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` | | `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README | diff --git a/docs/features/will-save-wait-until/README.md b/docs/features/will-save-wait-until/README.md new file mode 100644 index 0000000..97ed1c6 --- /dev/null +++ b/docs/features/will-save-wait-until/README.md @@ -0,0 +1,388 @@ +# will-save-wait-until + +## Goal + +Serve `textDocument/willSaveWaitUntil`, the protocol's own format-on-save hook: +the client asks the server for edits *before* it writes the file, waits for the +answer, and applies whatever comes back. VS Code users already have +`editor.formatOnSave`, which runs the ordinary `textDocument/formatting` +request — this exists for the editors that have no format-on-save of their own, +and for users who would rather the server owned the decision than their editor +config. Because a capable client sends this on **every** save of every buffer, +and because a server that formats uninvited would fight (and double up on) an +editor that already formats, the hook is gated on a new `lucisv.formatOnSave` +setting that is **off** by default and answers `null` in one comparison. When it +is on, this is `textDocument/formatting` with a different trigger — the same +engine, the same settings, the same all-or-nothing contract (CLAUDE.md +invariant #1) — so a save can never write anything a manual format would not. + +## Assumptions + +- **Off by default, and the decline is cheap.** `lucisv.formatOnSave` unset, + `false`, or wrong-typed all mean off. The handler returns `null` before it + looks at the buffer, the workspace, or a `lucisv.toml`. The safe direction for + a setting that rewrites the user's file on every save is the one that does + nothing, so a value that is not the JSON boolean `true` is dropped exactly as + every other wrong-typed setting in `settings.rs` is. +- **A plain `bool`, not an `Option`.** Every other field of + `ClientSettings` is "no opinion until a client says otherwise" because it has + a rung below it to fall through to. This one does not: unset and off are the + same answer, and there is no `lucisv.toml` key for it (the config file + describes *style*, and whether an editor formats on save is not style — it is + an editor behavior, and it belongs to the person at the editor). +- **Every save reason formats.** `Manual`, `AfterDelay` and `FocusOut` all + write the file, and a user who asked for their saves to be formatted asked + about all three. The `reason` field is decoded and deliberately not read. A + future knob could restrict it; none is built, because no one has asked for one. +- **The text is the buffer the server holds.** The request carries no text — it + arrives *before* `didSave`, and before the client has written — so what gets + formatted is what `didOpen`/`didChange` built. That is the same text every + other request in this server answers from. A buffer the server does not hold + answers `null` rather than reading the file from disk: the file on disk is + precisely the stale copy the save is about to replace. +- **No `tabSize` on this path, and it can differ from a manual format.** The + protocol sends `FormattingOptions` with `textDocument/formatting` and + `rangeFormatting`; it sends nothing of the sort with `willSaveWaitUntil`. So + the settings ladder in `format::settings_for` runs with rung 3 missing — + `lucisv.toml` > `lucisv.indent` > the built-in 2 — exactly as it already does + for a lint fix's indent (`format::indent_width`). **Honest consequence:** a + user with no `lucisv.toml` and no `lucisv.indent`, whose editor tab size is 4, + gets 4-space indent from a manual format and 2-space indent from a save. That + is a gap in the protocol, not a bug we can close from here — the request + simply does not carry the number — and the fix a user has is to say what they + want once, in a `lucisv.toml` or in `lucisv.indent`. It is written down in + `editors/vscode/package.json`'s setting description and in + `editors/nvim/README.md` so nobody has to discover it by diffing a save. +- **A formatter refusal is shown on every save, on purpose.** `edits()` is + reused unchanged, so an unparsable buffer produces no edit and one ERROR + message — per save, not once per file change. The alternative (dedup, the way + `warn_about_config` dedups a broken `lucisv.toml`) was rejected: that warning + is about a *config file* the user is not editing, while this is about the save + the user just performed. A save the user asked to be formatted, that was not + formatted, is worth saying every time it happens; going quiet would leave the + user believing their file was formatted when it was not. The repetition is + bounded by the user's own saves, and the broken-config warning keeps its + dedup — though QA sharpened what that dedup actually is (see the QA log): + it is cleared by `set_document`, so a save whose own edit comes back + through `didChange` re-arms it for the *next* save. Once per buffer + state, not once per broken config; still bounded by the user's saves + either way. +- **The capability is advertised unconditionally**, even though the default + answers `null`. It has to be: the setting can be pushed mid-session, and + `initialize` is the only time the sync options are sent. A client whose user + never turns it on pays one round trip per save for a `null`. +- **`willSave` (the notification) stays unadvertised.** It carries no reply, so + there is nothing this server could do with it that `didSave` does not already + cover. + +## Handshakes + +- **Consumes `format::settings_for` / `format::formatting`** — the same two + calls `Server::formatting` makes, in the same order, so the two paths cannot + drift. Added one function to `format.rs`, + `settings_without_editor_options(doc, client)`, which is `settings_for` with + a `FormattingOptions` that opts out of rung 3 (hard tabs, zero width — values + `config_from` already refuses). It is the options-less sibling of + `indent_width`, and it lives in `format.rs` so the reasoning about the + precedence ladder stays in one file. +- **Consumes `Server::edits`** unchanged — the all-or-nothing reply shape, and + the ERROR message on a refusal. `Ok(None)` becomes `[]`, matching what + `textDocument/formatting` answers for an already-formatted buffer; a test + asserts the two are byte-identical rather than merely equivalent. +- **Consumes `Server::warn_about_config`** unchanged — a broken `lucisv.toml` + is reported once per buffer state (the dedup is cleared by `set_document`; + see the Assumptions bullet and the QA log for the exact bound), which keeps + a save loop that changes nothing from repeating it. +- **Adds one field to `settings::ClientSettings`** (`format_on_save: bool`, + from `lucisv.formatOnSave`). `Workspace::set_client_settings` needed no + change: the field moves no files, so it does not ask for a reindex, and it is + read afresh by each save exactly as `indent`/`lineLength` are read afresh by + each format. +- **Changes what the client is told at `initialize`:** + `text_document_sync.will_save_wait_until` moves from `None` to `Some(true)`. + Nothing else in the sync options moves — `will_save` stays `None`, + `change: INCREMENTAL` and `save.includeText: false` are untouched — so no + client's sync or save behavior changes beyond gaining one request it may now + send. +- **Editor packaging:** `lucisv.formatOnSave` declared in + `editors/vscode/package.json` (default `false`); no `extension.js` change was + needed, because the client already pushes the whole `lucisv` section + (`synchronize.configurationSection: 'lucisv'`) and `vscode-languageclient` + registers the will-save feature from the advertised capability on its own. + `editors/nvim/README.md` documents the setting next to the `BufWritePre` + autocmd it is an alternative to, including the tab-settings caveat above. +- **No other crate is touched, and no new dependency.** + +## Status / TODO + +- [x] Advertise `will_save_wait_until: Some(true)`; leave `will_save` `None`. +- [x] `lucisv.formatOnSave` in `settings.rs`, default off, wrong types dropped. +- [x] `WillSaveWaitUntil` arm in the request dispatch + `will_save_wait_until` + handler: off → `null`, unopened → `null`, on → the formatting path. +- [x] `format::settings_without_editor_options` — the ladder with no `tabSize` + rung. +- [x] Reuse `edits()` and `warn_about_config()` unchanged. +- [x] Settings unit tests (present true/false, absent, wrong types, the + default VS Code payload). +- [x] `format.rs` unit test for the options-less ladder. +- [x] Server-level tests: off → `null` and silent; on → the edit; identical to + what `textDocument/formatting` answers; every save reason; unopened + buffer; already-formatted buffer → `[]`; unparsable buffer → no edits + + one ERROR per save; setting toggled on and off mid-session. +- [x] Idempotency guard: apply the edit, ask again, get no edits. +- [x] e2e: the capability on the wire, the push, the edit, the second save. +- [x] `editors/vscode/package.json` + `editors/nvim/README.md`. +- [x] `docs/features/lucisv-server/README.md` capability table. +- [x] TODO.md §9b item checked off. + +## Work log + +**2026-08-26 — dev.** Implemented in one round; no deviations from the plan. + +- **`main.rs`**: one field of the existing `TextDocumentSyncOptions` moved, + `will_save_wait_until: None` → `Some(true)`, with the reasoning in a comment + next to it. New test `the_sync_options_ask_for_the_save_hook_and_not_the_ + notification` pins both that and `will_save: None`, since "advertise exactly + what we implement" is the rule that block already lives by. +- **`settings.rs`**: `format_on_save: bool`, parsed with the existing `flag()` + helper plus `.unwrap_or(false)`. Chose `bool` over `Option` + deliberately — see Assumptions; the type says "unset is off", which is the + actual semantics, and it keeps every reader from writing + `.unwrap_or(false)` at the use site. The `vscode_payload` test helper gained + `"formatOnSave": false` so it stays the real shape of what the extension + pushes, and `the_default_vscode_payload_is_no_opinion_about_anything` still + passes unchanged (the default *is* the `Default` value). +- **`format.rs`**: `settings_without_editor_options`. The alternative — + calling `settings_for` with `FormattingOptions::default()` from the handler — + works (its `insert_spaces: false` makes rung 3 inert), but it makes + server.rs depend on a default value being inert somewhere else. A named + function with the reasoning attached costs three lines and makes the + precedence decision greppable from the module that owns precedence. +- **`server.rs`**: one dispatch arm and one handler. The handler is five + statements and reads top to bottom: setting → buffer → settings → format → + warn → `edits()`. The setting check comes *first*, before the workspace + lookup, because the decline is the hot path — this arrives on every save. +- **The error-on-every-save decision** was the one real judgement call; it is + argued in Assumptions and pinned by + `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`, + which drives two saves and asserts exactly one ERROR each time. If a user + ever complains, the change is a dedup keyed on (uri, generation) — but + guessing at that now would mean shipping silence for a failed save, which is + the worse failure. +- **Tests: 1 settings unit + 1 format unit + 1 capability unit + 7 + server-level + 1 e2e = 11 new.** The idempotency guard + (`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`) applies + the returned edit through a real `didChange` and asserts the next save has + nothing to do — the formatter's own invariant #2, asserted through this new + path rather than assumed from the engine's suite. The byte-identity test + (`the_save_hook_answers_exactly_what_the_formatting_request_answers`) + compares the two JSON results directly; it is what would catch the two paths + drifting apart. +- Nothing outside `crates/lucisv_server` changed in code. The three + documentation/packaging files touched outside this feature dir + (`TODO.md`, `docs/features/lucisv-server/README.md`, + `editors/vscode/package.json`, `editors/nvim/README.md`) are additions in the + house style; no QA log or Review section anywhere was edited. + +## QA log + +**2026-08-26 — QA.** Re-ran all gates, then attacked the six surfaces the lead +called out plus one I found on my own. No masked-corruption test was needed +(CLAUDE.md invariant #4): this feature touches nothing in `verify.rs` and adds +no new normalization to it. **Verdict: committable as-is.** Five findings +below, none blocking — one small fix made directly (pre-authorized), four are +new regression tests that now guard behavior the dev's suite did not exercise, +plus one real documentation gap for the dev to word better (not a code fix). + +**Gates, re-run clean:** +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets --workspace` — clean, no warnings. +- `cargo test --workspace` — all green (643 in the `lucisv_server` unit binary + after my additions, up from the dev's 638; every other crate unchanged and + green). +- `cargo test -p vlog_formatter` — 114 passed. +- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` — + `smoke: OK`. + +**A. Hard invariants ride through the new path — verified clean.** +- (a) No partial output on a refusal: structural, not just tested — + `format::formatting` (`format.rs:83-89`) uses `?` on `format_source`'s + `Result` before it ever constructs a `TextEdit`, so an `Err` cannot reach an + edit. `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown` + (`server.rs`) confirms it end to end: `[]` plus one ERROR, twice. +- (b) The runtime safety net runs inside this path: read the call chain — + `Server::will_save_wait_until` → `format::formatting` (`format.rs:83`) → + `vlog_formatter::format_source` (`crates/vlog_formatter/src/format.rs:80`), + which calls `verify_equivalence` then reformats and calls + `verify_convergence` before returning `Ok`. This is the exact same call + `Server::formatting` makes (`server.rs:410` vs `server.rs:463`) — same + function, same arguments shape, no bypass. +- (c) The idempotency guard is real, not string arithmetic: + `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` sends a + genuine `textDocument/didChange` notification through + `Session::notify`/`Server::notification` (the real dispatch), which lands in + `set_document` (`server.rs:816`) exactly as an editor's own edit would, and + then re-asks `willSaveWaitUntil` against the workspace's own copy of the + buffer. Confirmed by reading `change()`/`buffer()` (`server.rs:1821-1834`) — + they are the same helpers the pre-existing incremental-sync suite uses. + +**B2. Byte-identity and the tab-size asymmetry — verified clean, gap +confirmed real by test, not just documented.** Added two tests to +`server.rs` (`the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`, +`a_lucisv_toml_erases_the_tab_size_gap`) that construct exactly the case the +README's Assumptions section describes: no `lucisv.toml`, no +`lucisv.indent`, editor `tabSize: 4` — manual format indents 4 +(`config_from`'s rung 3), the save hook indents 2 (the built-in default, +since `settings_without_editor_options` sends `insert_spaces: false`, which +short-circuits rung 3's `options.insert_spaces && INDENT_RANGE.contains(...)` +check in `format.rs:162` regardless of the tab size carried). With a +`lucisv.toml { indent = 4 }` present, the two paths land on byte-identical +JSON even when the manual request's `tabSize` is 8 — rung 1 outranks both. +This matches the README exactly; nothing to fix. + +**B3. Setting plumbing — verified clean, plus one gap closed.** +- `vscode_payload`'s shape matches `extension.js`'s actual + `synchronize: { configurationSection: 'lucisv' }` (`editors/vscode/extension.js:68`, + unmodified by this diff) and `DidChangeConfigurationParams::settings`'s + unwrap in `server.rs`'s notification handler — traced, matches. +- Mid-session toggle both directions: `the_save_hook_declines_until_format_on_save_is_pushed` + covers on then off. Wrong types (`"true"`, `1`, `null`, `[true]`, + `{"on": true}`) → off, no panic: `format_on_save_is_off_until_a_client_asks_for_it` + (`settings.rs`) — ran clean. +- Reindex / generation: `set_client_settings` (`state.rs:163-168`) computes + its rescan bool from `exclude`/`filelist` equality only, so a `format_on_save` + change can never trigger it — verified by reading the code, but the dev's + own `only_an_exclude_change_asks_for_a_rescan` test (`state.rs`) predates + this field and so never actually exercised it (it builds + `ClientSettings { line_length, indent, ..Default::default() }`, which + defaults `format_on_save` to `false` either way — a no-op assertion for this + field). **Finding (low severity, fixed directly):** extended that test with + an explicit `ClientSettings { format_on_save: true, ..Default::default() }` + case (`state.rs`). Also added + `toggling_format_on_save_neither_rescans_nor_bumps_the_generation` + (`server.rs`) at the session level, asserting `session.server.generation` + is unmoved by a `formatOnSave` push in either direction — this is what + would catch it bumping a pull-diagnostics client's `resultId` for free. + All new assertions pass against the dev's code unchanged; this was a test + gap, not a behavior bug. + +**B4. Error-spam decision — verified clean, plus one real finding on the +"warns once" framing.** +- Two saves of an unparsable buffer → exactly two ERRORs: already covered by + the dev's `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`. + Confirmed passing, no changes needed. +- formatOnSave on + buffer fine + broken config → formats with defaults, + warns once: added `a_broken_config_still_saves_with_defaults_and_warns_once` + (`server.rs`). Had to build it carefully — see the finding below. +- **Finding (moderate, not fixed — needs a documentation call from the dev, + not a code change).** "Warns once" (Assumptions, work log) is **not** + once-per-broken-config; it is once-per-buffer-state. + `warn_about_config`'s dedup (`config_warnings: HashSet`) is cleared by + `set_document` (`server.rs:816-817`, doc comment: "re-arming its + `lucisv.toml` warning"), and `set_document` is exactly what runs when the + client applies a save hook's returned edit and the resulting `didChange` + reaches the server — the same sequence + `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` already + models on purpose. So: a save that itself needs reformatting under a + broken config warns on save 1, and warns **again** on save 2 (because the + intervening apply-and-write re-armed the dedup), and only goes quiet from + save 3 onward once the buffer stops changing. Proved by a new test, + `a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save` + (`server.rs`) — three saves, shown-counts 1, 1, 0. This is consistent with + `warn_about_config`'s own doc comment ("once per change of a file"), so it + is not a bug against that contract; it is the save-hook feature's own + Assumptions prose ("warns once") reading as a stronger guarantee than the + mechanism actually gives. Left to the dev to reword — a single edit to the + Assumptions bullet, not a behavior change, and QA does not redesign. +- Interaction case is otherwise as documented: single-edit-free saves (the + buffer already at the fallback default) stay deduped indefinitely, which is + the common case a per-save-loop actually cares about. + +**B5. Capability shape on the wire — verified clean, no strengthening +needed.** The new e2e test pins `willSaveWaitUntil: true` and `willSave` +absent (`sync.get("willSave").is_none()` — checked against the JSON, not a +Rust `Option`, so this really is "key missing" and not "key present as +`null`" — confirmed against `lsp-types`' `#[serde(skip_serializing_if = +"Option::is_none")]` on both fields). `change: 2` / `openClose: true` / +`save.includeText: false` are **not** re-pinned in the new test, but they +already are, unmodified, by the pre-existing +`incremental_changes_land_the_same_buffer_as_one_full_change`-adjacent e2e +test (`crates/lucisv_server/tests/e2e.rs:2805-2808`) against the same +`initialize` response shape — the two tests together pin the complete set +this attack surface asks for. Nothing to strengthen. + +**B6. CLAUDE.md compliance — verified clean.** +- No `unwrap()`/`expect()`/`panic!()` outside `#[cfg(test)]` in any of + `format.rs`, `main.rs`, `server.rs`, `settings.rs` — checked by line number, + every hit is inside a `mod tests` block. +- Doc comments present on `settings_without_editor_options` (`format.rs:63-71`) + and the `format_on_save` field (`settings.rs:47-53`) — both explain why, not + just what. +- `grep -c '^## ' docs/features/will-save-wait-until/README.md` → 7 matches, + one per section (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA + log, Review — "Status / TODO" and each of the six headers count once each); + no duplicates. +- `TODO.md`'s §9b item text is untouched — only the checkbox flipped and an + indented `→ ...` continuation appended, the same pattern every other + checked-off item in that file already uses. +- `editors/vscode/package.json`'s new entry sits between `inlineTemplates` and + `lineLength`, matching the file's feature-introduction ordering (not + alphabetical — confirmed against the surrounding keys); `editors/nvim/README.md`'s + new section matches the surrounding prose voice. + +**C. Pre-authorized small fix — done.** Checked `main.rs`'s `capabilities()` +against `editors/nvim/README.md:101-102`'s claim ("Not advertised by the +server ... range formatting, completion, rename, signature help, and +cross-file references"): false for all four named capabilities — +`document_range_formatting_provider`, `completion_provider`, `rename_provider`, +and `signature_help_provider` are all `Some(...)` in `capabilities()` +(`main.rs`, unchanged by this feature). Fixed the two lines to state that all +four are advertised and Neovim's built-in client wires them up with no extra +config, dropping the stale "your client will correctly refuse them" claim. +Left `cross-file references` out of the corrected line — it was never a +capability separate from `references_provider` (which *is* advertised); the +real limitation is the in-file-only scope already stated two lines above +(line 96), so restating it here as "not advertised" would have been wrong in +a different way. + +**D. Beyond the list — nothing further broken.** Checked and found clean, +no test added (already structurally impossible or already covered): +`TextDocumentSaveReason` is `#[serde(transparent)]` around a bare `i32` +(`lsp-types-0.97.0`), so an out-of-range `reason` (not 1/2/3) still decodes +without error — consistent with "decoded, deliberately unread," no panic +risk. `will_save_wait_until`'s dispatch arm decodes params before checking +the setting, same as every other request — not a new cost surface. Verified +`editors/vscode/package.json` is syntactically valid JSON after the edit. + +**Tests added this round (7, all passing):** +`server.rs`: `the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`, +`a_lucisv_toml_erases_the_tab_size_gap`, +`a_broken_config_still_saves_with_defaults_and_warns_once`, +`a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`, +`toggling_format_on_save_neither_rescans_nor_bumps_the_generation`. +`state.rs`: one case added inside `only_an_exclude_change_asks_for_a_rescan`. +`editors/nvim/README.md:101-102`: one-line-pair fix (not a test). + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. The design holds the line where it matters: the new door into the +formatter goes through the same `format::formatting` call — and so through +the runtime safety net — as the manual request, with the all-or-nothing +`edits()` contract unchanged; QA traced the chain to `format_source`'s +verification and I confirm the reading. Default-off was the right call +(a save hook that formats uninvited fights the editor's own +format-on-save), and `settings_without_editor_options` keeping the +precedence reasoning inside `format.rs` is the correct home for it. + +On QA's finding (the config warning's dedup is per buffer *state*, not +per broken config — a reformatting save re-arms it): accepted, and I have +reworded the Assumptions bullet to say exactly what QA proved; the +pinning test stays. The behavior itself is acceptable — the warning is +still bounded by the user's own saves, and a user who both breaks their +lucisv.toml and saves in a loop is being told something true each time. +The error-on-every-save decision for refusals stands as argued. QA's +tab-size-gap tests turned the README's honesty into executable fact, +which is the standard here. Accepted as shipped. diff --git a/editors/nvim/README.md b/editors/nvim/README.md index d3de3db..c5a6e4e 100644 --- a/editors/nvim/README.md +++ b/editors/nvim/README.md @@ -98,8 +98,9 @@ including `` `define`` expansion), `vim.lsp.buf.format()`, document and workspace symbols, diagnostics as you type, and semantic tokens — Neovim applies those on top of its treesitter/syntax highlighting with no extra setup. -Not advertised by the server, so your client will correctly refuse them: range -formatting, completion, rename, signature help, and cross-file references. +Range formatting, completion, rename and signature help are advertised too — +Neovim's built-in client wires all four up with no extra config, same as +everything above. **Inline completion (ghost text) needs a client that speaks it.** The server advertises `inlineCompletionProvider` — grey `) begin … end` after an `if (`, @@ -120,7 +121,8 @@ Two behaviors worth knowing before you file a bug: editor default is not a deliberate override), and without a config your editor's tab size governs the indent. -Format on save, if you want it: +Format on save, if you want it — one `autocmd`, and your client stays in +charge of when it runs: ```lua vim.api.nvim_create_autocmd('BufWritePre', { @@ -129,6 +131,28 @@ vim.api.nvim_create_autocmd('BufWritePre', { }) ``` +Or let the server do it, for a client that speaks +`textDocument/willSaveWaitUntil` — it asks before every write and applies what +comes back: + +```lua +vim.lsp.config('lucisv', { + cmd = { 'lucisv-server' }, + filetypes = { 'verilog', 'systemverilog' }, + root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' }, + settings = { lucisv = { formatOnSave = true } }, +}) +``` + +Pick one, not both. `lucisv.formatOnSave` is **off** unless you set it: the +server answers the save hook with "no edits" until you ask, so an editor that +already formats on save does not format twice. One difference from the +`autocmd` above is worth knowing: `willSaveWaitUntil` carries no tab settings, +so the indent comes from the project's `lucisv.toml`, then `lucisv.indent`, +then the built-in 2 — your `shiftwidth` is not consulted on this path even +though `vim.lsp.buf.format()` sends it. Set `lucisv.indent` if the two need to +agree. + ## Checking it works ``` diff --git a/editors/vscode/package.json b/editors/vscode/package.json index c366130..31ac741 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -168,6 +168,11 @@ "default": true, "markdownDescription": "Show grey ghost text that finishes a block as you open it: `if (` suggests `) begin … end`, a `case (` suggests its arms and `endcase`, and a `begin`, `fork`, `generate` or `module` at the end of a line suggests its closer. Tab accepts it as a snippet, so the cursor lands in the condition first and in the body second; where more than one shape fits (`always @(`), `Alt+]` cycles them. The accepted text is indented with the editor's own `editor.tabSize`/`editor.insertSpaces`, not with `#lucisv.indent#`. Requires `editor.inlineSuggest.enabled`." }, + "lucisv.formatOnSave": { + "type": "boolean", + "default": false, + "markdownDescription": "Let the server format the file when you save it, over `textDocument/willSaveWaitUntil`. Off by default, and **not** what a VS Code user wants: `#editor.formatOnSave#` already formats through lucisv and turning both on formats twice. This exists for the editors that have no format-on-save of their own. The indent comes from the project's `lucisv.toml`, then `#lucisv.indent#`, then the built-in 2 — never from `#editor.tabSize#`, which the protocol does not send with this request." + }, "lucisv.lineLength": { "type": [ "number",