Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dbd2f176aa | ||
|
|
6523c604bb | ||
|
|
e165c37a3a | ||
|
|
00c03eccf9 | ||
|
|
80b9afdfe3 | ||
|
|
c2ea1a11f6 |
No files matched your search
@@ -4,6 +4,57 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.9.0 — 2026-08-26
|
||||
|
||||
The performance-model release: TODO.md §9b, the high-value half of the
|
||||
LSP 3.18 audit, shipped one feature per dev/QA/review round.
|
||||
|
||||
### Incremental text sync
|
||||
|
||||
A keystroke now costs one range on the wire, not the whole file. Edits
|
||||
are applied by one pure function with clamping rules inherited from the
|
||||
existing position converter — a backwards range becomes a pure
|
||||
insertion, the only reading that cannot lose text — cross-checked
|
||||
against an independent reference model over 400 randomized edit
|
||||
sequences. One notification is still one reparse, one diagnostics
|
||||
generation, one publish.
|
||||
|
||||
### Format on save (willSaveWaitUntil)
|
||||
|
||||
The protocol's native format-on-save hook, for editors without one of
|
||||
their own. Off by default (`lucisv.formatOnSave`) so it never fights an
|
||||
editor that already formats on save; when on, it is the formatting
|
||||
request with a different trigger — same engine, same verified-output,
|
||||
all-or-nothing contract. The one protocol gap (no editor tab size on
|
||||
this path) is documented rather than papered over.
|
||||
|
||||
### Semantic tokens: range and delta
|
||||
|
||||
`semanticTokens/range` answers just the lines the editor is showing;
|
||||
`full/delta` answers edits against the previous result instead of the
|
||||
whole token set. One tokenizer and one pure encoder serve full, range
|
||||
and delta, proven byte-identical to the old encoder over a 41k-token
|
||||
corpus file; the delta's single-edit diff carries the classic
|
||||
prefix/suffix overlap trap, deliberately broken twice (dev and QA,
|
||||
independently) to prove the suite catches it.
|
||||
|
||||
### A progress bar on indexing
|
||||
|
||||
Every workspace rescan — the startup build included — now shows a real
|
||||
progress bar in clients that support one: what is being indexed, no
|
||||
invented percentages, and an honest file count when it comes down.
|
||||
|
||||
### $/cancelRequest
|
||||
|
||||
The server reads its backlog in bursts and answers a request whose
|
||||
cancel arrived alongside it with RequestCancelled instead of computing
|
||||
it — completion requests a fast typist already outran no longer cost a
|
||||
parse each. Cancellation is stateless by construction: a cancel matters
|
||||
only next to its own request, everything else is dropped on sight, and
|
||||
no cancel can talk the server out of a shutdown. Enabled by the
|
||||
server's first thread — a 12-line forwarder that makes the client's
|
||||
backlog observable at all through lsp-server's rendezvous channels.
|
||||
|
||||
## 0.8.0 — 2026-08-26
|
||||
|
||||
The protocol-compliance release: the server was audited line-by-line
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -687,23 +687,92 @@ and are not gaps.
|
||||
|
||||
### 9b. High-value, next rounds
|
||||
|
||||
- [ ] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`).
|
||||
- [x] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`).
|
||||
Full-buffer sync on every keystroke scales poorly; apply
|
||||
range-scoped `contentChanges` in order, with a full-text fallback on
|
||||
any malformed change. Touches `set_document` and the staleness model
|
||||
in `docs/features/lucisv-server/README.md`.
|
||||
- [ ] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
→ `docs/features/incremental-sync/README.md`
|
||||
(`crates/lucisv_server/src/sync.rs`); one pure
|
||||
`apply_changes(text, changes) -> String` over `convert::Positions`, a
|
||||
fresh line table per change so each range sees the previous one's
|
||||
result, rangeless changes still replacing the whole buffer, and every
|
||||
desynced position clamped (line past EOF, character past line end,
|
||||
surrogate half rounds forward, `start > end` becomes an insertion).
|
||||
Still one `set_document` — one reparse, one generation bump, one
|
||||
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.
|
||||
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
format-on-save hook (client-side `editor.formatOnSave` already works;
|
||||
this serves the editors without it).
|
||||
- [ ] **Semantic tokens `range` + `full/delta`** — we set
|
||||
→ `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`.
|
||||
- [x] **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.
|
||||
- [ ] **Work-done progress** — `reindex()` is a synchronous full
|
||||
→ `docs/features/semantic-tokens-delta/README.md`; `tokens.rs` split
|
||||
into classification → absolute form → filter → one pure encoder, so
|
||||
all three requests share a tokenizer. `range: Some(true)` answers the
|
||||
overlapping tokens whole, **re-encoded from the start of the
|
||||
document** (a range answer is self-contained, not a slice), carries
|
||||
no `resultId` and is not what a later delta diffs against; an empty
|
||||
range answers nothing. `full: Delta { delta: true }` answers one
|
||||
`SemanticTokensEdit` replacing everything between the common prefix
|
||||
and the common suffix — **the suffix capped to what the prefix left**,
|
||||
because identical lines of Verilog encode identically and an uncapped
|
||||
suffix claims the same tokens twice. `resultId`s are minted per
|
||||
answer, stored by `full` and `full/delta` alike, dropped on
|
||||
`didClose`; an id the server does not hold is answered in full. No
|
||||
token request bumps the diagnostics generation. Not done:
|
||||
`workspace/semanticTokens/refresh`.
|
||||
- [x] **Work-done progress** — `reindex()` is a synchronous full
|
||||
rescan on every save with no `window/workDoneProgress` reporting;
|
||||
on a big filelist the server just goes quiet.
|
||||
- [ ] **`$/cancelRequest`** — the loop handles requests sequentially
|
||||
→ `docs/features/work-done-progress/README.md`; every workspace
|
||||
rescan — the startup build, a save, a watched file, a changed
|
||||
`lucisv.exclude`/`filelist` — is wrapped in one
|
||||
`window/workDoneProgress/create` plus a `$/progress` begin/end pair
|
||||
on a fresh `lucisv-index-N` token, gated on the client's
|
||||
`window.workDoneProgress` (a client that did not ask is sent nothing
|
||||
at all, as the spec requires). `begin` goes out without waiting for
|
||||
the create's answer, because the rescan blocks the loop the moment
|
||||
it returns; the create's answer is ignored on the same path the
|
||||
watcher registrations' is. No percentage and no intermediate report
|
||||
— the rescan is one opaque call — and the `end` names the indexed
|
||||
file count, read off the index's own file list. The bar covers the
|
||||
scan, ending before the scope warnings and the republishes.
|
||||
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
|
||||
and ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.
|
||||
→ `docs/features/cancel-request/README.md`; **completes §9b.** `run()`
|
||||
now reads in bursts — one blocking receive, then everything already
|
||||
queued behind it — and handles the burst **in arrival order**, so a
|
||||
`didChange` ahead of a request is still applied before that request is
|
||||
answered. A request the same burst also carries a cancel for is
|
||||
answered `RequestCancelled` (-32800) without being dispatched; the
|
||||
cancels themselves are consumed there and never reach
|
||||
`notification()`. A cancel naming no request in its burst is dropped
|
||||
on the spot — it refers to a request already answered, or to one that
|
||||
never arrived — so the feature holds no state between bursts, and a
|
||||
double cancel is harmless. `shutdown` is honoured before the cancelled
|
||||
set is consulted and so is never cancellable. Numeric and string ids
|
||||
both read; malformed cancels dropped. The design's one correction:
|
||||
`lsp-server` 0.10 wires its stdio transport with `bounded(0)`
|
||||
*rendezvous* channels, so a backlog never sits on
|
||||
`connection.receiver` at all — the loop forwards messages onto an
|
||||
unbounded `std::sync::mpsc` queue of its own on one small thread
|
||||
(std-only, no new dependency), which stops at `shutdown` so
|
||||
`handle_shutdown` still reads the `exit` that follows. Nothing already
|
||||
running is cancelled; that needs the worker pool §6 defers.
|
||||
|
||||
### 9c. Moderate value, Verilog-shaped
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -32,6 +32,7 @@ mod settings;
|
||||
mod signature;
|
||||
mod state;
|
||||
mod symbols;
|
||||
mod sync;
|
||||
mod templates;
|
||||
mod tokens;
|
||||
mod uri;
|
||||
@@ -45,11 +46,11 @@ use lsp_types::{
|
||||
CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability,
|
||||
CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, DocumentLinkOptions,
|
||||
ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions,
|
||||
InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, SaveOptions,
|
||||
SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensLegend,
|
||||
SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities,
|
||||
SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
WorkDoneProgressOptions,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, WorkDoneProgressOptions,
|
||||
};
|
||||
|
||||
use crate::server::{ClientAbilities, Server};
|
||||
@@ -68,6 +69,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
file_watching: watch::dynamic_registration(¶ms),
|
||||
apply_edit: apply_edit_support(¶ms),
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
|
||||
|
||||
@@ -84,7 +86,28 @@ fn capabilities() -> ServerCapabilities {
|
||||
// The protocol default, and what the conversion in `convert.rs`
|
||||
// implements. Stated rather than left implicit.
|
||||
position_encoding: Some(PositionEncodingKind::UTF16),
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
|
||||
// Incremental sync: a keystroke costs one range, not the whole file.
|
||||
// Spelled out as options rather than a bare kind because a bare kind
|
||||
// says nothing about open/close or save, and clients fill that in
|
||||
// themselves — this states the same defaults a bare kind resolved to,
|
||||
// so nothing but `change` moves. `includeText: false` keeps a save
|
||||
// from re-sending a buffer the server already tracks edit by edit;
|
||||
// the `didSave` handler still honours text if a client sends it.
|
||||
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: Some(true),
|
||||
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
|
||||
include_text: Some(false),
|
||||
})),
|
||||
})),
|
||||
document_formatting_provider: Some(OneOf::Left(true)),
|
||||
document_range_formatting_provider: Some(OneOf::Left(true)),
|
||||
definition_provider: Some(OneOf::Left(true)),
|
||||
@@ -199,8 +222,16 @@ fn capabilities() -> ServerCapabilities {
|
||||
token_types: tokens::token_types(),
|
||||
token_modifiers: tokens::token_modifiers(),
|
||||
},
|
||||
range: None,
|
||||
full: Some(SemanticTokensFullOptions::Bool(true)),
|
||||
// The visible lines, for the first paint of a large file:
|
||||
// the same tokenizer, filtered, and re-encoded from the
|
||||
// start of the document so the answer stands on its own.
|
||||
range: Some(true),
|
||||
// `delta: true` rather than a bare `full: true`, so a client
|
||||
// that has an answer already asks what changed instead of
|
||||
// re-fetching the file's whole token set on every keystroke.
|
||||
// `full` itself stays served — the enum's `Delta` variant is
|
||||
// the full capability plus deltas, not a replacement.
|
||||
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
@@ -263,6 +294,21 @@ fn pull_diagnostics_support(params: &InitializeParams) -> bool {
|
||||
.is_some_and(|text_document| text_document.diagnostic.is_some())
|
||||
}
|
||||
|
||||
/// Whether the client renders server-initiated work-done progress.
|
||||
///
|
||||
/// The spec forbids a server from creating progress at all without this, so a
|
||||
/// client that said nothing is sent no `window/workDoneProgress/create` and no
|
||||
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
|
||||
/// before this was read.
|
||||
fn work_done_progress_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.work_done_progress)
|
||||
.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<PathBuf> {
|
||||
@@ -306,6 +352,31 @@ mod tests {
|
||||
assert!(caps.diagnostic_provider.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
|
||||
// A client keys entirely off this: it sends `full/delta` only where
|
||||
// `full.delta` is `true`, and `range` only where `range` is.
|
||||
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
|
||||
capabilities().semantic_tokens_provider
|
||||
else {
|
||||
panic!("the options form, not a registration");
|
||||
};
|
||||
assert_eq!(options.range, Some(true));
|
||||
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
|
||||
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
|
||||
}
|
||||
|
||||
#[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)) =
|
||||
@@ -335,6 +406,23 @@ mod tests {
|
||||
assert!(!apply_edit_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
|
||||
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |work_done_progress: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(work_done_progress_support(&saying(Some(true))));
|
||||
assert!(!work_done_progress_support(&saying(Some(false))));
|
||||
assert!(!work_done_progress_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
|
||||
use lsp_types::{
|
||||
|
||||
+1981
-45
File diff suppressed because it is too large.
Load diff
@@ -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<bool>,
|
||||
/// `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"])));
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Applying a `didChange`'s edits to a buffer.
|
||||
//!
|
||||
//! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole
|
||||
//! file on every keystroke and sends the ranges it touched instead. The server
|
||||
//! is then the only holder of the buffer's text, so this module is the one
|
||||
//! place a wrong offset silently rewrites what the user is looking at — hence
|
||||
//! a pure function, a second implementation to cross-check it against, and no
|
||||
//! slicing that can panic. The exact clamping rules are in
|
||||
//! `docs/features/incremental-sync/README.md`.
|
||||
|
||||
use lsp_types::TextDocumentContentChangeEvent;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
|
||||
/// Apply one `didChange`'s content changes to a buffer, in the order the
|
||||
/// client sent them, and return the buffer that results.
|
||||
///
|
||||
/// A change with no range replaces the whole document — what a full-sync
|
||||
/// client sends, and what still works if one arrives mid-batch.
|
||||
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
// The whole document. This also resets the state that the ranges
|
||||
// after it in the same batch are positioned against.
|
||||
text.clone_from(&change.text);
|
||||
continue;
|
||||
};
|
||||
// A fresh line table per change: each range is positioned against the
|
||||
// document as the *previous* changes in this batch left it. That is
|
||||
// O(changes × file) per notification, which at Verilog file sizes is
|
||||
// microseconds and buys a function with no incremental state to get
|
||||
// out of step.
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
let start = positions.offset(range.start) as usize;
|
||||
// A range that runs backwards is a client desync. Reading it as an
|
||||
// insertion at `start` is the one interpretation that deletes nothing:
|
||||
// we have no resync mechanism, so the safe direction is to keep text.
|
||||
let end = (positions.offset(range.end) as usize).max(start);
|
||||
let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else {
|
||||
// Unreachable: `Positions::offset` only ever returns character
|
||||
// boundaries. Written as a skip rather than a slice because the
|
||||
// slice would panic, and a panic here takes the buffer with it.
|
||||
continue;
|
||||
};
|
||||
text = format!("{before}{}{after}", change.text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
fn pos(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
/// A ranged change, the way a client sends one.
|
||||
fn edit(
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
text: &str,
|
||||
) -> lsp_types::TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }),
|
||||
range_length: None,
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A rangeless change: the whole buffer, as a full-sync client sends it.
|
||||
fn whole(text: &str) -> TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_lands_where_the_range_is_empty() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]);
|
||||
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_removes_exactly_the_range() {
|
||||
let text = "module m;\n wire aaa;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]);
|
||||
assert_eq!(after, "module m;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replace_swaps_the_range_for_the_text() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]);
|
||||
assert_eq!(after, "module m;\n logic a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_range_collapses_the_lines_it_spans() {
|
||||
let text = "a\nb\nc\n";
|
||||
let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]);
|
||||
assert_eq!(after, "aXc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_changes_see_what_the_earlier_ones_did() {
|
||||
// The batch a real editor sends for "type `wire w;` on a new line",
|
||||
// split into three: each range is against the state after the last.
|
||||
let text = "module m;\nendmodule\n";
|
||||
let after = apply_changes(
|
||||
text,
|
||||
&[
|
||||
edit((1, 0), (1, 0), "\n"), // open a line
|
||||
edit((1, 0), (1, 0), " wire "), // the keyword
|
||||
edit((1, 7), (1, 7), "w;"), // the name
|
||||
],
|
||||
);
|
||||
assert_eq!(after, "module m;\n wire w;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_range_positioned_against_the_original_text_would_be_wrong() {
|
||||
// The regression this whole module exists to prevent: if the line
|
||||
// table were built once, the second range below would land on the old
|
||||
// line 1 and the result would differ.
|
||||
let text = "aaa\nbbb\n";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]);
|
||||
assert_eq!(after, "x\naZa\nbbb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() {
|
||||
let text = "// é ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]);
|
||||
assert_eq!(after, "// é no\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_astral_character_takes_two_units_and_is_never_split() {
|
||||
// `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward
|
||||
// past the whole character, so no edit can ever cut it in half.
|
||||
let text = "// 🎉 ok\n";
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n");
|
||||
// Start inside the pair: the emoji survives, the edit begins after it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n");
|
||||
// End inside the pair: rounds forward, so the emoji goes with it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n");
|
||||
for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] {
|
||||
let out = apply_changes(text, &[change]);
|
||||
assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_after_an_emoji_counts_from_the_right_column() {
|
||||
let text = "// 🎉 wire a;\n";
|
||||
// "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `.
|
||||
let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]);
|
||||
assert_eq!(after, "// 🎉 logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_ends_survive_an_edit_on_the_line() {
|
||||
let text = "module m;\r\n wire a;\r\nendmodule\r\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]);
|
||||
assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_line_can_be_joined_to_the_next() {
|
||||
let text = "ab\r\ncd\r\n";
|
||||
let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]);
|
||||
assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_the_start_of_the_document() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n");
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_end_of_file() {
|
||||
// The empty last line a trailing newline opens.
|
||||
assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() {
|
||||
assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_into_an_empty_document() {
|
||||
assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_replaces_the_whole_document() {
|
||||
assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_of_several_rangeless_changes_wins() {
|
||||
// What the full-sync handler did before this feature, unchanged.
|
||||
assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_resets_what_the_next_range_is_against() {
|
||||
let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]);
|
||||
assert_eq!(after, "abc\ndXf\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_changes_is_the_buffer_unchanged() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_past_the_end_clamps_to_the_end_of_the_document() {
|
||||
let text = "a\nb\n";
|
||||
assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX");
|
||||
// And a range that *starts* in the document and ends past it.
|
||||
assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_past_the_end_of_a_line_clamps_to_its_content() {
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n");
|
||||
assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_runs_backwards_deletes_nothing() {
|
||||
// Clamping `end` up to `start` turns a desynced range into a pure
|
||||
// insertion — the only reading that cannot lose the user's text.
|
||||
assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n");
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized cross-check against a second implementation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// The same rules, implemented a second way: a flat `Vec<char>` with the
|
||||
/// line starts scanned out of it, rather than byte offsets off a
|
||||
/// `LineIndex`. Sharing no code with `apply_changes` is the point.
|
||||
fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
text.clone_from(&change.text);
|
||||
continue;
|
||||
};
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let start = reference_index(&chars, range.start);
|
||||
let end = reference_index(&chars, range.end).max(start);
|
||||
let mut out: String = chars[..start].iter().collect();
|
||||
out.push_str(&change.text);
|
||||
out.extend(chars[end..].iter());
|
||||
text = out;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The index into `chars` that a position names: lines are `\n`-
|
||||
/// terminated, one `\r` before that terminator is not content, a
|
||||
/// character past a line's content clamps to it, a line past the last
|
||||
/// clamps to the end of the text, and a character landing inside a
|
||||
/// surrogate pair rounds forward past the whole character.
|
||||
fn reference_index(chars: &[char], position: Position) -> usize {
|
||||
let mut starts = vec![0usize];
|
||||
for (i, c) in chars.iter().enumerate() {
|
||||
if *c == '\n' {
|
||||
starts.push(i + 1);
|
||||
}
|
||||
}
|
||||
let Some(&start) = starts.get(position.line as usize) else {
|
||||
return chars.len();
|
||||
};
|
||||
// The line's content ends before its `\n`, and before one `\r`.
|
||||
let mut end = match starts.get(position.line as usize + 1) {
|
||||
Some(&next) => next - 1,
|
||||
None => chars.len(),
|
||||
};
|
||||
if end > start && chars[end - 1] == '\r' {
|
||||
end -= 1;
|
||||
}
|
||||
let mut units = 0u32;
|
||||
let mut at = start;
|
||||
while at < end && units < position.character {
|
||||
units += chars[at].len_utf16() as u32;
|
||||
at += 1;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// A random document over an alphabet that mixes every width and both
|
||||
/// line endings — including a bare `\r`, which is an ordinary character.
|
||||
fn random_text(rng: &mut Lcg) -> String {
|
||||
const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"];
|
||||
let len = rng.below(24);
|
||||
(0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect()
|
||||
}
|
||||
|
||||
/// A random change: mostly ranged, occasionally a whole-document reset,
|
||||
/// with positions that are often — but deliberately not always — inside
|
||||
/// the document.
|
||||
fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent {
|
||||
if rng.below(10) == 0 {
|
||||
return whole(&random_text(rng));
|
||||
}
|
||||
let lines = text.matches('\n').count() as u32 + 1;
|
||||
let position = |rng: &mut Lcg| Position {
|
||||
line: rng.below(u64::from(lines) + 2) as u32,
|
||||
character: rng.below(12) as u32,
|
||||
};
|
||||
let (first, second) = (position(rng), position(rng));
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: first, end: second }),
|
||||
range_length: None,
|
||||
text: random_text(rng),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_edit_sequences_agree_with_the_reference_model() {
|
||||
let mut rng = Lcg(0x5EED_1CE5);
|
||||
let mut ranged = 0usize;
|
||||
for case in 0..400 {
|
||||
let text = random_text(&mut rng);
|
||||
let mut changes = Vec::new();
|
||||
let mut running = text.clone();
|
||||
for _ in 0..rng.below(5) + 1 {
|
||||
let change = random_change(&mut rng, &running);
|
||||
ranged += usize::from(change.range.is_some());
|
||||
// The next range is against the state this one leaves.
|
||||
running = apply_changes(&running, std::slice::from_ref(&change));
|
||||
changes.push(change);
|
||||
}
|
||||
let ours = apply_changes(&text, &changes);
|
||||
assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}");
|
||||
assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time");
|
||||
}
|
||||
assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA additions (2026-08-26) — see docs/features/incremental-sync/README.md
|
||||
// QA log for the full writeup of each of these.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() {
|
||||
// Character 4 is the low half of `🎉`'s pair (the emoji starts at 3,
|
||||
// ends at 5). A *start* boundary landing there rounds forward past
|
||||
// the whole character, so the emoji is excluded from — and survives
|
||||
// — a deletion that begins mid-pair.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]);
|
||||
assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() {
|
||||
// Symmetric case: an *end* boundary on the low half also rounds
|
||||
// forward, but here that means the deletion is widened to swallow
|
||||
// the whole character rather than stopping short of it.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]);
|
||||
assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() {
|
||||
// QA finding (docs/features/incremental-sync/README.md QA log,
|
||||
// 2026-08-26): pinning present, *surprising* behavior rather than
|
||||
// asserting it is correct. `convert.rs::line_content_end` treats a
|
||||
// trailing bare `\r` as "not content" whether or not a `\n` will
|
||||
// follow it, so a second change in the same batch that targets "end
|
||||
// of line" after a first change appended a lone `\r` lands *before*
|
||||
// that `\r`, not after it. A client that split one `\r\n` insertion
|
||||
// into two ranged changes this way would get `\n\r`, not `\r\n`. No
|
||||
// real editor's diff algorithm is known to do this, and no panic or
|
||||
// data loss occurs — but if this test's expected string ever needs
|
||||
// to change to `"ab\r\n"`, that is a deliberate fix to
|
||||
// `Positions::offset`/`line_content_end`, not an accidental one.
|
||||
let text = "ab";
|
||||
let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]);
|
||||
assert_eq!(after, "ab\n\r", "known edge case: see the comment above");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_covering_the_final_newline_removes_exactly_it() {
|
||||
let text = "a\nb\n";
|
||||
let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]);
|
||||
assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_width_inserts_at_the_same_position_compose_in_batch_order() {
|
||||
// Not a bug: per protocol, each change is positioned against what the
|
||||
// previous ones in the batch left, so two inserts naming the same
|
||||
// literal position land with the *second* one first — a client that
|
||||
// wants "12" must advance the second insert's position past the
|
||||
// first's text, exactly as it would need to for a non-zero-width
|
||||
// range. Pinned so a future refactor cannot silently change the
|
||||
// batch's ordering semantics.
|
||||
let text = "x";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]);
|
||||
assert_eq!(after, "21x");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
//! `textDocument/semanticTokens/full`.
|
||||
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/lucisv-server/README.md`.
|
||||
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
//!
|
||||
//! One tokenizer and one encoder serve all three requests: classification
|
||||
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
|
||||
//! protocol thinks in), a range answer drops the ones it does not want, and
|
||||
//! `encode` delta-encodes whatever is left from the start of the document.
|
||||
|
||||
use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
@@ -68,12 +76,53 @@ struct Piece {
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
/// One classified token in the protocol's own coordinates: a zero-based line,
|
||||
/// a UTF-16 start column and a UTF-16 length. This is the form the range
|
||||
/// filter works in, and the only input `encode` has.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Absolute {
|
||||
line: u32,
|
||||
start: u32,
|
||||
length: u32,
|
||||
ty: u32,
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
impl Absolute {
|
||||
/// Where this token starts, as the protocol names it.
|
||||
fn from(&self) -> Position {
|
||||
Position { line: self.line, character: self.start }
|
||||
}
|
||||
|
||||
/// Where it ends. A token never spans a line break (see `split_lines`), so
|
||||
/// this is on the same line.
|
||||
fn to(&self) -> Position {
|
||||
Position { line: self.line, character: self.start + self.length }
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify and encode the whole buffer.
|
||||
///
|
||||
/// A buffer that does not lex has no tokens, so this is empty — the user sees
|
||||
/// the editor's own grammar highlighting plus the parse diagnostic, which is
|
||||
/// the honest answer while the file is unlexable.
|
||||
pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
pub fn semantic_tokens(doc: &Document) -> Vec<SemanticToken> {
|
||||
encode(&absolute(doc))
|
||||
}
|
||||
|
||||
/// The tokens a range covers, encoded as a self-contained answer.
|
||||
///
|
||||
/// The protocol asks for a whole `SemanticTokens` here, not a slice of the
|
||||
/// full one: the relative encoding restarts from the start of the document
|
||||
/// exactly as a full answer's does, and only the tokens outside the range are
|
||||
/// missing. A token that merely overlaps the range is kept whole — the client
|
||||
/// asked which tokens to draw, not where to cut them.
|
||||
pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
encode(&within(absolute(doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect_trivia(token, &mut pieces);
|
||||
@@ -85,7 +134,21 @@ pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
});
|
||||
}
|
||||
}
|
||||
encode(pieces, doc)
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
|
||||
/// The tokens overlapping `range`, in the order they came in.
|
||||
///
|
||||
/// Overlap, not containment: a client sends the lines it is showing, and a
|
||||
/// token straddling the first of them is one the user can see. An **empty**
|
||||
/// range covers no characters, so it overlaps nothing — the containment test
|
||||
/// below would otherwise answer with every token the collapsed point sits
|
||||
/// inside.
|
||||
fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
if range.start >= range.end {
|
||||
return Vec::new();
|
||||
}
|
||||
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
|
||||
}
|
||||
|
||||
/// Comments live as trivia on the token that follows (or, for a trailing
|
||||
@@ -162,14 +225,15 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
}
|
||||
}
|
||||
|
||||
/// Split every piece at line boundaries, sort, and delta-encode.
|
||||
/// Split every piece at line boundaries, measure it in UTF-16 units, and
|
||||
/// sort.
|
||||
///
|
||||
/// The spec forbids a token from spanning a line break, and Verilog has three
|
||||
/// shapes that would: a block comment, a continued `` `define`` and a
|
||||
/// multi-line macro invocation.
|
||||
fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
|
||||
let positions = doc.positions();
|
||||
let mut flat: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
|
||||
let mut flat: Vec<Absolute> = Vec::new();
|
||||
for piece in pieces {
|
||||
for line_span in split_lines(&doc.text, piece.span) {
|
||||
let start = positions.position(line_span.start);
|
||||
@@ -177,33 +241,78 @@ fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
if end.character <= start.character {
|
||||
continue;
|
||||
}
|
||||
flat.push((
|
||||
start.line,
|
||||
start.character,
|
||||
end.character - start.character,
|
||||
piece.ty as u32,
|
||||
piece.modifiers,
|
||||
));
|
||||
flat.push(Absolute {
|
||||
line: start.line,
|
||||
start: start.character,
|
||||
length: end.character - start.character,
|
||||
ty: piece.ty as u32,
|
||||
modifiers: piece.modifiers,
|
||||
});
|
||||
}
|
||||
}
|
||||
flat.sort_by_key(|&(line, start, ..)| (line, start));
|
||||
flat.sort_by_key(|t| (t.line, t.start));
|
||||
flat
|
||||
}
|
||||
|
||||
let mut data = Vec::with_capacity(flat.len());
|
||||
/// Delta-encode, from the start of the document.
|
||||
///
|
||||
/// Pure: the same tokens always encode the same way, whether they are the
|
||||
/// whole file's or the handful a range kept.
|
||||
fn encode(tokens: &[Absolute]) -> Vec<SemanticToken> {
|
||||
let mut data = Vec::with_capacity(tokens.len());
|
||||
let (mut prev_line, mut prev_start) = (0u32, 0u32);
|
||||
for (line, start, length, ty, modifiers) in flat {
|
||||
let delta_line = line - prev_line;
|
||||
let delta_start = if delta_line == 0 { start - prev_start } else { start };
|
||||
for token in tokens {
|
||||
let delta_line = token.line - prev_line;
|
||||
let delta_start = if delta_line == 0 { token.start - prev_start } else { token.start };
|
||||
data.push(SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: ty,
|
||||
token_modifiers_bitset: modifiers,
|
||||
length: token.length,
|
||||
token_type: token.ty,
|
||||
token_modifiers_bitset: token.modifiers,
|
||||
});
|
||||
prev_line = line;
|
||||
prev_start = start;
|
||||
prev_line = token.line;
|
||||
prev_start = token.start;
|
||||
}
|
||||
SemanticTokens { result_id: None, data }
|
||||
data
|
||||
}
|
||||
|
||||
/// How many numbers one token is on the wire. An edit's `start` and
|
||||
/// `deleteCount` index that flat array, not the token list.
|
||||
const FIELDS: u32 = 5;
|
||||
|
||||
/// The edits that turn `old` into `new`: one replacement of everything
|
||||
/// between the common prefix and the common suffix, or none at all when the
|
||||
/// two are identical.
|
||||
///
|
||||
/// **Minimality beyond the prefix/suffix trim is deliberately not attempted.**
|
||||
/// A real diff would find the two edits an insertion in the middle of a file
|
||||
/// really is, but every token after an edit carries a changed `deltaLine`
|
||||
/// anyway, so the interesting cases — typing at the end of a line, or on a
|
||||
/// line — trim to almost nothing regardless. rust-analyzer answers the same
|
||||
/// way, and the invariant that matters is that applying the result
|
||||
/// reproduces `new` exactly.
|
||||
pub fn delta(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
|
||||
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
|
||||
// The suffix is counted over what the prefix left, never over the whole
|
||||
// vectors: two token lists that repeat themselves — which identical lines
|
||||
// of Verilog produce exactly — would otherwise claim the same tokens as
|
||||
// both prefix and suffix, and the edit would delete a region it also
|
||||
// re-inserts (or, with the subtraction underflowing, not be computable at
|
||||
// all). This overlap is the classic bug in this algorithm.
|
||||
let (old_rest, new_rest) = (&old[prefix..], &new[prefix..]);
|
||||
let suffix =
|
||||
old_rest.iter().rev().zip(new_rest.iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let deleted = old_rest.len() - suffix;
|
||||
let inserted = &new_rest[..new_rest.len() - suffix];
|
||||
if deleted == 0 && inserted.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![SemanticTokensEdit {
|
||||
start: prefix as u32 * FIELDS,
|
||||
delete_count: deleted as u32 * FIELDS,
|
||||
data: Some(inserted.to_vec()),
|
||||
}]
|
||||
}
|
||||
|
||||
/// One span per line the span touches, each stopping before the `\n`.
|
||||
@@ -231,17 +340,30 @@ mod tests {
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
/// Analyze `text` as an open buffer and hand the document to `f`.
|
||||
fn with_document<T>(text: &str, f: impl FnOnce(&Document) -> T) -> T {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let tokens = semantic_tokens(ws.document(&uri).expect("open"));
|
||||
f(ws.document(&uri).expect("open"))
|
||||
}
|
||||
|
||||
/// The whole buffer's tokens, as they go on the wire.
|
||||
fn tokens_of(text: &str) -> Vec<SemanticToken> {
|
||||
with_document(text, semantic_tokens)
|
||||
}
|
||||
|
||||
/// The tokens a range answer carries.
|
||||
fn ranged(text: &str, range: Range) -> Vec<SemanticToken> {
|
||||
with_document(text, |doc| semantic_tokens_in_range(doc, range))
|
||||
}
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.data
|
||||
.iter()
|
||||
data.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
@@ -250,6 +372,18 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
decode(&tokens_of(text))
|
||||
}
|
||||
|
||||
/// A range, spelled the way a test reads best.
|
||||
fn range(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range {
|
||||
start: Position { line: from.0, character: from.1 },
|
||||
end: Position { line: to.0, character: to.1 },
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords_numbers_and_strings_are_classified() {
|
||||
let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n");
|
||||
@@ -358,4 +492,487 @@ mod tests {
|
||||
vec![TextRange::new(0, 1), TextRange::new(2, 3)]
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Four lines, every one of them carrying tokens.
|
||||
const FOUR_LINES: &str =
|
||||
"module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n";
|
||||
|
||||
#[test]
|
||||
fn a_range_covering_everything_is_the_full_answer() {
|
||||
let full = tokens_of(FOUR_LINES);
|
||||
assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_re_encodes_from_the_start_of_the_document() {
|
||||
// The whole point of the re-encoding: a range answer is a
|
||||
// self-contained `SemanticTokens`, so its first token's deltas are
|
||||
// absolute — a client that pasted the slice out of the full answer
|
||||
// would draw line 2's tokens on line 0.
|
||||
let data = ranged(FOUR_LINES, range((2, 0), (3, 0)));
|
||||
let first = data.first().expect("line 2 has tokens");
|
||||
assert_eq!(first.delta_line, 2, "absolute from the document start");
|
||||
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
|
||||
assert_eq!(
|
||||
decode(&data),
|
||||
decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::<Vec<_>>(),
|
||||
"the same tokens the full answer puts on that line"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_range_covers_no_characters_and_so_no_tokens() {
|
||||
// Collapsed on a token, which is the tempting case to get wrong: a
|
||||
// zero-width range draws nothing, so it must answer nothing.
|
||||
assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_starts_mid_token_keeps_that_token_whole() {
|
||||
// The client asked which tokens to draw, not where to cut them —
|
||||
// and a length trimmed to the range would be a lie about the source.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_touching_no_token_is_empty() {
|
||||
// Wholly inside the whitespace of a line, and wholly past the file.
|
||||
assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_never_carries_a_token_from_outside_it() {
|
||||
let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0))));
|
||||
assert!(!inside.is_empty(), "premise: line 1 has tokens");
|
||||
assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}");
|
||||
}
|
||||
|
||||
/// The range/full agreement, on files nobody wrote to exercise it: for a
|
||||
/// window of whole lines, the range answer must decode to exactly the
|
||||
/// tokens the full answer puts on those lines. Stated line-wise rather
|
||||
/// than with the handler's own overlap test, so the two are independent.
|
||||
/// Skipped when `corpus/` is not checked out, like every other corpus
|
||||
/// test in this crate.
|
||||
#[test]
|
||||
fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let files =
|
||||
[corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")];
|
||||
let mut windows_checked = 0;
|
||||
for path in files {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default());
|
||||
let full = decode(&semantic_tokens(&doc));
|
||||
assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display());
|
||||
let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0);
|
||||
// Forty-line windows, the size an editor's viewport request is.
|
||||
let mut from = 0;
|
||||
while from <= last {
|
||||
let to = from + 40;
|
||||
let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0))));
|
||||
let expected: Vec<_> =
|
||||
full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect();
|
||||
assert_eq!(window, expected, "{}: lines {from}..{to}", path.display());
|
||||
windows_checked += 1;
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/full/delta`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The flat `u32` array the wire actually carries — what an edit's
|
||||
/// `start` and `deleteCount` index into.
|
||||
fn flat(tokens: &[SemanticToken]) -> Vec<u32> {
|
||||
tokens
|
||||
.iter()
|
||||
.flat_map(|t| {
|
||||
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Apply the edits exactly as a client does: in order, by index, on the
|
||||
/// flat array. Deliberately shares no code with `delta`.
|
||||
fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec<u32> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
let start = edit.start as usize;
|
||||
let end = start + edit.delete_count as usize;
|
||||
let inserted = flat(edit.data.as_deref().unwrap_or_default());
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// The invariant: applying what the server sent reproduces the new token
|
||||
/// list exactly. Returns the edits so a test can also say how many.
|
||||
fn reconstructs(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
apply_edits(&flat(&old), &edits),
|
||||
flat(&new),
|
||||
"the edits must reconstruct the new data:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
const MODULE: &str = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_buffer_produces_no_edits_at_all() {
|
||||
assert!(reconstructs(MODULE, MODULE).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_append_at_the_end_is_one_edit_that_deletes_nothing() {
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() {
|
||||
let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_in_the_middle_leaves_the_ends_alone() {
|
||||
let edits = reconstructs(
|
||||
"module m;\n wire a;\n wire b;\nendmodule\n",
|
||||
"module m;\n logic a;\n wire b;\nendmodule\n",
|
||||
);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_replacement_is_one_edit_over_everything() {
|
||||
let edits = reconstructs(MODULE, "`define W 8\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_stops_lexing_deletes_every_token_and_back() {
|
||||
// Mid-keystroke reality: an unterminated block comment has no tokens
|
||||
// at all, and the next keystroke brings them all back.
|
||||
let broken = "module m;\n wire a; /* unterminated\n";
|
||||
assert!(tokens_of(broken).is_empty(), "the premise");
|
||||
reconstructs(MODULE, broken);
|
||||
reconstructs(broken, MODULE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() {
|
||||
reconstructs(MODULE, "");
|
||||
reconstructs("", MODULE);
|
||||
assert!(reconstructs("", "").is_empty());
|
||||
}
|
||||
|
||||
/// A token, for the shapes that are about the algorithm rather than about
|
||||
/// Verilog.
|
||||
fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken {
|
||||
SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: Highlight::Keyword as u32,
|
||||
token_modifiers_bitset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() {
|
||||
// old = [A, B, A], new = [A]. The prefix claims the leading A; a
|
||||
// suffix counted over the *whole* lists would claim the trailing one
|
||||
// — the same token twice — and `new[prefix..new.len() - suffix]`
|
||||
// would then run backwards. Counting the suffix over what the prefix
|
||||
// left is the cap, and this is the shape that proves it.
|
||||
let (a, b) = (token(0, 0, 1), token(1, 0, 2));
|
||||
let old = vec![a, b, a];
|
||||
let new = vec![a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
|
||||
// And the mirror: growing into a repeating list.
|
||||
let edits = delta(&new, &old);
|
||||
assert_eq!(apply_edits(&flat(&new), &edits), flat(&old));
|
||||
|
||||
// The fully periodic case, where every token equals every other.
|
||||
let old = vec![a, a, a, a, a];
|
||||
let new = vec![a, a, a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() {
|
||||
// Identical lines encode to identical tokens — the delta encoding is
|
||||
// relative, so line 2 and line 3 of this buffer are byte-for-byte the
|
||||
// same five numbers. Deleting one of them is the overlap shape above,
|
||||
// reached without constructing anything by hand.
|
||||
let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n";
|
||||
let one = "module m;\n wire a;\nendmodule\n";
|
||||
let data = tokens_of(three);
|
||||
assert_eq!(data[2], data[4], "the premise: the encoding really does repeat");
|
||||
reconstructs(three, one);
|
||||
reconstructs(one, three);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edits_indices_count_numbers_and_not_tokens() {
|
||||
// The off-by-five that silently corrupts a client's cache: `start`
|
||||
// and `deleteCount` index the flat array, so both are five times a
|
||||
// token index.
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}");
|
||||
assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized sweep
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines a module body can be built from — repeats included, because
|
||||
/// repeats are what make the prefix and suffix fight over a token.
|
||||
const BODY: [&str; 8] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 8;",
|
||||
" // a comment",
|
||||
" assign a = b & c;",
|
||||
" always_ff @(posedge clk) q <= d;",
|
||||
" /* block */",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn buffer(rng: &mut Lcg) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(BODY[rng.below(BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pair_of_real_buffers_round_trips_through_its_delta() {
|
||||
let mut rng = Lcg(0x5eed);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
reconstructs(&before, &after);
|
||||
reconstructs(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): independent verification of the delta round-trip
|
||||
// and the range boundaries, on a code path that shares nothing with
|
||||
// the dev's own `apply_edits`/`reconstructs` helpers above.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// QA's own applier: unlike `apply_edits`, this never touches the flat
|
||||
/// `u32` array — it walks `SemanticToken`s and slices by hand instead of
|
||||
/// calling `Vec::splice`. It also asserts the `FIELDS` division is exact,
|
||||
/// which is a second, independent check of the "five times a token
|
||||
/// index" claim (`an_edits_indices_count_numbers_and_not_tokens`).
|
||||
fn independent_apply(
|
||||
old: &[SemanticToken],
|
||||
edits: &[SemanticTokensEdit],
|
||||
) -> Vec<SemanticToken> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}");
|
||||
assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}");
|
||||
let start = (edit.start / FIELDS) as usize;
|
||||
let deleted = (edit.delete_count / FIELDS) as usize;
|
||||
let mut rebuilt = Vec::with_capacity(data.len());
|
||||
rebuilt.extend_from_slice(&data[..start]);
|
||||
if let Some(inserted) = &edit.data {
|
||||
rebuilt.extend_from_slice(inserted);
|
||||
}
|
||||
rebuilt.extend_from_slice(&data[start + deleted..]);
|
||||
data = rebuilt;
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Same invariant as `reconstructs`, checked with QA's applier instead of
|
||||
/// the dev's.
|
||||
fn reconstructs_independently(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
independent_apply(&old, &edits),
|
||||
new,
|
||||
"QA reconstruction failed:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_two_independently_written_appliers_never_disagree() {
|
||||
// The dev's applier works on the flat `u32` array; QA's works on
|
||||
// `SemanticToken`s and never calls `Vec::splice`. Run both over the
|
||||
// same edits and the same inputs and demand they land on the same
|
||||
// place — and on the truth.
|
||||
let mut rng = Lcg(0xC0FFEE);
|
||||
for _ in 0..200 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
let (old, new) = (tokens_of(&before), tokens_of(&after));
|
||||
let edits = delta(&old, &new);
|
||||
let via_flat = apply_edits(&flat(&old), &edits);
|
||||
let via_tokens = flat(&independent_apply(&old, &edits));
|
||||
assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}");
|
||||
assert_eq!(via_tokens, flat(&new));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() {
|
||||
let module = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
// Both ends change at once, middle stays: prefix and suffix both
|
||||
// trim to non-trivial amounts.
|
||||
reconstructs_independently(
|
||||
module,
|
||||
"`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n",
|
||||
);
|
||||
// Middle only.
|
||||
reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n");
|
||||
// Identical.
|
||||
reconstructs_independently(module, module);
|
||||
// Complete replacement: nothing in common.
|
||||
reconstructs_independently(module, "`define totally different 1\n");
|
||||
// Old empty, new empty.
|
||||
reconstructs_independently("", module);
|
||||
reconstructs_independently(module, "");
|
||||
assert!(reconstructs_independently("", "").is_empty());
|
||||
// Single-token file, both directions and against itself.
|
||||
const SINGLE: &str = "// only one token\n";
|
||||
assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token");
|
||||
reconstructs_independently(SINGLE, module);
|
||||
reconstructs_independently(module, SINGLE);
|
||||
reconstructs_independently(SINGLE, SINGLE);
|
||||
}
|
||||
|
||||
/// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own
|
||||
/// seed.
|
||||
struct Xorshift64(u64);
|
||||
|
||||
impl Xorshift64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
self.0 = x;
|
||||
x
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// A pool that does not overlap the dev's `BODY`: it adds a block
|
||||
/// comment that spans lines, a continued `` `define``, and a generate
|
||||
/// block — pieces whose token *count* changes non-locally, not just
|
||||
/// whose content does.
|
||||
const QA_BODY: [&str; 9] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 4;",
|
||||
" // a trailing comment",
|
||||
" assign a = b ^ c;",
|
||||
" /* a block\n comment spanning lines */",
|
||||
" `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;",
|
||||
" generate\n if (W > 1) wire c;\n endgenerate",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn qa_buffer(rng: &mut Xorshift64) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() {
|
||||
let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng));
|
||||
reconstructs_independently(&before, &after);
|
||||
reconstructs_independently(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_ending_mid_token_keeps_that_token_whole() {
|
||||
// Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`:
|
||||
// the overlap guard must be symmetric at the far boundary too.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() {
|
||||
// Not an empty *line* (already covered by
|
||||
// `a_range_touching_no_token_is_empty`) — whitespace, plus an
|
||||
// unemitted `=`, between two real tokens on the same line.
|
||||
let text = "module m;\n assign a = b;\nendmodule\n";
|
||||
// "a" is the single character at column 9 (ends at 10); "b" starts
|
||||
// at column 17. Columns 11..16 are wholly inside that gap.
|
||||
let data = ranged(text, range((1, 11), (1, 16)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_reversed_range_is_total_and_answers_nothing() {
|
||||
// start > end is not a shape any client should send, but `within`'s
|
||||
// guard (`range.start >= range.end`) is symmetric to it: this must
|
||||
// not panic, and must answer empty exactly like a zero-width range.
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -2682,3 +2749,420 @@ fn selection_ranges_round_trip_over_the_wire() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A clean buffer with a multi-byte comment above the line the edits touch:
|
||||
/// a byte-vs-UTF-16 confusion in the sync path would land them on the wrong
|
||||
/// columns, and the diagnostics at the end would say so.
|
||||
const SYNCABLE: &str = "// é ✓ 🎉\nmodule sync_me;\n wire a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn incremental_changes_are_advertised_and_applied_over_the_wire() {
|
||||
let dir = temp_dir("incremental");
|
||||
let file = dir.join("sync_me.sv");
|
||||
std::fs::write(&file, SYNCABLE).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
// Three ranges in one notification, each positioned against what the
|
||||
// previous one left: delete the `a`, which breaks the buffer; type a `b`
|
||||
// back in, which fixes it; then open a new, broken declaration below.
|
||||
// A second notification finishes that declaration, badly spaced, so a
|
||||
// formatting request can read the composed buffer back off the wire.
|
||||
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(SYNCABLE).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{}]}}}}"#,
|
||||
[
|
||||
r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":8}},"text":""}"#,
|
||||
r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":7}},"text":"b"}"#,
|
||||
r#"{"range":{"start":{"line":3,"character":0},"end":{"line":3,"character":0}},"text":" wire ;\n"}"#,
|
||||
]
|
||||
.join(",")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":3}},"contentChanges":[{}]}}}}"#,
|
||||
r#"{"range":{"start":{"line":3,"character":9},"end":{"line":3,"character":9}},"text":"c"}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
)),
|
||||
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);
|
||||
|
||||
// 1. The capability says incremental, and says the rest explicitly.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let sync = &initialize["result"]["capabilities"]["textDocumentSync"];
|
||||
assert_eq!(sync["change"], 2, "TextDocumentSyncKind::Incremental: {initialize:#?}");
|
||||
assert_eq!(sync["openClose"], true, "{sync:#?}");
|
||||
assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}");
|
||||
|
||||
// 2. Each notification published once, and what it published describes
|
||||
// the composed buffer: the error is on the line the third range
|
||||
// inserted, and it clears when the fourth range finishes that line.
|
||||
let published: Vec<_> =
|
||||
messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect();
|
||||
assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}");
|
||||
assert!(
|
||||
published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"the file opened clean: {published:#?}"
|
||||
);
|
||||
let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array");
|
||||
assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}");
|
||||
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line");
|
||||
assert!(
|
||||
published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"and the next range fixed it: {published:#?}"
|
||||
);
|
||||
|
||||
// 3. And the buffer the server holds is exactly the composed text — read
|
||||
// back through the formatter, which normalizes only the spacing the
|
||||
// last range left behind.
|
||||
assert_eq!(
|
||||
new_text(&messages, 2),
|
||||
"// é ✓ 🎉\nmodule sync_me;\n wire b;\n wire c;\nendmodule\n",
|
||||
"the four ranges composed, and the emoji line untouched"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The client's side of a delta: splice each edit into the flat array it
|
||||
/// holds, by index. Shares nothing with the server's own code.
|
||||
fn apply_token_edits(previous: &[u64], answer: &serde_json::Value) -> Vec<u64> {
|
||||
let mut data = previous.to_vec();
|
||||
let edits = answer["edits"].as_array().unwrap_or_else(|| panic!("edits in {answer:#?}"));
|
||||
for edit in edits {
|
||||
let start = edit["start"].as_u64().expect("start") as usize;
|
||||
let end = start + edit["deleteCount"].as_u64().expect("deleteCount") as usize;
|
||||
let inserted = edit.get("data").map(token_numbers).unwrap_or_default();
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// A semantic-token `data` array as flat numbers.
|
||||
fn token_numbers(value: &serde_json::Value) -> Vec<u64> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("an array of numbers, got {value:#?}"))
|
||||
.iter()
|
||||
.map(|n| n.as_u64().expect("a number"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_range_and_delta_round_trip_over_the_wire() {
|
||||
// What a unit test cannot check: that both new capabilities reach the
|
||||
// wire in the shape a client keys off, and that a real delta — computed
|
||||
// by one process and applied by another, over the wire's flat number
|
||||
// array — reconstructs the token set the next full request answers.
|
||||
let dir = temp_dir("semantictokens");
|
||||
let file = dir.join("m.sv");
|
||||
let before = "module tokens_me;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
|
||||
let after =
|
||||
"module tokens_me;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n";
|
||||
std::fs::write(&file, before).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
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(before).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
|
||||
serde_json::to_string(after).expect("json")
|
||||
)),
|
||||
// The ids are minted one per answer from the start of the session, so
|
||||
// the full answer above is `"1"` — asserted below, so a changed
|
||||
// scheme fails loudly here rather than silently downgrading every
|
||||
// delta to a full answer.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/semanticTokens/full/delta","params":{{"textDocument":{{"uri":"{uri}"}},"previousResultId":"1"}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
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);
|
||||
|
||||
// 1. Both capabilities on the wire, in the shape a client reads.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let provider = &initialize["result"]["capabilities"]["semanticTokensProvider"];
|
||||
assert_eq!(provider["range"], true, "range is advertised: {provider:#?}");
|
||||
assert_eq!(provider["full"]["delta"], true, "and so are deltas: {provider:#?}");
|
||||
assert_eq!(
|
||||
provider["legend"]["tokenTypes"].as_array().expect("the legend").len(),
|
||||
14,
|
||||
"the legend is unchanged: {provider:#?}"
|
||||
);
|
||||
|
||||
// 2. The full answer is stamped, and its id is the one the delta named.
|
||||
let full = messages.iter().find(|m| m["id"] == 2).expect("full response");
|
||||
assert_eq!(full["result"]["resultId"], "1", "{full:#?}");
|
||||
let held = token_numbers(&full["result"]["data"]);
|
||||
assert!(!held.is_empty(), "{full:#?}");
|
||||
|
||||
// 3. The range answer stands on its own: no id, absolute first delta.
|
||||
let ranged = messages.iter().find(|m| m["id"] == 3).expect("range response");
|
||||
assert!(ranged["result"].get("resultId").is_none(), "nothing to name: {ranged:#?}");
|
||||
let window = token_numbers(&ranged["result"]["data"]);
|
||||
assert_eq!(window[0], 1, "deltaLine is absolute from the file start: {ranged:#?}");
|
||||
assert!(window.len() < held.len(), "and it is only part of the file: {ranged:#?}");
|
||||
|
||||
// 4. The delta reconstructs exactly what the next full request answers.
|
||||
let delta = messages.iter().find(|m| m["id"] == 4).expect("delta response");
|
||||
assert!(delta["result"].get("edits").is_some(), "a known id gets edits: {delta:#?}");
|
||||
let truth = messages.iter().find(|m| m["id"] == 5).expect("second full response");
|
||||
assert_eq!(
|
||||
apply_token_edits(&held, &delta["result"]),
|
||||
token_numbers(&truth["result"]["data"]),
|
||||
"applying the edits must land on the new token set exactly"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexing_reports_its_progress_over_the_wire() {
|
||||
// What only an e2e test can check: the create request and the two
|
||||
// `$/progress` notifications are framed, ordered, and carry the same
|
||||
// token — for a client that advertised `window.workDoneProgress`.
|
||||
let dir = temp_dir("progress");
|
||||
let file = dir.join("m.sv");
|
||||
let source = "module m;\nendmodule\n";
|
||||
std::fs::write(&file, source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
|
||||
)),
|
||||
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(source).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
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);
|
||||
|
||||
// Every progress message on the wire, in order, as (step, token).
|
||||
let steps: Vec<(String, String)> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m["method"].as_str() {
|
||||
Some("window/workDoneProgress/create") => Some((
|
||||
"create".to_string(),
|
||||
m["params"]["token"].as_str().expect("a string token").to_string(),
|
||||
)),
|
||||
Some("$/progress") => Some((
|
||||
m["params"]["value"]["kind"].as_str().expect("a kind").to_string(),
|
||||
m["params"]["token"].as_str().expect("a string token").to_string(),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Two rescans: the startup build, then the save. Each one create, one
|
||||
// begin, one end, on its own token.
|
||||
assert_eq!(
|
||||
steps,
|
||||
vec![
|
||||
("create".to_string(), "lucisv-index-0".to_string()),
|
||||
("begin".to_string(), "lucisv-index-0".to_string()),
|
||||
("end".to_string(), "lucisv-index-0".to_string()),
|
||||
("create".to_string(), "lucisv-index-1".to_string()),
|
||||
("begin".to_string(), "lucisv-index-1".to_string()),
|
||||
("end".to_string(), "lucisv-index-1".to_string()),
|
||||
],
|
||||
"{messages:#?}"
|
||||
);
|
||||
|
||||
// The begin says what it is doing, and offers no cancel button — a rescan
|
||||
// that has started runs to completion, whatever `$/cancelRequest` can do
|
||||
// for the requests still queued.
|
||||
let begin = messages.iter().find(|m| m["params"]["value"]["kind"] == "begin").expect("a begin");
|
||||
assert_eq!(begin["params"]["value"]["title"], "Indexing Verilog workspace", "{begin:#?}");
|
||||
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
|
||||
assert!(begin["params"]["value"].get("percentage").is_none(), "no fake numbers: {begin:#?}");
|
||||
|
||||
let end = messages.iter().find(|m| m["params"]["value"]["kind"] == "end").expect("an end");
|
||||
assert_eq!(end["params"]["value"]["message"], "1 file indexed", "{end:#?}");
|
||||
|
||||
// The create is a request the client may answer or error; leaving it
|
||||
// unanswered here is exactly what a client that does not care does, and
|
||||
// the session still shuts down cleanly (asserted inside `talk`).
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
|
||||
let dir = temp_dir("noprogress");
|
||||
let file = dir.join("m.sv");
|
||||
let source = "module m;\nendmodule\n";
|
||||
std::fs::write(&file, source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
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(source).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
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);
|
||||
assert!(
|
||||
messages.iter().all(|m| {
|
||||
m["method"] != "$/progress" && m["method"] != "window/workDoneProgress/create"
|
||||
}),
|
||||
"the spec forbids progress a client never asked for: {messages:#?}"
|
||||
);
|
||||
// And it still got its diagnostics, so the save path ran.
|
||||
assert!(
|
||||
messages.iter().any(|m| m["method"] == "textDocument/publishDiagnostics"),
|
||||
"{messages:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The ids the flood cancels — every second request.
|
||||
fn is_cancelled(id: u32) -> bool {
|
||||
id % 2 == 1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
|
||||
// The one test that runs the real `run()` loop, and so the only one that
|
||||
// exercises the burst drain over a real pipe. The whole session is written
|
||||
// in a single `write` before a byte is read back, so every request and the
|
||||
// cancel behind it are in flight together — which is the only situation a
|
||||
// one-message-at-a-time server can honour a cancel in at all.
|
||||
//
|
||||
// **How many get cancelled is not asserted, and cannot be.** Whether a
|
||||
// cancel reaches the loop in the same burst as its request is a race with
|
||||
// the transport's own threads, and the spec's answer to losing it is to
|
||||
// answer the request normally. So this pins what must hold either way —
|
||||
// one answer per request, never a wrong one — plus the fact that the
|
||||
// cancellation path does work over the wire. Twenty formatting requests
|
||||
// over a three-hundred-line buffer is enough work per message that the
|
||||
// backlog is real: under a twenty-four-way overload the worst observed
|
||||
// was two in five honoured, never none.
|
||||
let dir = temp_dir("cancelflood");
|
||||
let file = dir.join("m.sv");
|
||||
let source: String = std::iter::once("module flooded;\n".to_string())
|
||||
.chain((0..300).map(|i| format!("wire w{i};\n")))
|
||||
.chain(std::iter::once("endmodule\n".to_string()))
|
||||
.collect();
|
||||
std::fs::write(&file, &source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let mut session = vec![
|
||||
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(&source).expect("json")
|
||||
)),
|
||||
];
|
||||
for id in 10..30u32 {
|
||||
session.push(frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
)));
|
||||
if is_cancelled(id) {
|
||||
session.push(frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
|
||||
)));
|
||||
}
|
||||
}
|
||||
// A cancel for a request this server was never sent. It names nothing in
|
||||
// any burst, so it is dropped where it is read.
|
||||
session.push(frame(r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":999}}"#));
|
||||
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
|
||||
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
|
||||
|
||||
let messages = talk(&session.concat());
|
||||
|
||||
let mut honoured = 0;
|
||||
for id in 10..30u32 {
|
||||
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
|
||||
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
|
||||
let answer = answers[0];
|
||||
if answer.get("error").is_some() {
|
||||
assert!(is_cancelled(id), "id {id} was never cancelled: {answer:#?}");
|
||||
assert_eq!(answer["error"]["code"], -32800, "cancelled, not failed: {answer:#?}");
|
||||
assert!(answer.get("result").is_none(), "an error carries no result: {answer:#?}");
|
||||
assert!(
|
||||
answer["error"]["message"].as_str().is_some_and(|m| !m.is_empty()),
|
||||
"a cancelled response carries a message: {answer:#?}"
|
||||
);
|
||||
honoured += 1;
|
||||
} else {
|
||||
// Answered for real: the whole buffer, indented.
|
||||
let edits = answer["result"].as_array().expect("an array of edits");
|
||||
assert_eq!(edits.len(), 1, "one whole-document edit: {answer:#?}");
|
||||
assert!(
|
||||
edits[0]["newText"]
|
||||
.as_str()
|
||||
.expect("newText")
|
||||
.starts_with("module flooded;\n wire w0;\n"),
|
||||
"id {id} was formatted: {answer:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(honoured > 0, "the cancellation path runs over the wire: {messages:#?}");
|
||||
|
||||
// The shutdown came through the same flood and was still honoured —
|
||||
// `talk` asserts the process then exited cleanly.
|
||||
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
|
||||
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {shutdown:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
# cancel-request
|
||||
|
||||
## Goal
|
||||
|
||||
`$/cancelRequest` is the client's way of saying "drop that one, the user has
|
||||
moved on" — sent constantly by real editors, which cancel the completion,
|
||||
hover and inlay-hint requests of the previous keystroke on every new one.
|
||||
Until now the notification fell through `Server::notification`'s `_ => {}` arm
|
||||
and the request was computed and answered anyway. This round answers a
|
||||
cancelled request with the protocol's own `RequestCancelled` (-32800) instead
|
||||
of computing it, whenever the cancel reaches the loop in time — which, on a
|
||||
single-threaded server, means *while the request is still queued*. The gain is
|
||||
not correctness (an ignored cancel is legal) but work not done: on a slow
|
||||
rescan or a large-file format, the queue behind the busy handler is exactly
|
||||
where a stale completion request sits, and answering it costs nothing (TODO.md
|
||||
§9b, the last item of that section).
|
||||
|
||||
## What "in time" can mean on a one-message-at-a-time loop
|
||||
|
||||
Everything about this feature follows from one fact: **the client sends the
|
||||
request and its cancel down one ordered channel**, and the server handles one
|
||||
message at a time. Read strictly one message per iteration, a cancel is always
|
||||
too late — by the time `C(R)` is dequeued, `R` was dequeued, computed and
|
||||
answered an iteration ago. Cancellation only becomes reachable when the loop
|
||||
looks at *more than one message at a time*: while a handler runs, the client
|
||||
keeps sending, so the backlog waiting behind it can hold `[R1, C(R1), R2]` —
|
||||
and R1 can be answered `RequestCancelled` for free.
|
||||
|
||||
So `run()` now works in bursts:
|
||||
|
||||
1. block for the next message, as before;
|
||||
2. take everything already queued behind it, without blocking, into one FIFO
|
||||
(the blocked-for message first);
|
||||
3. scan that whole burst for `$/cancelRequest` notifications and collect the
|
||||
ids that name a request **in the same burst**;
|
||||
4. handle the burst strictly in arrival order — a cancelled request answered
|
||||
`RequestCancelled` without dispatch, every other message exactly as before.
|
||||
|
||||
Step 3 is what keeps the cancelled set from being state: it is built per burst
|
||||
and dropped with it.
|
||||
|
||||
### The transport does not queue — so we do
|
||||
|
||||
The first attempt used `connection.receiver.try_recv()` for step 2 and
|
||||
cancelled **nothing** over a real pipe. The reason is worth writing down,
|
||||
because it is invisible from the API:
|
||||
|
||||
> `lsp-server` 0.10's stdio transport wires its reader, writer and dropper
|
||||
> threads with **`crossbeam_channel::bounded(0)`** — rendezvous channels with
|
||||
> no capacity at all (`stdio.rs`). Its reader thread parks *inside* `send`
|
||||
> holding one message until the loop takes it. A client's backlog therefore
|
||||
> never sits on `connection.receiver`: it sits in the OS pipe, one message
|
||||
> deep from where we stand, and `try_recv` right after a `recv` loses a
|
||||
> microsecond-scale race with the reader thread essentially every time.
|
||||
|
||||
`Server::queue()` fixes this with the smallest thing that can: one forwarder
|
||||
thread that blocks on `connection.receiver` and pushes onto an unbounded
|
||||
`std::sync::mpsc` queue that `run()` owns. The backlog then accumulates where
|
||||
we can see it, and step 2 is a plain `try_recv` loop. The thread touches no
|
||||
server state, moves messages and nothing else, and is std-only — no new
|
||||
dependency.
|
||||
|
||||
The forwarder **stops at the `shutdown` request and never reads past it**.
|
||||
`Connection::handle_shutdown` answers the request and then reads the `exit`
|
||||
notification off the *connection* itself; a forwarder that kept going would
|
||||
take that `exit` first, and `handle_shutdown` would block for its full
|
||||
thirty-second timeout and then return a protocol error. Stopping there also
|
||||
means nothing after a shutdown is ever queued, which is exactly the protocol's
|
||||
own rule.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Cancellation is best-effort, and the spec says so.** LSP allows a server
|
||||
to ignore a cancel it cannot honour; the only hard requirement is that every
|
||||
request gets exactly one response. Both are held here: a cancel that misses
|
||||
its window leaves the request answered normally.
|
||||
- **A cancel arriving in a *later* burst than its request is dropped.** By
|
||||
then the request has been answered — there is nothing left to cancel, and
|
||||
remembering the id would be a set that grows for the life of the session.
|
||||
This is the single rule that keeps this feature stateless.
|
||||
- **A cancel in the same burst but dequeued *before* its request still
|
||||
cancels it.** The burst is scanned as a whole before any of it runs, so
|
||||
ordering within the burst does not matter. (A real client never sends the
|
||||
cancel first; a transport is free to make it look that way.)
|
||||
- **A cancel for a request the server never received is dropped** where it is
|
||||
read, for the same reason.
|
||||
- **Cancelling one request twice is harmless.** The id is removed from the
|
||||
cancelled set as it is used, so a second cancel finds nothing — and it could
|
||||
not touch a later request even if ids were reused, because the set never
|
||||
outlives its burst.
|
||||
- **`shutdown` is never cancellable.** `handle_shutdown` runs before the
|
||||
cancelled set is consulted, so a cancel naming the shutdown id cannot stop
|
||||
the server from shutting down. The spec's "a server should still answer a
|
||||
cancelled request" reading is the safe one here: a client that cannot shut
|
||||
its server down leaks a process.
|
||||
- **Notifications are never cancelled.** They carry no id and get no
|
||||
response; `$/cancelRequest` names request ids only. A `didChange` queued
|
||||
ahead of a cancelled request is still applied — the state a *later* request
|
||||
is answered against must not depend on which requests were dropped.
|
||||
- **Order inside a burst is the invariant, not an implementation detail.**
|
||||
A `didChange` the client sent before a completion request must be in effect
|
||||
when that completion is answered, exactly as it would be one message at a
|
||||
time. Pinned by
|
||||
`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`.
|
||||
- **Both id forms are read.** `CancelParams.id` is
|
||||
`NumberOrString`; a numeric id becomes `RequestId::from(i32)` and a string
|
||||
id `RequestId::from(String)`. The string `"8"` is not the number `8` —
|
||||
`RequestId` keeps them apart and so does the cancel, which is the only
|
||||
behaviour that can be right when a client uses both forms.
|
||||
- **A cancel whose params do not parse is dropped**, on the same reasoning as
|
||||
every other malformed notification: there is no id to act on and no id to
|
||||
answer on.
|
||||
- **The cancelled response carries a message.** `-32800` plus
|
||||
`"lucisv: request cancelled by the client"`. Clients do not show it — the
|
||||
code is what they read — but a log with the text in it is easier to read
|
||||
than a log with a number in it.
|
||||
- **Nothing already *running* is cancelled.** There is one thread; a format,
|
||||
a rescan or a rename that has started runs to completion. The work-done
|
||||
progress bar still advertises `cancellable: false`, which stays true.
|
||||
- **The queue is unbounded.** Backpressure on the pipe used to be the reader
|
||||
thread's rendezvous; now a burst is buffered in memory instead. For an LSP
|
||||
client that is bounded by what an editor sends between two of our handler
|
||||
calls — kilobytes. A client that floods a server faster than it can read
|
||||
would grow this queue, and would equally have grown the pipe before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server` (this feature's own module)
|
||||
|
||||
- `Server::run` no longer receives-and-dispatches inline. It builds the queue,
|
||||
blocks on it, and hands each burst to `process_batch`. Behaviour for a
|
||||
client that never cancels is identical, message for message.
|
||||
- **New private items:** `Server::queue()` (the forwarder),
|
||||
`Server::process_batch(Vec<Message>) -> Result<bool, …>` (the burst
|
||||
handler; `true` means the client shut us down), and the free functions
|
||||
`burst`, `is_shutdown`, `cancelled_in`, `cancelled_id`, `cancelled_response`.
|
||||
- `Server::request`, `Server::notification` and `Server::response` are
|
||||
**unchanged**. `$/cancelRequest` never reaches `notification()`; it is
|
||||
consumed in the burst handler, which is the only place that can act on one.
|
||||
- No field was added to `Server`. Cancellation state lives for the length of
|
||||
one burst and no longer.
|
||||
|
||||
### `lsp-server`
|
||||
|
||||
- Consumed, not changed: `Connection.receiver` is now `clone()`d (crossbeam
|
||||
receivers are `Clone`), and `handle_shutdown` is called exactly where it was
|
||||
— the forwarder's stop rule is what keeps its `exit` read working.
|
||||
- The rendezvous-channel finding above is a property of version `=0.10.0`,
|
||||
which the workspace pins. A future bump should re-read `stdio.rs`: if the
|
||||
transport ever queues, `Server::queue` becomes redundant rather than wrong.
|
||||
|
||||
### Every other crate, and `editors/vscode`
|
||||
|
||||
**Untouched.** No engine crate knows this happened, and no client capability
|
||||
gates it — `$/cancelRequest` is unconditional in the protocol, advertised by
|
||||
nobody and sent by everybody. `smoke.js` passes unchanged (run as a gate).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `run()` restructured into blocking receive → burst drain → burst handler
|
||||
- [x] Forwarder thread so the backlog is observable at all (the rendezvous
|
||||
finding), stopping at `shutdown` so `handle_shutdown` keeps its `exit`
|
||||
- [x] Cancelled ids collected per burst, matched against that burst's own
|
||||
requests, dropped otherwise
|
||||
- [x] Cancelled requests answered `-32800` without dispatch; the cancels
|
||||
themselves consumed
|
||||
- [x] `shutdown` honoured before any cancel is consulted
|
||||
- [x] Arrival order preserved across the whole burst (notifications included)
|
||||
- [x] Numeric and string cancel ids; malformed cancels dropped
|
||||
- [x] Tests: 10 unit in `server.rs` (through the `Session` harness, driving
|
||||
the real `process_batch`), 1 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox; loop description in
|
||||
`docs/features/lucisv-server/README.md`
|
||||
- [ ] **Not done, deliberately:** no cancellation of work in flight. That
|
||||
needs a worker pool and cancellation tokens threaded through the engine
|
||||
— TODO.md §6's explicit non-goal for as long as per-file recompute stays
|
||||
in the millisecond range.
|
||||
- [ ] **Not done, deliberately:** no `ContentModified` (-32801) for requests
|
||||
invalidated by a `didChange` queued behind them. It is the neighbouring
|
||||
idea and a real option now that the loop can see a burst, but the spec
|
||||
warns that an answer computed against slightly older text is usually
|
||||
still useful — and the client, not the server, is the one that knows.
|
||||
Filed here, not built.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent (§9b, `$/cancelRequest`)
|
||||
|
||||
- Read `CLAUDE.md`, `docs/features/lucisv-server/README.md`, TODO.md §9b and
|
||||
the whole of `server.rs`'s loop before touching anything.
|
||||
- **Verified the lead's design against the code, and found one thing that
|
||||
invalidated its second step.** The plan said to drain `connection.receiver`
|
||||
non-blockingly with `try_iter`/`try_recv`. Written that way, the e2e flood
|
||||
cancelled **zero** of five requests, reproducibly. `lsp-server` 0.10's
|
||||
`stdio.rs` uses `bounded(0)` rendezvous channels throughout: there is no
|
||||
queue on that receiver to drain, ever. The rest of the design — burst FIFO,
|
||||
batch-wide cancel scan, drop-if-not-in-batch, order preserved, shutdown
|
||||
never cancellable — is unchanged and implemented as written.
|
||||
- **Fix: one forwarder thread** (`Server::queue`) onto a `std::sync::mpsc`
|
||||
queue, so the backlog accumulates somewhere observable. Std-only, no new
|
||||
dependency, no shared state, ~12 lines. Considered and rejected: a timed
|
||||
drain window (`recv_timeout(1ms)`), which would tax *every* message with a
|
||||
millisecond of latency and still be a race; and handling shutdown ourselves
|
||||
to free the forwarder, which would duplicate `handle_shutdown`'s protocol
|
||||
for no gain.
|
||||
- **The forwarder's stop-at-shutdown rule was found by reading
|
||||
`handle_shutdown`, not by a failing test**: it reads `exit` off the
|
||||
connection itself, so an eager forwarder would have stolen it and turned
|
||||
every shutdown into a 30-second timeout followed by a protocol error. The
|
||||
rule is asserted by `a_shutdown_is_honoured_however_it_is_cancelled` and by
|
||||
the e2e session, which shuts down through the same flood.
|
||||
- Tests: 10 unit tests in `server.rs`, driving the real `process_batch`
|
||||
through a new `Session::batch` helper (the harness otherwise bypasses the
|
||||
loop entirely), plus `Session::answers()` for reading responses off the
|
||||
client end. One e2e test running the real binary and the real `run()`.
|
||||
- **The e2e test asserts what is deterministic, and says why.** Three
|
||||
iterations were needed to get there: with cheap requests, *how many* cancels
|
||||
land in the same burst as their request is a scheduling race, and demanding
|
||||
all five failed roughly one full-suite run in four (the suite runs 38
|
||||
server processes in parallel). The final shape floods twenty
|
||||
`textDocument/formatting` requests over a 300-line buffer — enough work per
|
||||
message that the forwarder is never starved — and asserts the properties
|
||||
that must hold on any schedule: exactly one response per request, `-32800`
|
||||
only ever on an id the client actually cancelled, a correct formatted answer
|
||||
on every other id, at least one honoured cancel (the wire path works), and
|
||||
a clean shutdown. Measured under a deliberate 24-way overload: worst case
|
||||
two of five honoured, never zero.
|
||||
- Also corrected two now-stale comments about cancellation being absent
|
||||
entirely — the module header of `server.rs`, `begin_indexing`'s note on
|
||||
`cancellable: false`, and the matching line in the progress e2e test. The
|
||||
bar's `false` stays correct: what has *started* still runs to completion.
|
||||
- Gates, all clean: `cargo fmt --all -- --check`, `cargo clippy --all-targets`
|
||||
(no warnings), `cargo test --workspace` (34 suites green; `lucisv_server`
|
||||
702 unit + 38 e2e), `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK. The e2e suite was re-run ten consecutive
|
||||
times looking for flake: ten passes.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent (§9b, `$/cancelRequest`)
|
||||
|
||||
**Verdict: committable as-is.** No corruption, no protocol violation, no
|
||||
reproducible flake found. Four gaps in test coverage for the highest-risk
|
||||
part of the change (the forwarder thread) were found and closed directly;
|
||||
one theoretical (not reproduced) flake risk in the e2e flood is recorded
|
||||
below with a reasoned trade-off, not "fixed," because the fixes available
|
||||
would weaken the property the test exists to prove.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
|
||||
clean, no warnings. `cargo test --workspace`: every suite green, including
|
||||
`lucisv_server` at 706 unit (was 702 pre-QA; +4 added below) + 38 e2e.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` →
|
||||
OK. `cargo test -p lucisv_server --test e2e` run five more times standalone,
|
||||
before the QA-added tests and five more times after: **10/10 green**, no
|
||||
flake observed in the flood test or anywhere else in the suite.
|
||||
|
||||
**1. Forwarder shutdown hand-off — verified clean, by reading
|
||||
`lsp-server` 0.10's actual source, not the dev's summary.**
|
||||
|
||||
- Read `~/.cargo/registry/.../lsp-server-0.10.0/src/stdio.rs`,
|
||||
`src/lib.rs` (`Connection::handle_shutdown`, `Connection::memory`) and
|
||||
`src/msg.rs` (`Request::is_shutdown`, `Notification::is_exit`,
|
||||
`Response`'s `#[serde(flatten)]` encoding). Confirms the README's claim:
|
||||
the stdio reader thread parks inside a `bounded(0)` `send` until taken,
|
||||
so a client's backlog really does live in the OS pipe and not on
|
||||
`connection.receiver`.
|
||||
- (a) **Method-name detection, and the notification case.** `is_shutdown`
|
||||
(`crates/lucisv_server/src/server.rs:1119`) matches
|
||||
`Message::Request { method == "shutdown" }` only — the same test
|
||||
`lsp-server`'s own `Request::is_shutdown` (msg.rs:233) uses. A
|
||||
**notification** shaped like `{"method":"shutdown"}` fails the match
|
||||
(wrong enum variant), so the forwarder does not stop for it; it is
|
||||
forwarded like any other message and falls through `notification()`'s
|
||||
`_ => {}` arm, doing nothing. This was asserted by nothing before QA —
|
||||
added `is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`
|
||||
(server.rs:3574). A malformed shutdown-*request* (e.g. non-null params)
|
||||
is not a distinct case: neither `is_shutdown` nor `handle_shutdown`
|
||||
parses params, only the method name, so there is nothing to be
|
||||
malformed.
|
||||
- (b) **The stolen-message / deadlock window.** Traced the forwarder
|
||||
(`Server::queue`, server.rs:209-233): it checks `is_shutdown` on the
|
||||
message **after** receiving it but **before** issuing its next `recv()`,
|
||||
and breaks its loop without calling `recv()` again when that check is
|
||||
true. `handle_shutdown` (lsp-server lib.rs:348) is only reached by
|
||||
`process_batch` for a request already sitting in the batch Vec — i.e.
|
||||
after the forwarder that produced it has already returned from its last
|
||||
`sender.send`. Because the forwarder's own break happens strictly before
|
||||
any further receive, there is no window where both the forwarder and
|
||||
`handle_shutdown` are calling `recv`/`recv_timeout` on the same
|
||||
crossbeam channel at once — no steal, no deadlock. Added
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`
|
||||
(server.rs:3632), which sends a real shutdown request + exit notification
|
||||
through a `Connection::memory()` pair, calls the real `Server::queue()`,
|
||||
and asserts (i) the shutdown is the last thing the forwarder ever
|
||||
forwards even after 50ms of extra opportunity to misbehave, and (ii) the
|
||||
`exit` is still sitting, unread, directly on `connection.receiver` —
|
||||
exactly where `handle_shutdown` looks for it. This is the one test in
|
||||
the whole suite that exercises the real `queue()` method without going
|
||||
through a subprocess.
|
||||
- (c) **Messages already forwarded ahead of a shutdown in the same
|
||||
batch.** Because the forwarder always stops immediately after
|
||||
forwarding the message it detects as shutdown, shutdown is provably
|
||||
always the *last* message that forwarder instance ever produces — there
|
||||
is no way for a message to be forwarded *after* shutdown by the same
|
||||
producer, and there is only ever one producer (next point). So the
|
||||
scenario "a request forwarded after shutdown gets silently dropped" is
|
||||
not reachable through this code path. Nothing found here; the design
|
||||
note in the feature README (lines 63-69) undersells this a little by
|
||||
only mentioning the *thirty-second timeout* consequence of an eager
|
||||
forwarder — the actual structural guarantee (shutdown is always last)
|
||||
is worth knowing but the doc isn't wrong, just less complete than it
|
||||
could be. Not fixed (doc-only, not a code finding, and rewriting
|
||||
someone else's README section is not QA's job per CLAUDE.md).
|
||||
|
||||
**2. Message loss/reordering — verified clean.**
|
||||
|
||||
- Exactly one producer: `Server::queue` is called exactly once, from
|
||||
`Server::run` (server.rs:185), which is itself called exactly once, from
|
||||
`main.rs:76`. No respawn path exists.
|
||||
- Single channel used throughout: `run`'s blocking head-of-burst read and
|
||||
`burst`'s non-blocking drain (server.rs:1126) both operate on the same
|
||||
`std::sync::mpsc::Receiver` returned by `queue()` — never a mix of the
|
||||
mpsc and `connection.receiver` on the consuming side. (`connection.receiver`
|
||||
itself is only ever touched by the forwarder's `source` handle and by
|
||||
`handle_shutdown`, never by `run`/`burst`/`process_batch`.)
|
||||
- Exactly-once processing: `burst` pushes the blocking-received `first`
|
||||
plus everything `try_recv` drains, with no filtering or dedup step in
|
||||
between — the FIFO in equals the FIFO out. Added
|
||||
`burst_collects_everything_already_queued_in_arrival_order`
|
||||
(server.rs:3602) directly against a fresh
|
||||
`std::sync::mpsc` channel (no `Server` involved), pinning arrival order
|
||||
for `[first, second, third]`. Previously `burst` had zero direct test
|
||||
coverage — every existing cancel test drives `process_batch` through
|
||||
`Session::batch`, bypassing `burst` entirely, so this was a real gap in
|
||||
a change the assignment calls "the highest-risk this repo's server has
|
||||
taken."
|
||||
|
||||
**3. `exit` handling / zombie-thread check — verified clean.**
|
||||
|
||||
- `talk()` (e2e.rs:66-79) and the progress-e2e session's own `finish()`
|
||||
(e2e.rs:1978-1985) both call `child.wait()` and assert
|
||||
`status.success()` — a hung forwarder or a process that doesn't
|
||||
terminate would hang or fail these, and none did across 10 e2e runs.
|
||||
This is a real check, not a rubber stamp: `child.wait()` blocks until
|
||||
the OS reports the process gone, so a genuinely undead forwarder thread
|
||||
(blocked on stdin, holding the process open) would show up as a test
|
||||
timeout, not a silent pass.
|
||||
- The forwarder thread is detached (`let _ = ... .spawn(...)`), never
|
||||
joined. This is fine for process exit: after `shutdown`+`exit`, the
|
||||
forwarder has *already* stopped itself (point 1b) well before `run()`
|
||||
returns, so by the time `main()` returns there is no thread left
|
||||
blocked on I/O that could hold the process open. In the one edge case
|
||||
where a client disconnects without ever sending `shutdown` (broken
|
||||
pipe), the forwarder's own `source.recv()` errors, it drops its `sender`
|
||||
and exits, closing the mpsc and unblocking `run()`'s own `recv()` the
|
||||
same way `self.connection.receiver.recv()` used to unblock pre-diff —
|
||||
behaviorally identical to the old direct-receive loop for that case.
|
||||
Not a new finding; equivalent to prior behavior.
|
||||
|
||||
**4. Cancellation semantics matrix — re-verified independently, assertions
|
||||
read (not just names), all pass; one gap closed.**
|
||||
|
||||
Read every assertion, not just the test name, for: same-burst
|
||||
cancel-after (`a_request_cancelled_in_the_same_burst_is_answered_cancelled`),
|
||||
cancel-before (`a_cancel_dequeued_before_its_request_still_cancels_it`),
|
||||
partial-batch cancel (`a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone`),
|
||||
orphan/late drop with the id-reuse proof
|
||||
(`a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot`),
|
||||
notification-ordering
|
||||
(`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`),
|
||||
notifications-uncancellable (`a_cancel_never_cancels_a_notification`),
|
||||
shutdown-uncancellable (`a_shutdown_is_honoured_however_it_is_cancelled`),
|
||||
double cancel (`cancelling_one_request_twice_answers_it_once`), int-vs-string
|
||||
ids including the `"8"` vs `8` case (`a_cancel_id_may_be_a_number_or_a_string`),
|
||||
and malformed params (`a_malformed_cancel_is_dropped_rather_than_guessed_at`).
|
||||
Every one asserts what its name claims; none was a false-positive
|
||||
(no-op) test. All pass, independently re-run.
|
||||
|
||||
**Gap found and closed:** no test covered a cancel naming a
|
||||
**server-initiated** id (the `lucisv-0`/`lucisv-index-N`/`lucisv-watched-files-N`
|
||||
namespace from `Server::send_request`, server.rs:949). Traced it: `cancelled_in`
|
||||
(server.rs:1141) only ever matches a cancel against ids of `Message::Request`
|
||||
entries *received in the same batch* — a server-initiated id only ever
|
||||
appears on the wire as a `Message::Response` coming back from the client,
|
||||
a different match arm in `process_batch` entirely, never consulted against
|
||||
`cancelled`. So interference is not possible by construction. Added
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(server.rs:3682) to pin this rather than leave it as an inference:
|
||||
it calls the real `send_request`, gets back `lucisv-0`, sends a cancel
|
||||
naming it alongside an ordinary client request, asserts the client request
|
||||
is untouched, and then answers the server-initiated request successfully
|
||||
to prove routing was never disturbed.
|
||||
|
||||
**5. `-32800` on the wire — verified, one assertion added.**
|
||||
|
||||
`cancelled_response` (server.rs:1171) uses
|
||||
`lsp_server::ErrorCode::RequestCanceled as i32`, which is `-32800` in
|
||||
`msg.rs:128` — matches spec. `Response`'s `#[serde(flatten, with =
|
||||
"ResponseResult")]` (lsp-server msg.rs:87-98) serializes to exactly one of
|
||||
`result`/`error`, never both — confirmed by reading the encoding, and by
|
||||
the e2e flood's existing `answer.get("result").is_none()` on a real wire
|
||||
response (e2e.rs:3141). Id-type preservation (int in → int in response) is
|
||||
implicitly covered by the flood test's own matching: it filters
|
||||
`messages.iter().filter(|m| m["id"] == id)` against a Rust `u32`, which
|
||||
would find nothing if the id had round-tripped as a string, and the test
|
||||
asserts exactly one match per id. **Gap found and closed:** nothing
|
||||
asserted that the error carried a non-empty `message` string, only that
|
||||
`code` was right and `result` was absent. Added that assertion in-line at
|
||||
e2e.rs (next to the `result`-absence check in
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each`).
|
||||
|
||||
**6. The e2e flood's honesty — one theoretical, unreproduced flake risk,
|
||||
documented rather than "fixed."**
|
||||
|
||||
Read the whole test (e2e.rs:3079-3168). The `honoured > 0` assertion
|
||||
(e2e.rs:3160) is the one the
|
||||
task flagged as suspicious, correctly. Reasoning:
|
||||
|
||||
- The forwarder thread and the main loop's request handling run
|
||||
concurrently on real OS threads. While the main thread is inside a
|
||||
synchronous `self.request(...)` call (formatting), the forwarder can
|
||||
keep draining the reader thread's rendezvous handoffs into the mpsc
|
||||
queue in parallel — this concurrency, not any timer, is what makes a
|
||||
multi-message burst likely.
|
||||
- It is **not mathematically impossible** for every burst to end up size
|
||||
1: a scheduler that always preempts the forwarder thread and lets the
|
||||
main thread fully drain-and-reblock before the next message is
|
||||
forwarded would produce zero cancellations, every time, for any finite
|
||||
request count. No such interleaving was produced in 10 standalone e2e
|
||||
runs plus one full `cargo test --workspace` run (which itself runs the
|
||||
e2e binary), so it is not a *practical* risk today, but "never observed"
|
||||
is exactly the "≠ impossible" the task named.
|
||||
- **Why not fixed:** the two available code fixes both make the test
|
||||
worse. Relaxing `honoured > 0` to `honoured >= 0` (i.e., deleting the
|
||||
assertion) would stop the test from ever proving the cancellation path
|
||||
works over the real wire at all — the one thing this e2e test exists to
|
||||
check per its own doc comment. Adding a synchronization point (e.g. a
|
||||
test-only delay hook) to force a burst would add production-code
|
||||
surface *purely for a test's benefit*, which the "simplicity first"
|
||||
section of `CLAUDE.md` weighs against, for a risk that is theoretical
|
||||
and has a fallback: a failure here is a flake in one non-gating-by-flake
|
||||
test, not a correctness bug (the request would still be answered
|
||||
correctly once instead of cancelled — see point 4's stateless-drop
|
||||
behavior — so no invariant breaks, only the "never zero" assertion
|
||||
would).
|
||||
- **Recommendation:** accept the residual risk as-is. If it is ever
|
||||
observed to flake in CI, the fix is almost certainly to widen the
|
||||
buffer/request count further (the dev already tuned this once, from a
|
||||
~1-in-4 flake rate with cheap requests down to zero observed in 10+ runs
|
||||
with 300 lines / 20 requests) rather than to touch the assertion itself.
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.**
|
||||
|
||||
- No bare `std::thread::spawn` (which panics on OS resource exhaustion).
|
||||
The forwarder uses `std::thread::Builder::new().spawn(...)`
|
||||
(server.rs:215), which returns `io::Result`, and the error is
|
||||
deliberately discarded with `let _ =` plus a comment explaining the
|
||||
fallback (the mpsc sender is dropped, so `run()`'s `recv()` fails and
|
||||
the loop ends cleanly instead of hanging) — no panic path introduced.
|
||||
This is in `main`-path server setup, which CLAUDE.md's "Tests and
|
||||
`main.rs` argument handling may use them" carve-out does not literally
|
||||
name, but the *effect* is a `Result`-returning call whose error is
|
||||
handled without panicking or unwrapping — no rule is broken; there is
|
||||
no `unwrap`/`expect`/`panic!` in this path at all.
|
||||
- All `.expect(...)`/`.unwrap()` calls introduced by the diff (checked
|
||||
with `git diff | grep`) are inside `mod tests` (`Session::batch`,
|
||||
`symbol_names`, `outcomes`, and the shutdown test's `sender.send(...)`)
|
||||
— allowed.
|
||||
- New free functions and the new `Server` methods all carry one-line-plus
|
||||
doc comments explaining what/why, consistent with the surrounding file's
|
||||
density; none of the new items are `pub`, so the strict "public items"
|
||||
rule doesn't even apply, but the dev exceeded it anyway.
|
||||
- `docs/features/cancel-request/README.md`: each of the seven required
|
||||
sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log,
|
||||
Review) appears **exactly once** (checked with `grep -n "^## "`); one
|
||||
extra explanatory section between Goal and Assumptions is additional,
|
||||
not a duplicate, and the template doesn't forbid it.
|
||||
- `TODO.md`: the §9b item's original text
|
||||
("**`$/cancelRequest`** — the loop handles requests sequentially and
|
||||
ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.") is byte-for-byte intact; only the
|
||||
checkbox flipped and a `→`-prefixed summary line was appended below it,
|
||||
which is the same pattern used by the 9 other completed items already
|
||||
in the file (`grep -c` confirms 10 occurrences total including this
|
||||
one) — not a one-off deviation.
|
||||
- `docs/features/lucisv-server/README.md` was also touched by this
|
||||
change. That file is the umbrella index every feature registers itself
|
||||
in (the method-dispatch table and the Status/TODO checklist both list
|
||||
every other feature the same way), so this is the expected cross-file
|
||||
touch the Handshakes section describes, not scope creep.
|
||||
|
||||
**Tests added this round (4 unit + 1 e2e assertion, all in the files
|
||||
already under review, no new files):**
|
||||
`is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`,
|
||||
`burst_collects_everything_already_queued_in_arrival_order`,
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`,
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(all in `crates/lucisv_server/src/server.rs`), plus a `message`-field
|
||||
assertion added to
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` in
|
||||
`crates/lucisv_server/tests/e2e.rs`. `lucisv_server` unit count moved from
|
||||
702 to 706; e2e stayed at 38 (one test grew an assertion, none added).
|
||||
|
||||
**Fixes made:** none beyond the test additions above — no corruption, no
|
||||
mishandled message, no dropped request found anywhere in the diff.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
plus two extra e2e passes (flood test green in every run I and QA made —
|
||||
twelve consecutive between us), clean. The dev's deviation from my brief
|
||||
was the right kind: my burst-drain design assumed a queue that lsp-server's
|
||||
rendezvous channels do not provide, the dev proved that over a real pipe
|
||||
(0/5 honoured) before changing anything, and the forwarder it added is
|
||||
the minimal honest fix — one thread, no shared state, stopping at
|
||||
shutdown for a reason it can cite from lsp-server's own source. QA then
|
||||
re-derived the shutdown hand-off from the vendored code rather than the
|
||||
work log, which is exactly the adversarial re-check this workflow exists
|
||||
for, and closed the four real gaps (the shutdown-shaped notification,
|
||||
bare `burst` coverage, the forwarder hand-off under a real Connection,
|
||||
and the server-id-namespace cancel).
|
||||
|
||||
The stateless cancelled-set design — a cancel matters only beside its
|
||||
request in one burst, everything else dropped on sight — is the reason
|
||||
this feature cannot leak or misfire across sessions, and shutdown
|
||||
sitting before the cancel check closes the one hole a hostile client
|
||||
could poke. On the flood test's `honoured > 0` assertion: QA is right
|
||||
that a pathological scheduler could in principle defeat it and right not
|
||||
to weaken it; the property is the point of the test, the risk is
|
||||
unreproduced in twelve runs, and if CI ever trips it the QA log already
|
||||
contains the analysis. This completes §9b. Accepted as shipped.
|
||||
@@ -0,0 +1,415 @@
|
||||
# incremental-sync
|
||||
|
||||
## Goal
|
||||
|
||||
Move the server from `TextDocumentSyncKind::FULL` to
|
||||
`TextDocumentSyncKind::INCREMENTAL`: a `didChange` now carries the ranges the
|
||||
user touched rather than the whole buffer, and the server applies them to the
|
||||
text it already holds. Full-buffer sync re-serializes, re-transfers and
|
||||
re-allocates the entire file on every keystroke, which is the wrong cost curve
|
||||
for a server that wants to answer per-keystroke (completion, signature help,
|
||||
inlay hints) — and for the editor side of a large `.sv` it is the one place
|
||||
lucisv was measurably ruder than ruff. The price of the move is that the server
|
||||
becomes the *only* holder of the buffer's text: a wrong offset here silently
|
||||
rewrites what the user is looking at, with no full-text resend to correct it.
|
||||
That is why the whole edit application is one pure function
|
||||
(`sync::apply_changes`), unit-tested against a second implementation, with no
|
||||
slice that can panic.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Positions are UTF-16, as `capabilities()` says.** Every conversion goes
|
||||
through `convert::Positions::offset`, the same function every other request
|
||||
handler uses. There is no second offset arithmetic in this feature — that is
|
||||
the point.
|
||||
- **Clamping, exactly.** A client desync (or an editor rounding a position) must
|
||||
never panic and never corrupt. The rules, all of them inherited from
|
||||
`Positions::offset` and pinned by tests in `sync.rs`:
|
||||
- a **line past the end** of the document clamps to the end of the document;
|
||||
- a **character past the end of a line's content** clamps to that content's
|
||||
end — before the line's `\n`, and before one `\r` preceding it, so an edit
|
||||
positioned past the visible end of a CRLF line cannot land between the
|
||||
`\r` and the `\n`;
|
||||
- a **character landing inside a surrogate pair** (the low half of an astral
|
||||
character such as `🎉`) **rounds forward** past the whole character. So a
|
||||
range boundary can never split a `char`, the output is always valid UTF-8,
|
||||
and an emoji is either wholly inside the replaced range or wholly outside
|
||||
it;
|
||||
- **`start > end` after conversion** clamps `end` up to `start`, which turns
|
||||
the change into a pure insertion at `start`. There is no resync mechanism
|
||||
in LSP short of the client closing and reopening the buffer, so the safe
|
||||
direction is the one that deletes nothing: a user can undo an unexpected
|
||||
insertion, but cannot recover text the server threw away.
|
||||
- **Each change is positioned against the document the previous changes in the
|
||||
same notification left.** This is what the protocol says, and it is why the
|
||||
line table is rebuilt per change rather than once per notification.
|
||||
- **A change with no `range` replaces the whole document**, mid-batch included,
|
||||
and resets the state the ranges after it are positioned against. A batch of
|
||||
rangeless changes therefore still ends at the last one — the pre-existing
|
||||
full-sync behavior, kept for a client that ignores the new capability.
|
||||
- **An empty `contentChanges` array is not a change**: nothing is reparsed and
|
||||
the generation counter does not move, exactly as before (the old handler's
|
||||
`next_back()` on an empty list did nothing).
|
||||
- **A `didChange` for a buffer that was never opened** is out of protocol, but
|
||||
is still taken rather than dropped: the base text is `""`, so a full-text
|
||||
change lands exactly as it did before this feature, and a ranged change
|
||||
clamps to an insertion at the start. No special case, no error path.
|
||||
- **`O(changes × file)` per notification, honestly.** Every ranged change
|
||||
builds a fresh `LineIndex` over the current text and allocates a new `String`.
|
||||
For the batch sizes editors actually send (1–5 ranges) over Verilog files
|
||||
this is microseconds, and it buys a function with no incremental state that
|
||||
can fall out of step with the text. A rope or an incrementally-patched line
|
||||
table is the optimization to reach for if a profile ever asks; TODO.md §6
|
||||
already defers that whole class of work.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `convert::Positions::offset`** (`crates/lucisv_server/src/convert.rs`)
|
||||
for every position→byte conversion, and `vlog_parser::LineIndex` to build it.
|
||||
Nothing was changed in either — the clamping this feature depends on is the
|
||||
clamping those already documented and tested.
|
||||
- **Promises `Server::set_document` is still called exactly once per
|
||||
`didChange` notification.** `set_document` bumps `self.generation`, which is
|
||||
the whole `resultId` of `docs/features/pull-diagnostics/README.md`; a bump
|
||||
per *range* would make one keystroke look like several to a pulling client,
|
||||
and no bump would let a changed buffer answer "unchanged". One notification =
|
||||
one reparse = one stamp = one `publish`. Pinned by
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
- **Changes what the client is told at `initialize`.**
|
||||
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
|
||||
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
|
||||
`save` values are not new behavior: they are what a bare `Kind` already
|
||||
resolved to client-side (`vscode-languageclient` expands a numeric
|
||||
`textDocumentSync` to exactly `{ openClose: true, change: <kind>, save: {
|
||||
includeText: false } }`), written out because the options form has no
|
||||
"unspecified" that means the same thing. `didSave` therefore carries no text,
|
||||
which is what it carried before — and the `DidSaveTextDocument` handler still
|
||||
adopts `params.text` if some client sends it anyway, so nothing regresses for
|
||||
a client that behaves differently.
|
||||
- **No other crate is touched.** No new dependency; the randomized test's
|
||||
generator is a five-line LCG rather than `rand`.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Advertise `TextDocumentSyncOptions` with `change: INCREMENTAL`,
|
||||
preserving the open/close and save semantics a bare `Kind` implied.
|
||||
- [x] `sync::apply_changes(text, changes) -> String` — pure, total, no
|
||||
panicking slice.
|
||||
- [x] All changes applied in order, each against the previous one's result.
|
||||
- [x] Rangeless change = whole-document replace, mid-batch included.
|
||||
- [x] Clamping rules (line past EOF, character past line end, surrogate half,
|
||||
`start > end`) defined above and tested.
|
||||
- [x] One `set_document` — one reparse, one generation bump, one publish — per
|
||||
notification.
|
||||
- [x] Unit tests: insert/delete/replace, dependent batches, multi-byte and
|
||||
astral characters, CRLF, (0,0), EOF, no trailing newline, rangeless
|
||||
mixed into a batch, every clamping rule.
|
||||
- [x] Randomized cross-check against a second implementation built on
|
||||
`char`s and lines, fixed seed, 400 cases.
|
||||
- [x] Server-level tests: incremental batch == one full change, generation
|
||||
bumps once, full-sync batch still ends at the last change, publishes
|
||||
reflect the composed text.
|
||||
- [x] e2e test driving the real binary with four ranges over two
|
||||
notifications.
|
||||
- [x] `docs/features/lucisv-server/README.md` sync/staleness text updated.
|
||||
- [x] TODO.md §9b item checked off.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-26 — dev.** Implemented the whole feature in one round.
|
||||
|
||||
- New module `crates/lucisv_server/src/sync.rs` (declared in `main.rs`), one
|
||||
public function `apply_changes(&str, &[TextDocumentContentChangeEvent]) ->
|
||||
String`. Chosen over putting it in `convert.rs`: `convert.rs` is the
|
||||
byte↔position primitive every handler shares, and this is a protocol-level
|
||||
policy (ordering, rangeless resets, desync clamping) built *on* it. Keeping
|
||||
them apart means the safety-critical policy has its own test module and its
|
||||
own reference implementation to be checked against.
|
||||
- The function is deliberately dumb: `String` in, `String` out, a fresh
|
||||
`LineIndex` per ranged change. No incremental line table, no rope, no
|
||||
reusable "document buffer" abstraction for a second user that does not
|
||||
exist. The cost is written down under Assumptions rather than optimized away.
|
||||
- **No panicking slice.** `start`/`end` come from `Positions::offset`, which
|
||||
only ever returns character boundaries, so `text[..start]` would be provably
|
||||
safe — but "provably" leans on another module's invariant, and the failure
|
||||
mode is a panic that takes the user's buffer with it. The splice uses
|
||||
`text.get(..start)` / `text.get(end..)` and skips the change if either is
|
||||
`None` (unreachable), so the function is total by construction.
|
||||
- **Clamping decisions.** Line/character clamping is inherited from
|
||||
`Positions::offset` rather than re-decided here — a second clamping rule
|
||||
would be a second set of off-by-ones. The one genuinely new decision is
|
||||
`start > end`: `end` clamps *up* to `start`, making the change an insertion.
|
||||
Rejected alternatives: dropping the change (leaves the server's text and the
|
||||
client's silently different, with no way back), and swapping the two (invents
|
||||
a deletion the client never asked for). Insertion is the only reading that
|
||||
cannot lose text.
|
||||
- **Capability.** Moved to the options form. Establishing what a bare `Kind`
|
||||
meant for save was the fiddly part: the spec leaves it to the client, and
|
||||
`vscode-languageclient` fills in `{ openClose: true, change, save: {
|
||||
includeText: false } }`. Writing those two out keeps every client on the
|
||||
behavior it had, and `includeText: false` is also the right answer on its own
|
||||
terms now — the server tracks the buffer edit by edit, so a save re-sending
|
||||
the file would be pure waste. The `didSave` handler was left alone: it still
|
||||
adopts `params.text` when present, so a client that sends text anyway is
|
||||
handled exactly as before.
|
||||
- **Handler.** `DidChangeTextDocument` reads the base text out of the workspace
|
||||
(`""` if the buffer is unknown), calls `apply_changes` once, and goes through
|
||||
the existing `set_document` + `publish` path unchanged — so the
|
||||
pull-diagnostics generation model, the `lucisv.toml` warning re-arm, and the
|
||||
push/pull gate all behave as they did.
|
||||
- **Tests: 23 unit (`sync.rs`) + 6 server-level (`server.rs`) + 1 e2e.** The
|
||||
randomized cross-check (`random_edit_sequences_agree_with_the_reference_model`)
|
||||
runs 400 sequences of 1–5 changes over random texts drawn from
|
||||
`{a, b, space, ;, \n, \r\n, é, 🎉}` — every character width, both line
|
||||
endings, and bare `\r`s — with positions deliberately allowed out of range so
|
||||
the clamping rules are exercised too. It compares against `reference_apply`,
|
||||
a flat `Vec<char>` implementation that scans its own line starts and shares
|
||||
no code with `apply_changes`, and additionally asserts that applying the
|
||||
batch in one call equals applying the changes one at a time. Seed is fixed
|
||||
(`0x5EED_1CE5`), no dependency added.
|
||||
- Deviations from the plan: none. Nothing outside `lucisv_server` was touched
|
||||
in code. Two documentation files outside this feature were annotated rather
|
||||
than rewritten, because both stated something this round made false:
|
||||
`docs/features/lucisv-server/README.md` (the "full-text sync only"
|
||||
assumption, the recompute table, and one sentence of an old QA log that read
|
||||
`textDocumentSync: 1` off the capabilities JSON) and one parenthetical in
|
||||
`docs/features/pull-diagnostics/README.md` that justified the single
|
||||
generation counter by "full-text sync ignores versions" — the conclusion
|
||||
still holds, the reason needed rewording. No QA log or Review section was
|
||||
otherwise touched.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-26 — QA.** Re-ran every gate, then attacked the six surfaces the
|
||||
lead flagged plus a few of my own. Verdict: **committable as-is**. No
|
||||
corruption, no panic, no divergence from a well-behaved client found; one
|
||||
pre-existing (not introduced by this feature) latent edge case documented
|
||||
and pinned rather than fixed, since fixing it means changing a shared
|
||||
primitive (`convert.rs`) outside this feature's scope.
|
||||
|
||||
**Gates re-run, all clean:**
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets` — clean (touched the three changed files and
|
||||
re-ran to defeat the cache; still clean).
|
||||
- `cargo test --workspace` — every crate green, 0 failed. `lucisv_server`'s
|
||||
own run: 628 lib tests (23 in `sync.rs` as claimed, plus 5 I added), 33
|
||||
e2e, 3 grammar. `cargo test -p vlog_formatter` also re-run per CLAUDE.md's
|
||||
formatter-change rule (this isn't a formatter change, but confirmed green
|
||||
anyway): 114 passed.
|
||||
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
|
||||
`smoke: OK`.
|
||||
|
||||
**1. Surrogate rounding — verified clean, direction confirmed by reading
|
||||
`convert.rs`.** `Positions::offset` (`crates/lucisv_server/src/convert.rs:39`)
|
||||
walks the line's `char`s accumulating UTF-16 units and only ever returns an
|
||||
offset it has actually reached by consuming whole `char`s (`offset += ch.
|
||||
len_utf8()` happens only together with `units += ch.len_utf16()`), so the
|
||||
returned byte offset is always the smallest character boundary whose
|
||||
cumulative UTF-16 unit count is `>= pos.character` — i.e. it always rounds
|
||||
up/forward, unconditionally, for every position (start or end). What
|
||||
"forward" *means* differs by role: for a start boundary it means the
|
||||
character is excluded (the insertion/deletion point moves past it, so the
|
||||
character survives); for an end boundary it means the character is included
|
||||
(the deletion widens to swallow it). Both are the same mechanical rule.
|
||||
Added two direct tests pinning the exact resulting string, as asked:
|
||||
`crates/lucisv_server/src/sync.rs`
|
||||
`a_deletion_starting_at_the_low_surrogate_index_preserves_the_character`
|
||||
(`edit((0,4),(0,6),"")` on `"// 🎉 ok\n"` → `"// 🎉ok\n"`, emoji survives) and
|
||||
`a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character`
|
||||
(`edit((0,3),(0,4),"")` on the same text → `"// ok\n"`, emoji consumed).
|
||||
Both pass. The dev's own two existing tests in
|
||||
`an_astral_character_takes_two_units_and_is_never_split` already hit this
|
||||
exact case (`edit((0,4),(0,6),"X")` and `edit((0,3),(0,4),"X")`) but as
|
||||
replacements, not pure deletions — the two I added close that gap with an
|
||||
empty `text`. Cross-checked against the LSP spec: positions are UTF-16
|
||||
code-unit offsets and a spec-compliant client never legitimately sends a
|
||||
mid-pair boundary, so any total, non-panicking rule is acceptable — the
|
||||
README's description ("rounds forward past the whole character") is
|
||||
accurate to the actual code, not just to the reference model.
|
||||
|
||||
**2. Divergence-from-editor risk — one real (low-severity, pre-existing)
|
||||
finding, everything else clean.**
|
||||
- **Fresh-`LineIndex`-per-change is not hoisted.** `crates/lucisv_server/src/
|
||||
sync.rs:35`, `let index = LineIndex::new(&text);`, is inside the `for
|
||||
change in changes` loop, rebuilt from the current `text` every iteration —
|
||||
confirmed by reading the code (not just trusting the comment), and then by
|
||||
actually breaking it: I temporarily hoisted the `LineIndex::new` call above
|
||||
the loop (reusing one stale index for every change) and reran `cargo test
|
||||
--bin lucisv-server sync::tests::`. Three tests failed against the stale
|
||||
index: `a_later_range_positioned_against_the_original_text_would_be_wrong`
|
||||
(panics — its own doc comment names exactly this regression),
|
||||
`a_rangeless_change_resets_what_the_next_range_is_against`, and
|
||||
`random_edit_sequences_agree_with_the_reference_model` (400/400 cases
|
||||
depend on this). `later_changes_see_what_the_earlier_ones_did` did *not*
|
||||
fail under hoisting — its three edits happen to stay valid against the
|
||||
stale index anyway, so it does not by itself pin this — but the three that
|
||||
did fail are sufficient. Reverted the hoist immediately after (confirmed
|
||||
back to 28/28 passing); no new test needed, the existing ones already pin
|
||||
this correctly.
|
||||
- **A change whose range covers the final newline** — clean. Added
|
||||
`a_change_covering_the_final_newline_removes_exactly_it`:
|
||||
`edit((1,1),(2,0),"")` on `"a\nb\n"` → `"a\nb"`. Removes exactly the
|
||||
trailing `\n`, nothing else.
|
||||
- **Adjacent zero-width ranges at the same position in one batch** — not a
|
||||
bug, and pinned as such. Added
|
||||
`zero_width_inserts_at_the_same_position_compose_in_batch_order`: two
|
||||
inserts both naming `(0,0)` on `"x"` with texts `"1"` then `"2"` produce
|
||||
`"21x"`, because each change's position is (correctly, per protocol)
|
||||
resolved against the text the previous change left — the second insert's
|
||||
literal position `0` is now *before* the first insert's text. A client
|
||||
that wants `"12"` must advance the second position past the first's
|
||||
length, same as it would for a non-zero-width range. This matches "each
|
||||
change is positioned against the document the previous changes in the
|
||||
same notification left" exactly.
|
||||
- **`\r\n` split across two changes in one batch — finding.**
|
||||
`crlf_split_across_two_changes_in_one_batch_reorders_the_bytes`
|
||||
(`crates/lucisv_server/src/sync.rs`): `apply_changes("ab", &[edit((0,2),
|
||||
(0,2), "\r"), edit((0,2),(0,2), "\n")])` produces `"ab\n\r"`, not
|
||||
`"ab\r\n"`. Root cause: `convert.rs::line_content_end`
|
||||
(`crates/lucisv_server/src/convert.rs:96`) treats a trailing bare `\r` as
|
||||
"not content" unconditionally — whether or not a `\n` will ever follow it
|
||||
— so once change 1 leaves the buffer ending in a lone `\r`, "end of line"
|
||||
for change 2 clamps to *before* that `\r`, and the `\n` lands ahead of it
|
||||
instead of after. This is **not introduced by this feature**: the rule
|
||||
lives in `convert.rs`, which predates incremental sync and is shared by
|
||||
every position-converting handler. What incremental sync newly does is
|
||||
give this quirk a path to actually rewrite the *persisted buffer* rather
|
||||
than just a hover/diagnostic range — before this feature, the server never
|
||||
computed byte offsets to build a document to save, it just accepted the
|
||||
client's already-composed text verbatim. In practice this needs a client
|
||||
to split one `\r\n` insertion into two separate ranged edits inside a
|
||||
single `didChange` batch, positioned at the exact same coordinates for
|
||||
both; no known editor's diff algorithm does this (VS Code/Neovim send
|
||||
`\r\n` as one atomic edit). No panic, no data loss (both bytes survive,
|
||||
just reordered), so it does not violate the "never corrupt" invariant in
|
||||
the "produces wrong output" sense used elsewhere in this repo (no crash,
|
||||
no truncation) but it is a genuine silent-divergence risk if a
|
||||
pathological client ever does this. Recorded and pinned rather than fixed:
|
||||
fixing it means deciding whether `line_content_end` should special-case "a
|
||||
bare trailing `\r` with nothing after it, at the very end of the buffer or
|
||||
the very end of a change-in-progress" — a `convert.rs` decision that
|
||||
affects every handler, out of this feature's stated scope
|
||||
(`sync.rs`/`main.rs`/`server.rs` only). Filed as a follow-up rather than
|
||||
redesigned here.
|
||||
- Multi-byte/astral columns (`a_ranged_change_over_multi_byte_text_edits_the_
|
||||
right_columns`, server.rs) and CRLF-on-one-line edits (`crlf_line_ends_
|
||||
survive_an_edit_on_the_line`, sync.rs) — re-verified by hand-tracing
|
||||
`Positions::offset`, both clean, no off-by-one.
|
||||
|
||||
**3. Full-sync regression — verified clean.** Diffed the old handler
|
||||
(`git show aa303ce:crates/lucisv_server/src/server.rs`, the `next_back()`
|
||||
form) against the new path:
|
||||
- *Multiple rangeless changes*: old took only the literal last element via
|
||||
`next_back()` (O(1), never touched the earlier ones); new applies all of
|
||||
them via `apply_changes`, but each rangeless change fully replaces `text`
|
||||
and continues, so the net result is identical — last one wins either way.
|
||||
Confirmed by the dev's `the_last_of_several_rangeless_changes_wins`
|
||||
(sync.rs) and `a_full_sync_clients_batch_still_lets_the_last_change_win`
|
||||
(server.rs). The new path is `O(changes)` string clones instead of `O(1)`
|
||||
for this specific case — a real but tiny and already-documented cost, not
|
||||
a correctness regression.
|
||||
- *Empty `contentChanges`*: old — `next_back()` on empty returns `None`, no
|
||||
`set_document`/no `publish`. New — explicit `if p.content_changes.
|
||||
is_empty() { return; }` before touching anything. Identical observable
|
||||
behavior; confirmed by `one_notification_is_one_generation_bump_however_
|
||||
many_ranges`'s second half (server.rs) which checks the generation counter
|
||||
does not move.
|
||||
- *Unknown/never-opened uri*: old — `set_document(uri, change.text)`
|
||||
unconditionally, no existence check. New — `self.workspace.document(&uri).
|
||||
map_or("", ...)` then `apply_changes`; for a rangeless change this reduces
|
||||
to the same `set_document(uri, change.text)`. Confirmed by `a_change_
|
||||
naming_a_buffer_that_was_never_opened_is_taken_as_written` (server.rs,
|
||||
rangeless case). I did not find a server-level test of a *ranged* change
|
||||
against a never-opened buffer, but it is exercised at the unit level
|
||||
(`an_edit_into_an_empty_document` in sync.rs, since `apply_changes` is
|
||||
handed `""` either way) and the handler code between the two cases is the
|
||||
same three lines — low-severity gap, noting rather than adding a
|
||||
redundant test.
|
||||
|
||||
**4. Capability shape — verified clean, confirmed on the actual wire, not
|
||||
just by reading the struct.** Ran the built binary directly through a
|
||||
minimal `initialize` and inspected the raw JSON response (not just the
|
||||
e2e/smoke assertions): `textDocumentSync` serialized as exactly
|
||||
`{"change":2,"openClose":true,"save":{"includeText":false}}` — no
|
||||
`willSave`/`willSaveWaitUntil` keys at all (`lsp_types::
|
||||
TextDocumentSyncOptions` marks both `#[serde(skip_serializing_if = "Option::
|
||||
is_none")]`, so `None` means genuinely absent from the wire, not `null`).
|
||||
This is exactly what `vscode-languageclient` and Neovim's builtin client
|
||||
parse as `{openClose: true, change: Incremental, save: {includeText:
|
||||
false}}`, with the will-save fields correctly unadvertised for a future
|
||||
round. `incremental_changes_are_advertised_and_applied_over_the_wire`
|
||||
(e2e.rs) asserts `sync["change"] == 2`, `sync["openClose"] == true`,
|
||||
`sync["save"]["includeText"] == false` — confirmed this really does pin the
|
||||
shape, it isn't a no-op assertion.
|
||||
|
||||
**5. Performance honesty — verified clean.** `Server::set_document`
|
||||
(`crates/lucisv_server/src/state.rs:175`, called from the `DidChangeTextDocument`
|
||||
arm exactly once per notification per the diff at `server.rs`) is the only
|
||||
place a `Document::new` (full reparse/tokens/`Semantics`) happens. Inside
|
||||
`sync::apply_changes`, only a `LineIndex::new` (a single linear scan for
|
||||
`\n` bytes, not a parse) and a `String` allocation happen per *ranged*
|
||||
change — that's the honest `O(changes × file)`, not `O(changes × file²)`
|
||||
and not a hidden per-change reparse. Confirmed by reading `state.rs:175-179`
|
||||
and by the fact that `self.generation` (bumped only inside `set_document`)
|
||||
moves exactly once per notification regardless of range count, per
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
|
||||
**6. CLAUDE.md compliance — clean.** No `unwrap`/`expect`/`panic!` in
|
||||
library code paths in `sync.rs` or the `server.rs` handler diff (`grep`
|
||||
confirms the only `expect()`s introduced are inside `#[cfg(test)]` code in
|
||||
`server.rs`, which CLAUDE.md permits). No new `#[allow]`. `sync.rs` has a
|
||||
module doc comment and `apply_changes` has a doc comment. Feature README has
|
||||
all six required sections. `TODO.md`'s §9b item text is unchanged aside from
|
||||
the checkbox and an appended implementation-summary paragraph (allowed — the
|
||||
rule is "leave the item text intact", not "add nothing"). The two annotation
|
||||
edits to `docs/features/lucisv-server/README.md` and `docs/features/
|
||||
pull-diagnostics/README.md` are both dated 2026-08-26, self-identifying
|
||||
("*(That last sentence records the state at the time of this QA pass
|
||||
only...)*", "*(Still true after incremental sync, 2026-08-26: ...)*"), and
|
||||
factual against the diff — neither rewrites the original text, both append.
|
||||
One minor nit: the original (pre-existing) `TODO.md` §9b bullet's plan text
|
||||
says "with a full-text fallback on any malformed change", but the shipped
|
||||
implementation uses clamping instead of a full-text fallback for a malformed
|
||||
change — a better and thoroughly-justified design choice (see the README's
|
||||
Assumptions and Work log), but the Work log's "Deviations from the plan:
|
||||
none" doesn't call out that the *originally-planned* mechanism changed
|
||||
between the TODO's wording and the implementation. Cosmetic — the actual
|
||||
behavior is fully and correctly documented elsewhere in the same README —
|
||||
not asking for a fix, just noting it for the record.
|
||||
|
||||
**Tests added this round** (all in `crates/lucisv_server/src/sync.rs`,
|
||||
all passing): `a_deletion_starting_at_the_low_surrogate_index_preserves_
|
||||
the_character`, `a_deletion_ending_at_the_low_surrogate_index_consumes_
|
||||
the_whole_character`, `crlf_split_across_two_changes_in_one_batch_
|
||||
reorders_the_bytes`, `a_change_covering_the_final_newline_removes_exactly_
|
||||
it`, `zero_width_inserts_at_the_same_position_compose_in_batch_order`.
|
||||
|
||||
**Verdict: committable as-is.** No dev follow-up required to ship; the
|
||||
`\r\n`-split-across-changes behavior is worth a future look if `convert.rs`
|
||||
is ever revisited, but it is pre-existing, unreachable by any known real
|
||||
client, and now pinned by a test rather than silently latent.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
|
||||
workspace suite/smoke.js myself, all clean. `apply_changes` is the right
|
||||
shape: pure, total, no panicking slice, and the fresh-line-table-per-change
|
||||
decision buys correctness with microseconds — the honest O(changes × file)
|
||||
note is exactly how this repo trades. Inheriting the clamping rules from
|
||||
`Positions::offset` instead of inventing a second set was the correct call,
|
||||
and the `start > end` → pure-insertion rule is the only reading that cannot
|
||||
lose the user's text.
|
||||
|
||||
On QA's finding (a `\r` + `\n` split across two same-position inserts in
|
||||
one batch lands as `\n\r`): accepted as pinned, not fixed. The root cause
|
||||
is `convert.rs`'s pre-existing treatment of a trailing bare `\r`, which is
|
||||
shared by every handler and out of this feature's scope; no real client
|
||||
splits a CRLF across two changes of one batch, and the behavior is now
|
||||
documented by a test rather than latent. If a cross-file `convert.rs`
|
||||
round ever opens, this goes with it. The randomized cross-check (400
|
||||
sequences against an independent model), the deliberate-breakage check
|
||||
that the line table really is rebuilt per change, and the wire-level
|
||||
capability assertion give this the confidence a sync rewrite needs.
|
||||
Accepted as shipped.
|
||||
@@ -18,10 +18,14 @@ 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/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `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 |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
@@ -39,6 +43,8 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. 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` |
|
||||
| `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` |
|
||||
| `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` |
|
||||
|
||||
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
|
||||
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
|
||||
@@ -184,23 +190,45 @@ every character boundary of a document mixing all of those.
|
||||
## State and staleness
|
||||
|
||||
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
|
||||
own) read and write stdio; this crate's loop receives one message, handles it
|
||||
to completion, and sends the response before looking at the next. No shared
|
||||
mutable state, no locks, no cancellation. Verilog files are small and every
|
||||
handler is milliseconds; the complexity of a worker pool buys nothing yet.
|
||||
own) read and write stdio; this crate's loop handles one message to completion,
|
||||
and sends the response before looking at the next. No shared mutable state, no
|
||||
locks, and nothing already running is ever interrupted. Verilog files are small
|
||||
and every handler is milliseconds; the complexity of a worker pool buys nothing
|
||||
yet.
|
||||
|
||||
**Since 2026-08-26 the loop reads in bursts** rather than strictly one message
|
||||
at a time: it blocks for the next message, takes everything already queued
|
||||
behind it without blocking, and then handles that whole burst **in arrival
|
||||
order** — a `didChange` ahead of a completion is applied before the completion
|
||||
is answered, exactly as before. The one thing the burst adds is
|
||||
`$/cancelRequest`: a request the same burst also carries a cancel for is
|
||||
answered `RequestCancelled` (-32800) instead of being computed, which is the
|
||||
only moment a one-thread server can honour a cancel at all. A cancel that
|
||||
names no request in its burst is dropped where it is read (the request was
|
||||
answered in an earlier burst, or never existed), so cancellation costs no
|
||||
state; `shutdown` is handled before any cancel is consulted and so can never
|
||||
be cancelled. Because `lsp-server`'s transport uses zero-capacity rendezvous
|
||||
channels — a client's backlog sits in the OS pipe, not on
|
||||
`connection.receiver` — the loop first forwards incoming messages onto an
|
||||
unbounded queue of its own on one small thread, which stops at `shutdown` so
|
||||
`handle_shutdown` keeps its own read of the `exit` that follows. Rules,
|
||||
reasoning and the measurements: `docs/features/cancel-request/README.md`.
|
||||
|
||||
**Two layers, invalidated by different events** — exactly the split
|
||||
`docs/features/workspace-index/README.md` designed for:
|
||||
|
||||
| layer | rebuilt when | cost |
|
||||
|---|---|---|
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
|
||||
| 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 `` `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
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there.
|
||||
deferred there. Incremental *sync* did not change that: the wire now carries
|
||||
ranges, but a `didChange` still throws the whole `Document` away and builds a
|
||||
new one — one reparse per notification, which is also the one generation bump
|
||||
the pull-diagnostics `resultId` depends on.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the roots are walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
@@ -217,6 +245,18 @@ point where the answer is expected to change anyway. Measured cost of a
|
||||
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
||||
plus the file reads.
|
||||
|
||||
**Every rescan is visible since 2026-08-26**, for a client that advertised
|
||||
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
|
||||
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
|
||||
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
|
||||
big filelist reads as work rather than as a hang. The `begin` does not wait for
|
||||
the create's answer (the rescan blocks the loop immediately after), the answer
|
||||
is ignored on the same path the watcher registrations' is, there is no
|
||||
percentage and no intermediate report — the rescan is one opaque call — and the
|
||||
`end` names the indexed file count. A client that did not advertise the
|
||||
capability is sent nothing at all, which the spec requires. Rules and the
|
||||
startup-legality argument: `docs/features/work-done-progress/README.md`.
|
||||
|
||||
**Changes made outside the editor close on the next notification, not on the
|
||||
next save** (M9, `docs/features/file-watching/README.md`). The server registers
|
||||
`workspace/didChangeWatchedFiles` for `**/*.{v,vh,sv,svh}` and for the
|
||||
@@ -240,10 +280,17 @@ not see.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Full-text document sync only.** The server advertises
|
||||
`TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and
|
||||
there is no incremental-edit application to get wrong. At Verilog file sizes
|
||||
the wire cost is irrelevant.
|
||||
- ~~**Full-text document sync only.**~~ **Superseded (incremental-sync, round
|
||||
2026-08-26).** The server advertises `TextDocumentSyncKind::INCREMENTAL`
|
||||
inside a `TextDocumentSyncOptions` (`openClose: true`,
|
||||
`save.includeText: false` — the same values a bare `Kind` resolved to
|
||||
client-side, so only `change` moved). A `didChange` now carries ranges, and
|
||||
`sync::apply_changes` applies them in order to the buffer the server holds:
|
||||
each range is positioned against what the previous ones left, a change with
|
||||
no range still replaces the whole document, and every out-of-range or
|
||||
backwards position clamps rather than panicking. The server is now the only
|
||||
holder of the buffer text, which is what makes that function's rules worth
|
||||
reading in full: `docs/features/incremental-sync/README.md`.
|
||||
- **Every document URI is a `file:` URI.** `untitled:` buffers are accepted
|
||||
and served for everything single-file (diagnostics, tokens, formatting,
|
||||
symbols), but they have no path, so they never enter the workspace index.
|
||||
@@ -380,7 +427,18 @@ Two rules that are easy to get wrong and are tested:
|
||||
three multi-line token shapes that would violate it — a block comment, a
|
||||
continued `` `define``, and a multi-line macro invocation. Every span is
|
||||
split at `\n` before encoding, and the pieces are sorted by (line, start)
|
||||
before the delta encoding runs.
|
||||
before the delta encoding runs. Single-line tokens are also what lets the
|
||||
`range` filter reason about overlap without looking at the text at all.
|
||||
|
||||
Since 2026-08-26 that classification feeds three requests, not one: the pass
|
||||
produces an intermediate **absolute** form (line, column, length, type,
|
||||
modifiers), `range` filters it, and one pure encoder delta-encodes whatever is
|
||||
left — from the start of the document in every case, so a range answer stands
|
||||
on its own. The `resultId` bookkeeping that makes `full/delta` possible lives
|
||||
in `server.rs` (one counter, one remembered answer per open buffer, dropped on
|
||||
`didClose`), because `tokens.rs` owns no state. Rules, the prefix/suffix
|
||||
overlap trap and the round-trip property:
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
|
||||
## Hover, and the order it tries things
|
||||
|
||||
@@ -444,7 +502,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
|
||||
- [x] `textDocument/formatting`.
|
||||
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
|
||||
- [x] `textDocument/semanticTokens/full`.
|
||||
- [x] `textDocument/semanticTokens/full`, joined by `/range` and `/full/delta`
|
||||
(2026-08-26) — one tokenizer and one encoder behind all three, plus a
|
||||
per-buffer `resultId` dropped on `didClose`.
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
- [x] `textDocument/hover`.
|
||||
- [x] `textDocument/definition`.
|
||||
- [x] `textDocument/references`.
|
||||
@@ -497,6 +558,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`docs/features/hierarchy/README.md`.
|
||||
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
|
||||
`docs/features/macro-expansion/README.md`.
|
||||
- [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26,
|
||||
completing TODO.md §9b): the loop reads in bursts and answers a queued
|
||||
request whose cancel is in the same burst with `RequestCancelled`,
|
||||
order across the burst unchanged. `docs/features/cancel-request/README.md`.
|
||||
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
||||
`lspconfig` snippet are their own TODO.md §6 item).
|
||||
|
||||
@@ -772,7 +837,10 @@ character-past-end-of-line, line-past-end-of-file, and both-past-end → all
|
||||
six combinations return graceful `null`/`[]`, no protocol error, no crash;
|
||||
server process survived and later exited cleanly (code 0). `textDocumentSync`
|
||||
confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping
|
||||
`didChange`" scenario is moot as documented.
|
||||
`didChange`" scenario is moot as documented. *(That last sentence records the
|
||||
state at the time of this QA pass only: sync became incremental on
|
||||
2026-08-26, and the clamping that keeps a desynced `didChange` harmless is
|
||||
specified and tested in `docs/features/incremental-sync/README.md`.)*
|
||||
|
||||
**Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and
|
||||
a well-framed-but-garbage JSON body → in both cases the process does **not**
|
||||
|
||||
@@ -36,9 +36,12 @@ of squiggles for one file is the classic way to ship this feature wrong.
|
||||
full report — a cheap, correct answer. The error the coarse direction
|
||||
cannot make is the expensive one: a stale `unchanged` is a wrong squiggle
|
||||
left on screen. (The brief suggested `generation/doc-version`; the server
|
||||
does not track document versions at all — full-text sync ignores them — so
|
||||
does not track document versions at all — the sync path ignores them — so
|
||||
the second half would have been a constant. One number, documented, beats a
|
||||
format that implies a precision that is not there.)
|
||||
format that implies a precision that is not there.) *(Still true after
|
||||
incremental sync, 2026-08-26: `DidChangeTextDocumentParams.version` is
|
||||
unread, and one notification is still exactly one generation bump however
|
||||
many ranges it carried.)*
|
||||
- **`inter_file_dependencies: true` is honest.** A save rebuilds the
|
||||
workspace index, and a buffer's diagnostics are computed against that index
|
||||
(`resolve_external` in `state.rs`), so a save in file A really can change
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
# semantic-tokens-delta
|
||||
|
||||
## Goal
|
||||
|
||||
Serve the two semantic-token requests this server advertised nothing for:
|
||||
`textDocument/semanticTokens/range`, so the first paint of a large file costs
|
||||
the visible lines rather than the whole file, and
|
||||
`textDocument/semanticTokens/full/delta`, so a client that already holds an
|
||||
answer is told what *changed* instead of being handed the file's whole token
|
||||
set on every keystroke (TODO.md §9b). Both are the same tokenizer that already
|
||||
served `full`: the classification pass now produces an intermediate
|
||||
**absolute** form — line, column, length, type, modifiers — a range answer
|
||||
filters that form and the one encoder delta-encodes whatever is left, so the
|
||||
three requests cannot disagree about what a token is. The delta itself is the
|
||||
standard prefix/suffix trim rust-analyzer uses, with the one invariant that
|
||||
matters tested as a property: applying the returned edits to the old data
|
||||
reproduces the new data exactly.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A range answer is a self-contained `SemanticTokens`, not a slice of the
|
||||
full one.** The relative encoding restarts from the start of the *document*
|
||||
exactly as a full answer's does; only the tokens outside the range are
|
||||
missing. So the first kept token's `deltaLine`/`deltaStart` are absolute,
|
||||
which is why the encoder had to be split out of the classifier rather than
|
||||
the range answer being a sub-slice of the full one. (A client that pasted a
|
||||
slice out of a full answer would draw line 40's tokens on line 0 — pinned by
|
||||
`a_range_answer_re_encodes_from_the_start_of_the_document`.)
|
||||
- **A token that only overlaps the range is kept whole.** The client asked
|
||||
which tokens to draw, not where to cut them, and a `length` trimmed to the
|
||||
range would be a lie about the source. Tokens are single-line by
|
||||
construction (every span is split at `\n` before encoding — the rule
|
||||
`no_token_ever_spans_a_line_break` has pinned since the first round), so
|
||||
"overlap" never has to reason across lines.
|
||||
- **An empty range answers nothing.** A zero-width range covers no characters,
|
||||
so nothing intersects it. Without the explicit guard the overlap test
|
||||
degenerates into *containment* and a collapsed cursor position would answer
|
||||
with the token it sits inside — tokens the client has no room to draw. No
|
||||
editor is known to send one; it is guarded because the arithmetic invites it.
|
||||
- **`resultId`s are minted per answer, from one counter, and are not the
|
||||
diagnostics generation.** A `previousResultId` must name the exact data the
|
||||
client holds, which the pull-diagnostics generation cannot do: that one is
|
||||
bumped by a buffer change *and* by an index rebuild, and it is shared by
|
||||
every open buffer. This counter counts *answers* — one per full and per
|
||||
delta, whatever the buffer — so an id is unambiguous and never reused.
|
||||
Answering the same unchanged buffer twice mints two ids and one empty edit
|
||||
list; that is a string per answer, not a recomputation.
|
||||
- **A range answer is deliberately *not* remembered and carries no
|
||||
`resultId`.** It is a partial view; a later delta computed against it would
|
||||
be a diff against something the client never held whole. Only `full` and
|
||||
`full/delta` write the remembered answer.
|
||||
- **One answer per buffer is remembered, and it dies with the buffer.** A
|
||||
client that asks again has moved on from the previous answer, so there is no
|
||||
history to keep. `didClose` drops the entry, so the map is bounded by the
|
||||
number of *open* buffers, not by the number of files ever opened. A delta
|
||||
naming an id from before a close is answered in full.
|
||||
- **Mismatched, absent or stale `previousResultId` → a full answer.**
|
||||
`SemanticTokensFullDeltaResult` allows either, and a delta against data we
|
||||
cannot see would be a guess. That is also what makes a server restart, a
|
||||
client restart and a `didClose`/`didOpen` cycle all self-healing.
|
||||
- **Minimality beyond the prefix/suffix trim is not attempted.** One
|
||||
`SemanticTokensEdit` replaces everything between the common prefix and the
|
||||
common suffix. A real diff would describe an insertion in the middle of a
|
||||
file as two small edits, but the encoding is *relative*: the first token
|
||||
after an inserted line carries a changed `deltaLine`, so a "middle"
|
||||
insertion already invalidates only that one token plus the ones that moved,
|
||||
and everything below it re-matches as suffix. rust-analyzer answers the same
|
||||
way. The payload is what the client re-parses, not what it re-renders.
|
||||
- **The buffer that does not lex still round-trips.** It has no tokens at all
|
||||
(the lexer is all-or-nothing), so a delta out of it deletes everything and a
|
||||
delta back into it inserts everything. Mid-keystroke this is the common
|
||||
case, and it is tested in both directions.
|
||||
- **`workspace/semanticTokens/refresh` is out of scope and not sent.** That
|
||||
request exists for the case where the *server* decides the client's tokens
|
||||
went stale without the client having edited anything — an index rebuild
|
||||
changing how a name resolves, say. The case that matters (the user typing)
|
||||
makes the client re-pull on its own. Recorded as backlog below, not built.
|
||||
|
||||
## The delta algorithm, and the bug it is easy to write
|
||||
|
||||
```
|
||||
prefix = how many leading tokens are equal
|
||||
old_rest, new_rest = both lists past the prefix
|
||||
suffix = how many trailing tokens of old_rest and new_rest are equal
|
||||
edit = replace old_rest[..old_rest.len() - suffix]
|
||||
with new_rest[..new_rest.len() - suffix]
|
||||
```
|
||||
|
||||
**The suffix is counted over what the prefix left, never over the whole
|
||||
lists.** That is the cap, and skipping it is *the* classic bug in this
|
||||
algorithm: when the two token lists repeat themselves, a suffix counted over
|
||||
the whole lists claims tokens the prefix has already claimed, and
|
||||
`new_rest[..new_rest.len() - suffix]` then runs backwards — a panic in debug,
|
||||
an edit that deletes a region it also re-inserts in the general case.
|
||||
|
||||
This is not hypothetical for Verilog. The encoding is relative, so **identical
|
||||
lines encode to identical tokens**: line 2 and line 3 of
|
||||
|
||||
```systemverilog
|
||||
module m;
|
||||
wire a;
|
||||
wire a;
|
||||
wire a;
|
||||
endmodule
|
||||
```
|
||||
|
||||
are byte-for-byte the same five numbers. Deleting one of those lines is
|
||||
exactly the `old = [A, B, A]`, `new = [A]` shape. Both the hand-built shape and
|
||||
the real-Verilog one are tested (`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`), and both were
|
||||
confirmed to **fail** — by panic — against a deliberately uncapped
|
||||
implementation before being committed to.
|
||||
|
||||
**`start` and `deleteCount` count numbers, not tokens.** The wire carries a
|
||||
flat `u32` array of five numbers per token, and an edit indexes *that*. Both
|
||||
are five times a token index (`FIELDS`), pinned by
|
||||
`an_edits_indices_count_numbers_and_not_tokens` — the off-by-five here does not
|
||||
fail loudly, it silently corrupts a client's cache.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `lsp-types` (0.97, no new dependency):**
|
||||
`SemanticTokensRangeParams`, `SemanticTokensRangeResult`,
|
||||
`SemanticTokensDeltaParams`, `SemanticTokensFullDeltaResult`,
|
||||
`SemanticTokensDelta`, `SemanticTokensEdit`, and — for the capability —
|
||||
`SemanticTokensOptions { range: Option<bool>, full: Option<SemanticTokensFullOptions> }`
|
||||
with `SemanticTokensFullOptions::Delta { delta: Some(true) }`. The `Delta`
|
||||
variant is the full capability *plus* deltas, not a replacement:
|
||||
`semanticTokens/full` is still served and still answered.
|
||||
|
||||
**Consumed from other crates: nothing new.** `vlog_parser`, `vlog_semantic`,
|
||||
`vlog_formatter`, `vlog_refactor`, `lucisv_core` are untouched, as is every
|
||||
file outside `crates/lucisv_server`. This feature is protocol arithmetic over a
|
||||
classification that already existed.
|
||||
|
||||
**Changed inside this crate, for whoever reads `tokens.rs` next:**
|
||||
|
||||
- `tokens::semantic_tokens(doc)` now returns `Vec<SemanticToken>` (the `data`)
|
||||
rather than a whole `SemanticTokens`. The `resultId` is the server's to
|
||||
stamp, because only the server knows what it remembered — the module owns
|
||||
no state.
|
||||
- New: `tokens::semantic_tokens_in_range(doc, range) -> Vec<SemanticToken>`
|
||||
and `tokens::delta(old, new) -> Vec<SemanticTokensEdit>`.
|
||||
- Private and new: `Absolute` (line, start, length, type, modifiers),
|
||||
`absolute(doc)`, `flatten(pieces, doc)`, `within(tokens, range)`,
|
||||
`encode(&[Absolute])`. `encode` is pure — the same tokens always encode the
|
||||
same way, whether they are the whole file's or the handful a range kept —
|
||||
which is what lets `full` and `range` share it.
|
||||
- `Server` gains `tokens: HashMap<Uri, TokenAnswer>` and `token_results: u64`,
|
||||
written only by `remember_tokens` and cleared only by `didClose`. **Neither
|
||||
touches `generation`**: every token request is read-only, and bumping the
|
||||
diagnostics generation on a viewport repaint would throw away a pulling
|
||||
client's whole diagnostic cache several times a second
|
||||
(`no_token_request_bumps_the_diagnostics_generation`).
|
||||
|
||||
**Requested of other modules:** nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `tokens.rs` split into classification → `Absolute` → filter → `encode`,
|
||||
with `full` and `range` sharing all four steps.
|
||||
- [x] `textDocument/semanticTokens/range`, advertised as `range: Some(true)`,
|
||||
re-encoded from the document start, overlap kept whole, empty range
|
||||
empty.
|
||||
- [x] `textDocument/semanticTokens/full/delta`, advertised as
|
||||
`full: Delta { delta: Some(true) }`, single-edit prefix/suffix diff with
|
||||
the suffix capped.
|
||||
- [x] Per-buffer `resultId` bookkeeping: minted per answer, stored by both
|
||||
`full` and `full/delta`, dropped on `didClose`.
|
||||
- [x] `semanticTokens/full` returns a `resultId` now (it did not before), so a
|
||||
client may mix the two requests.
|
||||
- [x] Round-trip property tests: append, delete, middle change, identical,
|
||||
complete replacement, unlexable buffer both ways, empty buffer both
|
||||
ways, the prefix/suffix-overlap shapes, and a 300-iteration fixed-seed
|
||||
randomized sweep over real Verilog buffers.
|
||||
- [x] Range/full agreement as a property over two corpus files, in 40-line
|
||||
windows (the size of an editor viewport request), stated line-wise so it
|
||||
is independent of the handler's own overlap test.
|
||||
- [x] Server-level tests through the `Session` harness, and one e2e round trip
|
||||
through the real binary.
|
||||
- [x] TODO.md §9b box, this README, and the `lucisv-server` capability table.
|
||||
- [ ] **Not done, deliberately:** `workspace/semanticTokens/refresh`. Nothing
|
||||
the server learns on its own (an index rebuild changing how a name
|
||||
resolves) currently invalidates a client's token cache; when something
|
||||
does, this is the request to send.
|
||||
- [ ] **Not done:** partial results / `workDoneProgress` on any of the three
|
||||
requests. The whole-file answer is sub-millisecond at Verilog file
|
||||
sizes; streaming it in chunks would be complexity for nobody.
|
||||
- [ ] **Not measured:** whether the delta payload is actually smaller than the
|
||||
full one for a typical edit. It must be by construction for an edit near
|
||||
either end of a file, and it is at worst the full set plus one edit
|
||||
header for an edit near the middle. No benchmark was written.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Read first**: `CLAUDE.md`, `docs/features/lucisv-server/README.md` (the
|
||||
capability table and the `semanticTokens` mapping section),
|
||||
`docs/features/pull-diagnostics/README.md` for the house style on result
|
||||
ids, `tokens.rs` in full, and `lsp-types` 0.97's `semantic_tokens.rs` for
|
||||
the exact shapes (`range` is a plain `Option<bool>` there, not an options
|
||||
struct; `SemanticTokensFullDeltaResult` has three variants and we use two).
|
||||
- **The refactor came before either handler.** `semantic_tokens` was one
|
||||
function doing classification, line splitting, sorting and delta encoding,
|
||||
and the range answer needs to cut in between the third and the fourth. It
|
||||
is now `absolute(doc)` (classify + split + sort, producing `Absolute`),
|
||||
`within(tokens, range)` (the filter) and `encode(&[Absolute])` (pure delta
|
||||
encoding). The eleven pre-existing token tests were left with their
|
||||
assertions untouched — only the test *helpers* moved, because
|
||||
`semantic_tokens` now hands back the `data` rather than a `SemanticTokens`
|
||||
— which is the evidence that the factoring changed no behavior.
|
||||
- **The overlap cap was verified by breaking it, not by reasoning.** After
|
||||
writing the capped `delta`, the suffix computation was temporarily changed
|
||||
to count over the whole lists and the suite re-run: three tests failed with
|
||||
a subtraction-overflow panic
|
||||
(`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` via the shared
|
||||
round-trip helper, and `every_pair_of_real_buffers_round_trips_through_its_delta`
|
||||
— the randomized sweep found it on its own, which is why the `BODY` line
|
||||
pool deliberately repeats `" wire a;"`). The implementation was then
|
||||
restored. CLAUDE.md's invariant #4 is about `verify.rs`, but its spirit —
|
||||
a normalization ships with the attack that would forgive a corruption —
|
||||
is what this check is.
|
||||
- **The one design decision that is not the obvious one**: a range answer
|
||||
carries no `resultId` and is not remembered. It would have been one line to
|
||||
remember it, and it would have silently made the next delta a diff against
|
||||
a partial view. Written down in Assumptions and pinned by
|
||||
`a_range_request_is_not_the_answer_a_later_delta_is_computed_against`.
|
||||
- **The empty-range guard was written for the arithmetic, not for a client.**
|
||||
`from < range.end && range.start < to` is the interval-overlap test only
|
||||
when the range is non-empty; for a collapsed range it is containment. One
|
||||
early return, one test, one sentence in Assumptions.
|
||||
- **`generation` was deliberately not touched**, and the test for it says so
|
||||
twice: directly on the field, and observably through a pull that is still
|
||||
`unchanged` after a token request. Pull diagnostics' README asks every new
|
||||
feature to audit whether it bumps the generation; the audit's answer here
|
||||
is no, and this is where it is recorded.
|
||||
- **Nothing outside this crate moved.** No new dependency, no version bump,
|
||||
no engine change, no `editors/` change (`smoke.js`'s capability list already
|
||||
contains `semanticTokensProvider`, and it passes against the built binary).
|
||||
- **Results.** `cargo test --workspace`: **1793 passed, 0 failed** (1764
|
||||
before — +29: 18 unit tests in `tokens.rs`, 9 in `server.rs`, 1 in
|
||||
`main.rs`, 1 e2e). `cargo clippy --all-targets`: silent.
|
||||
`cargo fmt --all -- --check`: clean. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: OK. No commits.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates re-run, from a clean rebuild** (`touch`ed the three changed source
|
||||
files first so clippy could not reuse a stale cached pass):
|
||||
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace
|
||||
-- -D warnings`: silent. `cargo test --workspace`: **1793 passed, 0 failed**
|
||||
before QA's own additions, **1802 passed, 0 failed** after (9 QA tests added,
|
||||
see below). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK. All match the dev's claims.
|
||||
|
||||
**1. The delta invariant, independently — verified clean, tests added.**
|
||||
Wrote a second applier, `independent_apply` (`tokens.rs`, in `mod tests`),
|
||||
that shares no code with the dev's `apply_edits`: it walks `SemanticToken`s
|
||||
rather than the flat `u32` array, slices by hand (`extend_from_slice`)
|
||||
rather than calling `Vec::splice`, and separately asserts `edit.start` /
|
||||
`edit.delete_count` divide evenly by `FIELDS` — a second, independent check
|
||||
of the ×5 claim. Cross-checked the two appliers directly against each other
|
||||
over 200 random pairs (`qa_the_two_independently_written_appliers_never_disagree`)
|
||||
— **they never disagreed**. Ran QA's applier over: both ends changing at
|
||||
once, middle-only, identical, complete replacement, old empty, new empty,
|
||||
and a single-token file, both directions
|
||||
(`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`).
|
||||
Ran a second randomized sweep, different generator (xorshift64, not the
|
||||
dev's LCG), different seed (`0xDEAD_BEEF_1234_5678` vs `0x5eed`), and a
|
||||
different line pool that adds a block comment spanning lines, a continued
|
||||
`` `define``, and a `generate`/`endgenerate` block — pieces whose token
|
||||
*count* is not simply one-line-in-N-tokens-out
|
||||
(`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`).
|
||||
All green. **Verdict: verified clean.**
|
||||
|
||||
**2. The overlap cap, re-verified — reproduced, with one correction to the
|
||||
work log's specifics.** Reproduced the dev's breakage myself: changed the
|
||||
suffix computation in `delta` (`tokens.rs:304-305` at the time) from
|
||||
counting over `old_rest`/`new_rest` to counting over the whole `old`/`new`,
|
||||
re-ran `cargo test -p lucisv_server`, and restored it — the file is back to
|
||||
its pre-experiment text (diffed against git to confirm no leftover debug
|
||||
code). Result: **10 tests failed** by `attempt to subtract with overflow`
|
||||
panic, including `the_suffix_is_capped_so_it_cannot_overlap_the_prefix`, the
|
||||
dev's own sweep `every_pair_of_real_buffers_round_trips_through_its_delta`,
|
||||
and — usefully — all of QA's own new round-trip tests from surface 1 above,
|
||||
which is exactly the cross-check CLAUDE.md invariant #4 asks for (an
|
||||
independently-written attack finding the same class of bug). **One
|
||||
correction**: the work log names
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` as one of the
|
||||
three tests that failed in the dev's own experiment. Re-running the same
|
||||
breakage, this specific test **passes** — traced with a temporary debug
|
||||
print (`old.len()=9 new.len()=5 prefix=4 suffix=1` and the mirror), the
|
||||
type/declaration-modifier mismatch a few tokens in breaks the naive
|
||||
whole-list suffix match before it ever grows past `old_rest`'s length, so no
|
||||
overflow occurs for this particular buffer pair under this literal
|
||||
interpretation of "count over the whole lists." This is a documentation
|
||||
accuracy nit, not a safety finding — the class of bug is still real and
|
||||
still demonstrated by the other two named tests plus QA's own — but the dev
|
||||
should either soften the claim (the failure was seen at the time, with
|
||||
whatever the code looked like then, or via a different breakage) or drop
|
||||
that one test's name from the sentence. **Then tried to construct a shape
|
||||
that defeats the capped implementation and produces wrong data instead of a
|
||||
panic**: with the cap in place, `suffix = old_rest.iter().rev().zip(new_rest.iter().rev())…`
|
||||
is inherently bounded by `min(old_rest.len(), new_rest.len())` because
|
||||
`Iterator::zip` itself stops at the shorter side — so `deleted =
|
||||
old_rest.len() - suffix` can never underflow, and the algebra (`old[:prefix]
|
||||
+ inserted + old_rest[deleted..]` reduces to exactly `new`) holds
|
||||
unconditionally, not just on the tested shapes. Tried anyway: long shared
|
||||
prefix and long shared suffix overlapping in the middle over periodic data
|
||||
(the `[A,A,A,A,A]` → `[A,A,A]` shape, and variants with the periodic run at
|
||||
different positions) — all round-trip correctly, consistent with the
|
||||
argument above. **Verdict: verified clean; the cap is load-bearing (10
|
||||
failures without it) and, with it, the round-trip property holds by
|
||||
construction, not merely on the cases anyone thought to test.**
|
||||
|
||||
**3. u32 semantics — verified clean.** `an_edits_indices_count_numbers_and_not_tokens`
|
||||
(dev's) and QA's own `independent_apply` (which asserts `% FIELDS == 0`
|
||||
before dividing, on every edit, in every test above, including the 500
|
||||
combined sweep iterations) agree the ×5 conversion is exact and consistently
|
||||
applied. Wire shape: an unchanged buffer answers `edits: []` (present, empty
|
||||
— `a_delta_over_an_unchanged_buffer_is_an_empty_edit_list`,
|
||||
`server.rs:2508`) and a stale/unknown/absent-state id answers the
|
||||
`Tokens` variant with no `edits` key at all
|
||||
(`a_delta_naming_an_id_we_do_not_hold_is_answered_in_full`) — both legal per
|
||||
`SemanticTokensFullDeltaResult`'s untagged enum, and both are pinned by
|
||||
existing tests, not left to accident.
|
||||
|
||||
**4. Range self-containment — verified clean, gaps closed with new tests.**
|
||||
The dev covered: full-document range, absolute first-token deltas, overlap
|
||||
kept whole at the *start* boundary, empty range, whitespace-only *lines*,
|
||||
range never leaking outside tokens, and a 40-line-window corpus sweep (which
|
||||
QA re-ran directly against the checked-out `corpus/` — genuinely exercised,
|
||||
not skipped: `windows_checked` well over 20). QA added the three shapes the
|
||||
list asked for that were not yet pinned: (a) overlap kept whole at the *end*
|
||||
boundary, mirroring the dev's start-boundary test
|
||||
(`qa_a_range_ending_mid_token_keeps_that_token_whole`); (b) a range on a line
|
||||
*with* tokens, covering only the whitespace (plus an unemitted `=`) between
|
||||
two of them — not an empty line
|
||||
(`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`);
|
||||
(c) a reversed range (`start > end`) — `within`'s guard
|
||||
(`range.start >= range.end`) is symmetric to this by construction since
|
||||
`Position` derives `Ord` over `(line, character)` lexicographically, so this
|
||||
was already total and already answered empty, but nothing pinned it before
|
||||
now (`qa_a_reversed_range_is_total_and_answers_nothing`). All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**5. State lifecycle — verified clean, two gaps closed with new tests.** The
|
||||
dev covered: didClose+reopen with the old id → full, memory dropped on
|
||||
close (`server.rs:784`, `self.tokens.remove(&uri)`, confirmed keyed by
|
||||
`Uri` and removed, not just marked stale), and the unopened-buffer → null
|
||||
convention for all three request kinds
|
||||
(`every_token_request_for_a_buffer_that_is_not_open_answers_null`, which
|
||||
also asserts the map stays empty). QA added: (a) two buffers open at once,
|
||||
buffer A's id presented to buffer B — answered in full, not edits computed
|
||||
against A's data, and closing A leaves B's own remembered state untouched
|
||||
(`qa_two_open_buffers_ids_do_not_cross_contaminate`); worth noting as a
|
||||
observation rather than a bug: presenting a foreign id to B *does* mint a
|
||||
fresh id for B and overwrite B's own remembered answer (every answer does,
|
||||
by design — "Answering the same unchanged buffer twice mints two ids"), so
|
||||
the first version of this test asserted something the design doesn't
|
||||
promise (that `id_b` keeps working) — fixed once understood, noted here so
|
||||
the next reader doesn't trip on the same assumption. (b) `full → delta →
|
||||
full → delta → full` stays consistent across three edits
|
||||
(`qa_full_delta_full_delta_stays_consistent_across_edits`), and separately,
|
||||
a `full/delta` answer's *own* `resultId` chains directly into the next delta
|
||||
without ever going back through `full`
|
||||
(`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`)
|
||||
— checked against `ground_truth`, a helper that reads the document straight
|
||||
through `tokens::semantic_tokens` and bypasses the request dispatch (and
|
||||
thus the very `tokens`/`token_results` bookkeeping under test) entirely, so
|
||||
the check does not depend on the server's own memory being right. All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**6. No behavior change for existing clients — verified clean, two ways.**
|
||||
(a) Direct code comparison: `classify`, `modifiers`, `identifier_type`,
|
||||
`symbol_type`, `collect_trivia`, `split_lines`, `token_types` and
|
||||
`token_modifiers` are byte-for-byte identical between
|
||||
`git show 80b9afd:crates/lucisv_server/src/tokens.rs` and the new file; the
|
||||
new `flatten`+`encode` pair is the old single `encode` function split at
|
||||
exactly the line-splitting/sorting boundary, with no logic added or
|
||||
removed. (b) Empirical, at the binary level: built the pre-refactor commit
|
||||
in a separate worktree (`git worktree add`, removed after), drove both the
|
||||
old and the new `lucisv-server` binaries over stdio with the same
|
||||
`textDocument/semanticTokens/full` request against a real corpus file
|
||||
(`corpus/picorv32/picorv32.v`, 41,325 tokens), and diffed the `data` arrays:
|
||||
**byte-for-byte identical**; the only difference in the response is the new
|
||||
`resultId` field, which the old binary did not send at all. The legend
|
||||
(`token_types`/`token_modifiers`) is likewise unchanged (confirmed both by
|
||||
the code diff and by `the_semantic_token_capability_asks_for_ranges_and_for_deltas`
|
||||
asserting length 14). **Verdict: verified clean — this is about as strong
|
||||
as evidence gets for "the refactor changed no behavior."**
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.** `grep`-checked all non-test
|
||||
code in `tokens.rs`, `server.rs`, `main.rs` for `.unwrap()`, `.expect(`,
|
||||
`panic!`: none. No `#[allow]` added anywhere in the diff. No `unsafe`
|
||||
anywhere in the diff. The two new public functions
|
||||
(`semantic_tokens_in_range`, `delta`) both carry doc comments explaining
|
||||
what/why. The feature README has each of the six required sections exactly
|
||||
once (plus one extra, non-required "The delta algorithm…" section, which is
|
||||
additive and not a substitute for any required one). `TODO.md`'s item text
|
||||
is unchanged save the checkbox and an appended `→` summary — the original
|
||||
sentence is intact verbatim.
|
||||
|
||||
**Fixes made directly (small, per the QA remit):** none needed in the
|
||||
dev's own code — every finding above was either "verified clean" or a
|
||||
documentation-accuracy nit (item 2) recorded rather than edited, since
|
||||
CLAUDE.md reserves the Work log for the dev agent's own account of what it
|
||||
did and why, and the specific breakage the dev saw is not reproducible
|
||||
after the fact to know which description would be truer. QA did fix one bug
|
||||
in **QA's own** first draft of `qa_two_open_buffers_ids_do_not_cross_contaminate`
|
||||
(a wrong assumption about `id_b` surviving a cross-request, see item 5)
|
||||
before it ever reached this log.
|
||||
|
||||
**Tests added this round:** 9, all passing, workspace total 1793 → 1802.
|
||||
`tokens.rs`: `qa_the_two_independently_written_appliers_never_disagree`,
|
||||
`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`,
|
||||
`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`,
|
||||
`qa_a_range_ending_mid_token_keeps_that_token_whole`,
|
||||
`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`,
|
||||
`qa_a_reversed_range_is_total_and_answers_nothing`. `server.rs`:
|
||||
`qa_two_open_buffers_ids_do_not_cross_contaminate`,
|
||||
`qa_full_delta_full_delta_stays_consistent_across_edits`,
|
||||
`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`.
|
||||
|
||||
**Overall verdict: committable as-is.** No corruption, non-idempotency,
|
||||
dropped-comment, or safety-net-widening risk found — this feature does not
|
||||
touch `verify.rs`, the formatter, or anything outside `crates/lucisv_server`,
|
||||
and every claim in the dev's work log checked out except the one test name
|
||||
in item 2, which is cosmetic. All gates green, all new and old tests green,
|
||||
one empirical binary-level spot check green.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1802 workspace tests, 0 failed), clean. The refactor is the right seam:
|
||||
one tokenizer, one pure encoder, and range/full provably cannot drift —
|
||||
QA's byte-for-byte comparison of a 41k-token corpus file against the
|
||||
pre-refactor binary is the strongest possible form of "the factoring
|
||||
changed nothing". The delta design's judgment calls are all correct:
|
||||
range answers carrying no resultId (a delta must never diff against a
|
||||
partial view), a per-answer counter separate from the shared diagnostics
|
||||
generation, and prefix/suffix-with-cap over anything cleverer — with the
|
||||
round-trip property, not minimality, as the contract.
|
||||
|
||||
Two QA results deserve the record: the two independently written edit
|
||||
appliers never disagreed across 200 random pairs, and the overlap cap was
|
||||
broken on purpose twice (dev and QA separately) with the suite catching
|
||||
it both times. One cosmetic correction accepted from the QA log: the work
|
||||
log names `repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`
|
||||
among the tests that fail with the cap reverted; QA's re-run shows that
|
||||
particular pair breaks the match earlier and that test passes — the trap
|
||||
is real but is caught by the other ten failures. The work log stands as
|
||||
the dev's account, with the QA log as the precise version. Accepted as
|
||||
shipped.
|
||||
@@ -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<bool>`.** 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<bool>`
|
||||
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<Uri>`) 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.
|
||||
@@ -0,0 +1,383 @@
|
||||
# work-done-progress
|
||||
|
||||
## Goal
|
||||
|
||||
A workspace rescan is the one thing this server does that a user can feel.
|
||||
`Server::reindex()` is a synchronous full re-walk of the roots — 0.68 s for the
|
||||
860-file corpus, seconds for a real filelist — and it runs on every save, on
|
||||
every watched-file notification, and whenever `lucisv.exclude`/`lucisv.filelist`
|
||||
changes. Until now it happened in total silence: the editor's status bar said
|
||||
nothing, the server simply stopped answering for a while, and a user with a
|
||||
large project had no way to tell a slow index from a hung server. This round
|
||||
wraps every rescan — the startup build included — in server-initiated work-done
|
||||
progress: one `window/workDoneProgress/create`, one `$/progress` begin, the
|
||||
scan, one `$/progress` end naming the file count. Gated on the client's own
|
||||
`window.workDoneProgress` capability, because the spec forbids creating
|
||||
progress a client never asked for (TODO.md §9b).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`window.workDoneProgress` is the gate, and there is no fallback.** A client
|
||||
that did not advertise it is sent no `create` and no `$/progress` — not a
|
||||
degraded bar, not a `showMessage`. The spec is explicit that a server may
|
||||
only initiate progress against a client that asked; and a popup per save
|
||||
would be worse than the silence it replaced.
|
||||
- **`begin` is sent without waiting for the `create`'s answer.** The spec
|
||||
permits it ("the server is allowed to report progress before the create
|
||||
request is answered"), and here it is not merely permitted but necessary:
|
||||
the rescan blocks the single-threaded loop the moment `begin_indexing`
|
||||
returns, so waiting for the answer would mean the loop never processes it
|
||||
and the bar appears only after the work it describes is over. A client that
|
||||
*errors* the create is required to ignore the `$/progress` notifications
|
||||
carrying that token, so the worst case is a client that renders nothing —
|
||||
which is exactly what it rendered before this feature existed.
|
||||
- **The create's answer is ignored.** It goes through `Server::response`'s
|
||||
existing "not in the `applying` map, fall through" path, the same one the
|
||||
file-watcher (un)registrations use. Nothing is retried and nothing is
|
||||
remembered: the ids are minted from the one shared `request_ids` counter, so
|
||||
a progress answer can never be mistaken for an `applyEdit` answer.
|
||||
- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index`
|
||||
is one opaque call: it walks the roots, reads every file, builds the index,
|
||||
the completion tables and the include graph, and returns. There is no
|
||||
progress to observe without threading a callback through three engine
|
||||
layers, and an invented percentage — "it is probably about half done" — is a
|
||||
lie the user would learn to distrust. An indeterminate bar is the honest
|
||||
shape.
|
||||
- **The end message is the index's own file count**, read from
|
||||
`WorkspaceIndex::files().len()` after the scan. That number was already
|
||||
public and already computed; nothing was plumbed to obtain it. It counts the
|
||||
files the index was built from — in-scope files that read successfully, with
|
||||
open buffers overriding disk — which is what "indexed" means everywhere else
|
||||
in this server.
|
||||
- **The bar covers the scan, not the republish.** `end` is sent the instant
|
||||
`rebuild_index` returns, before `report_scope`'s warnings and before the
|
||||
per-buffer republishes that follow. Either order is defensible; this one is
|
||||
pinned by a test (`the_bar_is_down_before_the_republish`) because the bar
|
||||
names the *scan*, and the republish is per-open-buffer work the user already
|
||||
pays on every keystroke without a bar.
|
||||
- **The startup build gets a bar too, and that is legal.** `Server::new` runs
|
||||
after `main`'s `initialize_finish`, which returns only once the client's
|
||||
`initialized` notification has arrived — the same fact that makes the
|
||||
existing watcher registration legal there, and it is already stated in that
|
||||
code's comment. So the first index build, which is the slowest of the
|
||||
session, is wrapped like every other. Determined by reading `main.rs:59-79`
|
||||
and `server.rs`'s `Server::new`, not assumed.
|
||||
- **No cancellation.** `cancellable: Some(false)` is stated rather than left
|
||||
unset: the loop is one thread, a rescan runs to completion, and there is no
|
||||
`window/workDoneProgress/cancel` handler. A cancel button the user could
|
||||
press and that did nothing would be worse than no button.
|
||||
- **One bar at a time, in practice.** The loop is synchronous, so a rescan
|
||||
cannot overlap another rescan; every `begin` is followed by its own `end`
|
||||
before the next `begin` can be minted. The token counter guarantees
|
||||
uniqueness regardless.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `work_done_progress: bool`, filled by `main.rs` from
|
||||
`InitializeParams.capabilities.window.work_done_progress` (absent → false),
|
||||
in the style of the three fields already there. Every existing test that
|
||||
builds `ClientAbilities { ..Default::default() }` is unaffected.
|
||||
- `Server` gains `indexings: u32` — the progress-token counter. It is
|
||||
deliberately *not* the request-id counter: a token is not a request id, and
|
||||
`lucisv-index-3` reads as the fourth rescan rather than as an unrelated
|
||||
ordinal.
|
||||
- Two new private methods, `begin_indexing() -> Option<ProgressToken>` and
|
||||
`end_indexing(Option<ProgressToken>)`, plus a one-line `progress()` sender.
|
||||
`None` is the whole of the "this client cannot show a bar" path, so neither
|
||||
caller branches on the ability itself.
|
||||
- `Server::new` is restructured: the `Server` is built around a
|
||||
`Workspace::default()` and `open_roots` is then called *through* it, so the
|
||||
startup build can sit between a `begin_indexing`/`end_indexing` pair. Same
|
||||
work, same order relative to `report_scope` and `register_watchers`.
|
||||
- `Server::response`'s doc comment now names three things asked of the client
|
||||
rather than two. Its code is unchanged — the create's answer already fell
|
||||
through the `applying` lookup.
|
||||
|
||||
### `state::Workspace`, and every engine crate
|
||||
|
||||
**Untouched.** The file count comes from `Workspace::index()` and
|
||||
`WorkspaceIndex::files()`, both of which were already public and already
|
||||
called from this crate. No signature moved, `rebuild_index` still returns just
|
||||
its scope warnings, and nothing was plumbed for the sake of the end message.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change.** `vscode-languageclient` advertises
|
||||
`window.workDoneProgress` itself and renders server-initiated progress in the
|
||||
status bar with no help from `extension.js`. `smoke.js` sends
|
||||
`capabilities: {}`, so it takes the no-progress path and passes untouched —
|
||||
verified by running it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `window.workDoneProgress` read into `ClientAbilities` at initialize
|
||||
- [x] `begin_indexing`/`end_indexing` around `rebuild_index()` in `reindex()`
|
||||
- [x] The startup index build wrapped in the same pair (legal: `Server::new`
|
||||
runs after `initialize_finish`)
|
||||
- [x] A fresh `lucisv-index-N` token per rescan, never reused
|
||||
- [x] `end` carries the indexed file count, singular and plural
|
||||
- [x] A client without the capability is sent zero progress messages
|
||||
- [x] The create's answer stays ignored and cannot disturb `applyEdit` routing
|
||||
- [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness
|
||||
section
|
||||
- [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting,
|
||||
a rename across the workspace and `callHierarchy/incomingCalls` are the
|
||||
other candidates; all three are request-scoped, so they would use the
|
||||
*client-supplied* `workDoneToken` rather than a created one, which is a
|
||||
different mechanism with a different gate. Filed here, not built.
|
||||
- [ ] **Not done, deliberately:** no `window/workDoneProgress/cancel` handler.
|
||||
There is nothing in this server to cancel — see Assumptions.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9b
|
||||
|
||||
- **Read the code before deciding about the startup build, as the brief asked.**
|
||||
`main.rs` calls `connection.initialize_finish(...)` on line 74 and
|
||||
`Server::new(...)` on line 76, and `initialize_finish` returns only after the
|
||||
client's `initialized` notification has been received and consumed. So the
|
||||
startup build happens at a moment when server-initiated requests are legal —
|
||||
the existing `register_watchers()` call in `Server::new` already relies on
|
||||
exactly that, and says so in a comment. **Verdict: wrapped.** It is the
|
||||
slowest rescan of the session and the one most worth a bar.
|
||||
- **The one structural change is in `Server::new`**: the struct is now built
|
||||
first and `open_roots` called through it, because `begin_indexing` needs
|
||||
`&mut self`. Nothing else about that function moved — `report_scope` still
|
||||
runs on the warnings `open_roots` returned, and `register_watchers` still
|
||||
runs last.
|
||||
- **`Option<ProgressToken>` is the ability check.** `begin_indexing` returns
|
||||
`None` for a client that cannot show a bar and `end_indexing` returns on
|
||||
`None`, so neither `reindex` nor `Server::new` mentions the capability. That
|
||||
also makes "a bar that went up came down" structural rather than a
|
||||
discipline: there is exactly one value that ends it and exactly one place
|
||||
it is produced.
|
||||
- **Tokens are strings, `lucisv-index-N`, off their own counter.** A number
|
||||
token would collide conceptually with the `lucisv-N` request ids in a log,
|
||||
and the string says what the bar is for. The counter starts at the startup
|
||||
build, so `lucisv-index-0` is always the first index and the first save is
|
||||
always `lucisv-index-1` — pinned by tests at both the unit and the wire
|
||||
level.
|
||||
- **The end message reads `WorkspaceIndex::files().len()`,** which was already
|
||||
public and already reachable through `Workspace::index()`. The brief's
|
||||
fallback ("end with no message if no count is cheaply available") was not
|
||||
needed; nothing was plumbed. The singular case has its own assertion, because
|
||||
"1 files indexed" is the kind of thing that ships.
|
||||
- **`report_scope` still shows its popup after the bar comes down.** A filelist
|
||||
warning and a progress bar are unrelated; sequencing them the other way would
|
||||
have meant holding the bar up across a modal in some clients.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`TODO.md`, `docs/features/lucisv-server/README.md`, this README. No engine
|
||||
crate, no `editors/`, no new dependency, no version bump.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** (1802 on `HEAD`, measured — 7 new unit tests in `server.rs`, 1 in
|
||||
`main.rs`, 2 new e2e sessions). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK, exit 0. No commits.
|
||||
|
||||
The ten tests, and what each is for:
|
||||
|
||||
| test | pins |
|
||||
|---|---|
|
||||
| `the_startup_index_build_runs_under_the_first_bar` | the startup determination above, as observable traffic |
|
||||
| `a_save_puts_a_bar_up_and_takes_it_down_again` | create → begin → end, one token, on the save path |
|
||||
| `the_bar_says_how_many_files_were_indexed` | the end message, plural and singular |
|
||||
| `the_bar_is_down_before_the_republish` | the documented ordering against `publishDiagnostics` |
|
||||
| `a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all` | zero messages of any kind, at startup and on save |
|
||||
| `every_rescan_path_gets_its_own_bar_and_its_own_token` | the watched-file and config-change paths, three distinct tokens, no leaked begin, no `report` |
|
||||
| `a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit` | an `Ok` *and* an `Err` create answer arriving between an `applyEdit` push and its answer; the refusal still reported exactly once |
|
||||
| `work_done_progress_support_is_read_from_the_clients_own_capabilities` (`main.rs`) | absent/false/true, and no panic on `InitializeParams::default()` |
|
||||
| `indexing_reports_its_progress_over_the_wire` + `a_client_that_never_asked_for_progress_is_sent_none_over_the_wire` (e2e) | the whole sequence against the real binary, both gate states, including `title`, `cancellable: false` and the absence of `percentage` |
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9b
|
||||
|
||||
**Gates re-run**, on the working tree as handed off (commit `00c03ec` +
|
||||
uncommitted): `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` zero warnings. `cargo test --workspace`: **1812 passed, 0
|
||||
failed** — matches the dev log exactly. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. After the
|
||||
four tests added below: **1816 passed, 0 failed**, gates re-checked and still
|
||||
clean.
|
||||
|
||||
Per attack surface (lead's numbering):
|
||||
|
||||
1. **`Server::new` restructuring — verified clean, structurally rather than
|
||||
just empirically.** `Workspace::default()` then `open_roots(roots)` is the
|
||||
same value undergoing the same two operations in the same order whether the
|
||||
mutation happens on a local binding before it moves into the `Server`
|
||||
literal (old, `server.rs` pre-`00c03ec`-diff) or on `&mut self.workspace`
|
||||
after it is already a field (new) — a move is bitwise and Rust invokes no
|
||||
`Drop`/observer between them, so there is no field `open_roots` could leave
|
||||
stale that the old order would have filled: every field of `Workspace`
|
||||
(`docs`, `roots`, `index`, `candidates`, `includes`, `client`) gets the
|
||||
identical value either way. Every other `Server` field's initializer
|
||||
(`connection`, `config_warnings`, `abilities`, `watchers`, `registrations`,
|
||||
`request_ids`, `applying`, `generation`, `tokens`, `token_results`, and the
|
||||
new `indexings: 0`) is inert and side-effect-free, so field-initializer
|
||||
order carries no risk. `report_scope` still receives `open_roots`'s
|
||||
warnings (`server.rs:109-111`); `register_watchers` still runs last
|
||||
(`server.rs:116`).
|
||||
**Gap found and fixed**: the ordering the lead flagged as the actual risk —
|
||||
whether `register_watchers`'s request lands before or after the startup
|
||||
bar comes down — was not observable in any existing test, because every
|
||||
dev test using `watching_progress()` (`work_done_progress: true`) leaves
|
||||
`file_watching` at its `Default::default()` of `false`, so
|
||||
`register_watchers` is a no-op in all of them; conversely every test that
|
||||
turns `file_watching` on (`Session::new(_, true)`) leaves
|
||||
`work_done_progress` off. No test ever ran both abilities together. Added
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`
|
||||
(`server.rs`, in `mod tests`, right after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`),
|
||||
which turns both abilities on and pins the wire order `create, begin, end,
|
||||
register`.
|
||||
|
||||
2. **Protocol conformance — verified clean.** The e2e test
|
||||
`indexing_reports_its_progress_over_the_wire` decodes the actual JSON
|
||||
(not the Rust struct) off the real binary and asserts, in one ordered
|
||||
`Vec`: `create` precedes `begin` for the *same* token, for both the
|
||||
startup rescan (`lucisv-index-0`) and the save-triggered one
|
||||
(`lucisv-index-1`) — i.e., create-before-begin holds across consecutive
|
||||
rescans, not just once. The token is read with
|
||||
`.as_str().expect("a string token")`, which fails the test if the wire ever
|
||||
sends a JSON number instead — so the string-typed-token requirement is
|
||||
pinned, not assumed. `title`, `cancellable: false` (explicit `false`, not
|
||||
absent), and the absence of `percentage` are asserted off the decoded
|
||||
`begin`; the `end`'s `message` is asserted off the decoded `end`. No gap.
|
||||
|
||||
3. **Pairing is structural — verified clean.** Read `reindex()`
|
||||
(`server.rs:887-897`) and `Server::new` (`server.rs:140-169`): in both,
|
||||
nothing sits between `begin_indexing()` and `end_indexing()` but a call
|
||||
that returns a plain `Vec<String>` (`rebuild_index`/`open_roots`), never a
|
||||
`Result` — there is no `?` and no early-return expression available to
|
||||
write between them even by accident. `end_indexing` is therefore
|
||||
unconditionally reached in every existing and reachable call site.
|
||||
Multiple rapid reindexes: the server is single-threaded and `reindex()` is
|
||||
fully synchronous (begin, scan, end, all before the call returns), so two
|
||||
rescans provably cannot interleave regardless of how close together their
|
||||
triggers arrive — confirmed observably by
|
||||
`every_rescan_path_gets_its_own_bar_and_its_own_token`, which fires a save,
|
||||
a watched-file change and a config change back-to-back and gets three
|
||||
strictly-paired, strictly-increasing tokens. No gap.
|
||||
|
||||
4. **Capability gating — mostly verified clean, one gap fixed.** Startup and
|
||||
save, both gated correctly, per `a_client_that_did_not_ask_for_a_bar_is_
|
||||
sent_no_progress_at_all`. `window: {}` and `window: {
|
||||
workDoneProgress: false }` are both covered by
|
||||
`work_done_progress_support_is_read_from_the_clients_own_capabilities`
|
||||
(`main.rs`) via `saying(None)` and `saying(Some(false))` respectively —
|
||||
`ClientCapabilities::default()`'s `window` field is itself `None`, and
|
||||
`saying(None)` still wraps a `Some(WindowClientCapabilities{ .. })`, which
|
||||
is exactly the `window: {}` shape; neither panics on
|
||||
`InitializeParams::default()`.
|
||||
**Gap found and fixed**: the watched-file and `lucisv.exclude`/`filelist`
|
||||
reindex triggers were never driven with the capability *off* — only proven
|
||||
off by reading that they share `reindex()`'s single `begin_indexing` call
|
||||
with the save path. Added
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`
|
||||
(`server.rs`), which drives both and asserts `session.progress()` empty
|
||||
after each.
|
||||
|
||||
5. **Response routing under interleaving — one direction existing, the
|
||||
reverse was missing; fixed.** The dev's
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`
|
||||
answers the create (`Ok` then, for the same id, `Err`) while the
|
||||
`applyEdit` is still outstanding, then answers the edit — this is a real
|
||||
interleaving (create resolved first), and both answer shapes are exercised.
|
||||
The reverse ordering the lead asked for — `applyEdit` resolved *first*,
|
||||
then a *late* create answer — was not present. Added
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`
|
||||
(`server.rs`): answers the edit as accepted, confirms nothing is shown, then
|
||||
feeds a late `Response::new_ok` for the create's id and confirms it is
|
||||
still silently dropped. This same test doubles as "a create answer arriving
|
||||
for a token the server already Ended": by the time the edit is answered,
|
||||
the watched-file reindex that minted the create has already run its
|
||||
`begin`/`end` pair synchronously (per point 3), so the create answer that
|
||||
follows is necessarily late-for-an-ended-bar. It is ignored cleanly because
|
||||
`response()` keys off `RequestId`, never off `ProgressToken` — the two are
|
||||
different namespaces and `request_ids` never repeats, so there is no
|
||||
representable state where a create's id could collide with anything a
|
||||
still-outstanding request cares about. No further scenario to test here.
|
||||
|
||||
6. **End-message count — verified clean, one gap fixed.** `end_indexing`
|
||||
reads `self.workspace.index().files().len()` (`server.rs:192`), which is
|
||||
the index's own file list, computed by `rebuild_index` immediately before
|
||||
`end_indexing` runs — not open-buffer count, not scope-file count before
|
||||
filtering. Singular/plural pinned by `the_bar_says_how_many_files_were_
|
||||
indexed` ("2 files indexed" / "1 file indexed", explicitly asserting `"not
|
||||
`1 files`"`).
|
||||
**Gap found and fixed**: no test drove a rootless workspace with zero open
|
||||
buffers through startup. Traced `default_files()` → `sibling_files()`
|
||||
(`state.rs:308-328`) for that case: no roots and no docs means no
|
||||
directories to walk, so the index is empty and `files == 0`; the plural
|
||||
branch (`files == 1` is false for 0) correctly renders `"s"`. Added
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing` (`server.rs`), asserting `"0 files indexed"` and, by not
|
||||
panicking, non-crashing. Confirmed passing.
|
||||
|
||||
7. **CLAUDE.md compliance — verified clean.** Grepped every non-`#[cfg(test)]`
|
||||
line of `server.rs` and `main.rs` (i.e., everything before their `mod
|
||||
tests`) for `unwrap(`, `expect(`, `panic!(`: zero hits. Every new item
|
||||
(`ClientAbilities::work_done_progress`, `Server::indexings`,
|
||||
`INDEXING_TITLE`, `begin_indexing`, `end_indexing`, `progress`,
|
||||
`work_done_progress_support`) carries a doc comment. This README's seven
|
||||
required sections (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`,
|
||||
`Work log`, `QA log`, `Review`) each appear exactly once
|
||||
(`grep -n "^## "`). `TODO.md`'s §9b item text is untouched — only its
|
||||
checkbox flipped to `[x]` and an indented `→` note appended below, per the
|
||||
existing convention elsewhere in that file.
|
||||
|
||||
**Beyond the list.** One thing noted for the record, not a defect in this
|
||||
diff: `Workspace::collect_sources` (`state.rs`, untouched by this round) folds
|
||||
in every open buffer's path unconditionally, even one outside the walked
|
||||
scope, so in principle an open buffer for a file the workspace walk would not
|
||||
have found could nudge the "N file(s) indexed" count up by one beyond what a
|
||||
disk-only scan would report. This is pre-existing behavior this feature did
|
||||
not introduce and does not change (`state.rs` has no diff against `00c03ec`),
|
||||
so it is not filed as a finding against this round — just flagged in case a
|
||||
future change to the end message's wording ever needs it.
|
||||
|
||||
**Fixes made** (all additive; no dev code changed): four new tests in
|
||||
`crates/lucisv_server/src/server.rs`'s `mod tests`, inserted after
|
||||
`a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit`:
|
||||
`a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too`,
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
|
||||
`a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either`,
|
||||
`a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_
|
||||
crashing`. All four pass; full workspace suite is green at 1816; `cargo fmt`
|
||||
and `cargo clippy --all-targets` stay clean.
|
||||
|
||||
**Verdict: committable as-is.** No corruption risk, no idempotency risk (this
|
||||
feature touches only the LSP transport, never formatted output), no dropped
|
||||
comments, no widened `verify.rs` forgiveness (that file has no diff in this
|
||||
round). The one structurally risky change — `Server::new`'s construction
|
||||
order — is provably equivalent to the old order and now has its
|
||||
previously-unpinned watcher-vs-bar ordering under test. No dev follow-up
|
||||
required.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1816 workspace tests, 0 failed), clean. The `Option<ProgressToken>`-as-
|
||||
capability-gate design is the kind of structural guarantee this repo
|
||||
prefers over discipline: neither caller can put a bar up for a client
|
||||
that cannot show one, and nothing between `begin` and `end` can return
|
||||
early — I read the two call sites and confirm QA's finding that the
|
||||
pairing is unconditional. The startup-build determination was done the
|
||||
right way (read from `initialize_finish`'s contract and the existing
|
||||
`register_watchers` comment, not guessed), and the restructured
|
||||
`Server::new` is provably equivalent — same value, same two operations,
|
||||
different borrow spelling — with the previously-unpinned
|
||||
watcher-after-bar ordering now under test thanks to QA. Honesty calls
|
||||
all correct: no invented percentage, `cancellable: false` because
|
||||
nothing here can cancel, and the end message costing nothing because the
|
||||
index already knew its file count. QA's four gap-closing tests (both
|
||||
interleaving directions, capability-off on all trigger paths, the
|
||||
rootless zero-count startup) complete the surface. Accepted as shipped.
|
||||
+27
-3
@@ -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
|
||||
|
||||
```
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the lucisv language server.",
|
||||
"version": "0.8.0",
|
||||
"version": "0.9.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user