Files
lucisv/crates/lucisv_server/src/server.rs
T
lucioandClaude Fable 5 bf17ddd1e5
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 21s
LSP §9c: type hierarchy over extends
textDocument/prepareTypeHierarchy + typeHierarchy/supertypes/subtypes
for SystemVerilog classes. Supertypes is one computed offset into the
existing resolution machinery — the overlay promotion made cross-file
bare class names answerable, and the offset is the LAST byte of the
extends name span so pkg::base lands in the tail's reference, never
the package's. Subtypes is a workspace census on the callers_of_each
pattern (one sources() pass, prefilter, deterministic sort), matching
the base name as written — 0 of the corpus's 270 extends clauses are
qualified, and the asymmetry with supertypes is documented and pinned
from both directions, including the same-name/different-file
consequence. Ambiguous bases answer every declaration, like
definition. Modules stay on callHierarchy by scope ruling.

lsp-types 0.97 has no server-side typeHierarchyProvider field, so
initialize_value() inserts the one key into the serialized result —
QA's strip-and-compare test proves every other key survives with
identical values. QA also traced the parser to show the degenerate
extends spans the code guards against cannot be constructed, corrected
two README figures the lead applied (the 309 extends count did not
reproduce; 270 does), and pinned the generate-block walk gap as a
scoped choice. Interface classes stay blocked on the parser, pinned.

45 tests added (dev 33 + QA 12), including the real ibex UVM chain
and a 10-deep expansion. The inheritance-edge index want is filed
beside the instantiation-edge Handshake as one future round.

docs/features/type-hierarchy/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 21:35:36 -07:00

4378 lines
205 KiB
Rust

//! The request loop: one burst in, one response per request, on one thread.
//!
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
//! messages over a channel. Everything below is synchronous — Verilog files
//! are small, every handler is milliseconds, and a worker pool would buy
//! nothing yet. A request that has already started therefore runs to
//! completion; the one thing `$/cancelRequest` can do here is answer a request
//! still *queued* behind the one being served, which is what the burst drain
//! in `run` is for. See `docs/features/lucisv-server/README.md` and
//! `docs/features/cancel-request/README.md`.
use std::collections::{HashMap, HashSet};
use std::error::Error;
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _,
Progress, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls,
CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest, Completion,
DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest,
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
TypeHierarchySubtypes, TypeHierarchySupertypes, UnregisterCapability, WillSaveWaitUntil,
WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind,
CodeActionParams, CodeLensParams, CompletionParams, DidChangeConfigurationParams,
DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams,
DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams,
DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams,
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams,
GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams,
LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position,
PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport,
RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken,
SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams,
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri,
WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin,
WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams,
WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport,
WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams,
WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay,
inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature,
symbols, sync, tokens, type_def, type_hierarchy, watch,
};
/// What the client said it can do, read once at `initialize` because that is
/// the only time those capabilities are sent.
#[derive(Default)]
pub struct ClientAbilities {
/// Whether the client can expand a completion item's tabstops.
pub snippets: bool,
/// Whether the client accepts a `workspace/didChangeWatchedFiles`
/// registration. There is no static form of that capability, so a client
/// that says nothing keeps the save-only staleness model.
pub file_watching: bool,
/// Whether the client applies a `workspace/applyEdit` request. A client
/// that cannot gets a command's edit back as the request result instead,
/// which is what every client got before this was read.
pub apply_edit: bool,
/// Whether the client *pulls* diagnostics (LSP 3.17). One client is never
/// served both models: a pulling client is pushed nothing at all.
pub pull_diagnostics: bool,
/// Whether the client renders server-initiated work-done progress. The
/// spec forbids creating any without it, so a client that said nothing
/// sees the workspace rescan exactly as it did before — silently.
pub work_done_progress: bool,
/// Whether the client accepts a `workspace/codeLens/refresh`. A client
/// that said nothing is never asked, and keeps the instantiation counts it
/// last requested until it asks again for its own reasons.
pub code_lens_refresh: bool,
/// Whether the client opens a document the server asks it to
/// (`window/showDocument`). This is what lets the instantiation lens
/// navigate; a client without it still gets the sites back as the
/// command's result.
pub show_document: bool,
}
/// Everything the server owns.
pub struct Server {
connection: Connection,
workspace: Workspace,
/// Documents whose `lucisv.toml` problem has already been reported. Cleared
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `lucisv.filelist` can replace it: the watched filelist path is
/// part of the registration, so a new path needs a new registration.
watchers: Option<String>,
/// Numbers the file-watcher registrations, so a replacement can name the
/// one it supersedes.
registrations: u32,
/// Numbers the requests made *of* the client. A repeated id is a protocol
/// error, so this only ever counts up.
request_ids: u32,
/// The `workspace/applyEdit` requests still waiting for an answer, by the
/// id they were sent with, each remembering the command that asked for it
/// so a refusal can be named. Nothing else the server asks of the client
/// is recorded here, which is exactly what makes its answer ignorable.
applying: HashMap<RequestId, String>,
/// Counts everything that can change what a pull request would answer: a
/// buffer's text, and the workspace index. It is the whole of a
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
generation: u64,
/// The last full-or-delta semantic-token answer for each open buffer —
/// what a delta is computed *against*. Dropped on `didClose`, so this
/// only ever holds what the editor is showing. See
/// `docs/features/semantic-tokens-delta/README.md`.
tokens: HashMap<Uri, TokenAnswer>,
/// Numbers the semantic-token answers. Per answer, not per generation: a
/// client's `previousResultId` has to name the exact data it holds, and
/// two buffers' answers are never comparable.
token_results: u64,
/// Numbers the progress tokens the index rescans run under. One rescan is
/// one token, and a token is never reused: a client keys the bar it is
/// showing off it.
indexings: u32,
}
/// What the workspace-rescan progress bar calls itself. One title for every
/// rescan — startup, save, watched file, changed scope — because they are the
/// same work and a user reading the status bar wants to know that.
const INDEXING_TITLE: &str = "Indexing Verilog workspace";
/// One semantic-token answer, kept so the next delta request can be answered
/// against it.
struct TokenAnswer {
result_id: String,
data: Vec<SemanticToken>,
}
impl Server {
pub fn new(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
) -> Server {
let mut server = Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
abilities,
watchers: None,
registrations: 0,
request_ids: 0,
applying: HashMap::new(),
generation: 0,
tokens: HashMap::new(),
token_results: 0,
indexings: 0,
};
// The earliest legal moment for anything server-initiated: `main`
// builds this only after `initialize_finish`, which returns once the
// client's `initialized` notification has arrived — and consumes it,
// so the loop below never sees one to hang these off instead. The
// first index build is the slowest one of the session, so it gets the
// same bar every later rescan gets.
let bar = server.begin_indexing();
let warnings = server.workspace.open_roots(roots);
server.end_indexing(bar);
server.report_scope(warnings);
server.register_watchers();
server
}
/// Receive until the client shuts us down or the channel closes.
///
/// One blocking receive, then everything already queued behind it, then
/// that whole burst in arrival order. The drain is what makes
/// `$/cancelRequest` mean anything: while a handler runs, the client's
/// later requests and its cancels for them pile up together, and a cancel
/// found next to its request answers that request for free.
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
let queue = self.queue();
while let Ok(message) = queue.recv() {
if self.process_batch(burst(&queue, message))? {
return Ok(());
}
}
Ok(())
}
/// Move the incoming messages onto a queue of our own, and report it.
///
/// Necessary because `lsp-server`'s transport hands messages over
/// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding
/// one message until this loop takes it, so a client's backlog never sits
/// on `connection.receiver` at all: it sits in the OS pipe, invisible and
/// one message deep. Forwarding onto an unbounded queue is what makes
/// "everything already sent" observable without blocking, which is the
/// whole premise of the burst below.
///
/// The forwarder stops at `shutdown` and never reads past it, because
/// `handle_shutdown` reads the `exit` notification off the *connection*
/// itself — a forwarder that kept going would steal it and strand the
/// handshake for thirty seconds. It owns nothing but messages in flight
/// and touches no server state.
fn queue(&self) -> std::sync::mpsc::Receiver<Message> {
let (sender, receiver) = std::sync::mpsc::channel();
let source = self.connection.receiver.clone();
// A failed spawn would leave the server unable to receive anything at
// all; there is nothing useful to do with that but let `run` end when
// the queue's sender is dropped.
let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || {
while let Ok(message) = source.recv() {
let last = is_shutdown(&message);
if sender.send(message).is_err() || last {
break;
}
}
});
receiver
}
/// Handle one burst in arrival order, reporting whether the client shut us
/// down.
///
/// Order is the whole contract: a `didChange` queued ahead of a completion
/// is applied before that completion is answered, exactly as it would be
/// one message at a time. The only thing the burst adds is that a request
/// this burst also carries a cancel for is answered `RequestCancelled`
/// instead of computed — except `shutdown`, which is honoured before the
/// cancelled set is ever consulted, so no cancel can talk the server out
/// of shutting down.
fn process_batch(&mut self, batch: Vec<Message>) -> Result<bool, Box<dyn Error + Sync + Send>> {
let mut cancelled = cancelled_in(&batch);
for message in batch {
match message {
Message::Request(request) => {
if self.connection.handle_shutdown(&request)? {
return Ok(true);
}
// Removed as it is used: a second cancel for the same id
// then finds nothing, and the set cannot outlive the burst.
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
self.request(request)
};
self.connection.sender.send(Message::Response(response))?;
}
// The cancels themselves are consumed here — `notification`
// has nothing to do with one, and everything it could do has
// already been done above.
Message::Notification(notification) if notification.method == Cancel::METHOD => {}
Message::Notification(notification) => self.notification(notification),
Message::Response(response) => self.response(response),
}
}
Ok(false)
}
// ------------------------------------------------------------------
// requests
// ------------------------------------------------------------------
fn request(&mut self, request: Request) -> Response {
let id = request.id.clone();
let method = request.method.clone();
let result = match method.as_str() {
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
// One keystroke, at most one edit, never a word to the user — see
// `on_type_formatting`.
OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)),
// Format-on-save, protocol-native: the client asks before it
// writes, and applies whatever comes back. Opt-in, and the decline
// is the cheap path — see `will_save_wait_until`.
WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)),
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.map(|offset| hover::hover(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
}),
GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.map(|offset| nav::definition(&self.workspace, &uri, offset))
.unwrap_or_default();
to_value(GotoDefinitionResponse::Array(locations))
}),
// The same answer shape as go-to-definition, deliberately: an
// array in every case, empty where there is nothing to jump to,
// and every candidate where the workspace holds the type name
// twice. A buffer this server has not been sent is the empty
// array too, which is what `unwrap_or_default` on the position
// conversion means here as it does above.
GotoTypeDefinition::METHOD => {
decode(request).and_then(|p: GotoTypeDefinitionParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.map(|offset| type_def::type_definition(&self.workspace, &uri, offset))
.unwrap_or_default();
to_value(GotoTypeDefinitionResponse::Array(locations))
})
}
// A closing label and the name it repeats, edited together. `null`
// for every position that is not one of those two names — and for
// a pair that could not be linked honestly (no label written, a
// label that does not match, an escaped identifier), because an
// empty `ranges` list is not what "nothing to link" means here.
LinkedEditingRange::METHOD => {
decode(request).and_then(|p: LinkedEditingRangeParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.and_then(|offset| {
let doc = self.workspace.document(&uri)?;
linked::linked_editing_ranges(doc, offset)
})
.map_or(Ok(Value::Null), to_value)
})
}
// The underline half of include navigation. Unresolvable includes
// are simply absent from the list — never an error, and never a
// link that goes nowhere.
DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| {
to_value(includes::document_links(&self.workspace, &p.text_document.uri))
}),
References::METHOD => decode(request).and_then(|p: ReferenceParams| {
let include = p.context.include_declaration;
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
.unwrap_or_default();
to_value(locations)
}),
// Two answers behind one request: a scope keyword pairs with its
// own closer, and anything else is a symbol whose other
// occurrences in this file are what to draw. A cursor that is
// neither answers `null` rather than an empty list — an empty list
// means "no occurrences anywhere", which suppresses the editor's
// own word highlighting, and losing that everywhere would be a
// poor trade for gaining this.
DocumentHighlightRequest::METHOD => {
decode(request).and_then(|p: DocumentHighlightParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let found = self.offset(&uri, position).and_then(|offset| {
let doc = self.workspace.document(&uri)?;
pairs::highlights(doc, offset)
.or_else(|| nav::document_highlights(doc, offset))
});
found.map_or(Ok(Value::Null), to_value)
})
}
FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| {
match self.workspace.document(&p.text_document.uri) {
Some(doc) => to_value(folding::folding_ranges(doc)),
None => Ok(Value::Null),
}
}),
// Ghost port names on ordered connection lists. Range-scoped, as
// the protocol asks: the client sends the lines it is showing and
// gets the hints inside them.
InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| {
to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range))
}),
SemanticTokensFullRequest::METHOD => {
decode(request).and_then(|p: SemanticTokensParams| {
self.semantic_tokens_full(&p.text_document.uri)
.map(SemanticTokensResult::Tokens)
.map_or(Ok(Value::Null), to_value)
})
}
// The same answer as `full`, said as what changed since the
// client's last one — or as a whole new answer when we cannot
// prove what it holds.
SemanticTokensFullDeltaRequest::METHOD => {
decode(request).and_then(|p: SemanticTokensDeltaParams| {
self.semantic_tokens_delta(&p.text_document.uri, &p.previous_result_id)
.map_or(Ok(Value::Null), to_value)
})
}
// The visible lines only, for the first paint of a large file.
// Self-contained and unremembered: a range answer is not what a
// later delta is computed against, so it carries no `resultId`.
SemanticTokensRangeRequest::METHOD => {
decode(request).and_then(|p: SemanticTokensRangeParams| {
match self.workspace.document(&p.text_document.uri) {
Some(doc) => to_value(SemanticTokensRangeResult::Tokens(SemanticTokens {
result_id: None,
data: tokens::semantic_tokens_in_range(doc, p.range),
})),
None => Ok(Value::Null),
}
})
}
DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| {
match self.workspace.document(&p.text_document.uri) {
Some(doc) => {
to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc)))
}
None => Ok(Value::Null),
}
}),
CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| {
let uri = p.text_document.uri;
let only = p.context.only;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
// A code-action request carries no `tabSize`, so the width a
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
// or from the built-in default.
let tab_width =
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
let mut actions =
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
// The port refactorings answer for the cursor, not for a range:
// the request's start is where the user is.
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
{
let offset = doc.positions().offset(p.range.start);
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
}
to_value(actions)
}),
// Custom method, so it is matched by name rather than through a
// `lsp_types::request` type. Nothing advertises it: a client that
// does not know it never asks.
pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| {
match self.workspace.document(&p.text_document.uri) {
Some(doc) => to_value(pairs::scope_pairs(doc)),
None => Ok(Value::Null),
}
}),
// A rename the engine declines comes back as a request error
// carrying its own sentence, which is what an editor shows in the
// rename box. `prepareRename` declines the same way, so the box
// never opens for a rename that would then fail.
PrepareRenameRequest::METHOD => {
decode(request).and_then(|at: TextDocumentPositionParams| {
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::prepare(&self.workspace, &uri, offset) {
Ok(response) => to_value(response),
Err(message) => Err(Failure::Request(message)),
}
})
}
Rename::METHOD => decode(request).and_then(|p: RenameParams| {
let new_name = p.new_name;
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::rename(&self.workspace, &uri, offset, &new_name) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
to_value(edit)
}
Err(message) => Err(Failure::Request(message)),
}
}),
// "N instantiations" over every module and interface declared in
// the buffer. Every lens is complete when it is returned — there
// is no `codeLens/resolve` — and a buffer this server has not been
// sent answers `null`, as every other document-scoped request
// does.
CodeLensRequest::METHOD => decode(request).and_then(|p: CodeLensParams| {
lens::code_lenses(&self.workspace, &p.text_document.uri)
.map_or(Ok(Value::Null), to_value)
}),
// The port refactorings, and the code lens's own jump. A refusal
// is the engine's own sentence, returned as `RequestFailed`
// exactly as a declined rename is.
ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| {
if p.command == lens::SHOW_INSTANTIATIONS {
return match lens::execute(&self.workspace, &p.arguments) {
Ok(locations) => self.show_instantiations(locations),
Err(message) => Err(Failure::Request(message)),
};
}
match ports::execute(&self.workspace, &p.command, &p.arguments) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
self.deliver(&p.command, edit)
}
Err(message) => Err(Failure::Request(message)),
}
}),
// Pull diagnostics, LSP 3.17. Same parse+lint pass the push model
// publishes; only the timing and the caching differ.
DocumentDiagnosticRequest::METHOD => {
decode(request).and_then(|p: DocumentDiagnosticParams| {
let report = self.document_report(&p.text_document.uri, p.previous_result_id);
to_value(DocumentDiagnosticReportResult::Report(report))
})
}
WorkspaceDiagnosticRequest::METHOD => {
decode(request).and_then(|p: WorkspaceDiagnosticParams| {
let report = self.workspace_report(&p.previous_result_ids);
to_value(WorkspaceDiagnosticReportResult::Report(report))
})
}
// Expand-selection. One chain per position, in the order asked —
// a client sends one position per cursor, and a multi-cursor
// editor matches the answers up by index.
SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| {
match self.workspace.document(&p.text_document.uri) {
Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)),
None => Ok(Value::Null),
}
}),
// Module hinting. A position that is not a module item answers
// `null` rather than an empty list, so the editor's own word
// completion is left in charge there.
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
.map_or(Ok(Value::Null), to_value)
}),
// Ghost text. `null` for every position that is not one of the
// two triggers, which is nearly all of them — the request arrives
// on every keystroke, so the decline has to be the cheap path.
InlineCompletionRequest::METHOD => {
decode(request).and_then(|p: InlineCompletionParams| {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
inline::inline_completions(&self.workspace, &uri, position)
.map_or(Ok(Value::Null), to_value)
})
}
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.and_then(|offset| signature::signature_help(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
}),
// The module hierarchy. `prepare` answers `null` for a position
// that is not a module name, which is what stops an editor from
// opening an empty hierarchy view; the two directions then answer
// one hop each, and the client drives the expansion.
CallHierarchyPrepare::METHOD => {
decode(request).and_then(|p: CallHierarchyPrepareParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
})
}
CallHierarchyIncomingCalls::METHOD => {
decode(request).and_then(|p: CallHierarchyIncomingCallsParams| {
to_value(hierarchy::incoming(&self.workspace, &p.item))
})
}
CallHierarchyOutgoingCalls::METHOD => {
decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| {
to_value(hierarchy::outgoing(&self.workspace, &p.item))
})
}
// The class inheritance tree. Same contract as the call hierarchy
// above: `prepare` answers `null` for a position that is not a
// class name, and the two directions answer one hop each while the
// client drives the expansion.
TypeHierarchyPrepare::METHOD => {
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
})
}
TypeHierarchySupertypes::METHOD => {
decode(request).and_then(|p: TypeHierarchySupertypesParams| {
to_value(type_hierarchy::supertypes(&self.workspace, &p.item))
})
}
TypeHierarchySubtypes::METHOD => {
decode(request).and_then(|p: TypeHierarchySubtypesParams| {
to_value(type_hierarchy::subtypes(&self.workspace, &p.item))
})
}
WorkspaceSymbolRequest::METHOD => {
decode(request).and_then(|p: WorkspaceSymbolParams| {
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
&self.workspace,
&p.query,
)))
})
}
_ => Err(Failure::MethodNotFound(method)),
};
match result {
Ok(value) => Response::new_ok(id, value),
Err(failure) => failure.into_response(id),
}
}
fn formatting(&mut self, params: DocumentFormattingParams) -> Result<Value, Failure> {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::formatting(doc, &settings.config);
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
// one, but an editor that refuses to format because of a typo in a
// config file is an editor the user turns off. The buffer is formatted
// with the built-in defaults, and the reason is said once per change of
// the file — a format-on-save loop would otherwise repeat it forever.
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// `textDocument/rangeFormatting`, on the same engine and the same
/// all-or-nothing contract as whole-document formatting.
fn range_formatting(
&mut self,
params: DocumentRangeFormattingParams,
) -> Result<Value, Failure> {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::range_formatting(doc, &settings.config, params.range);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// `textDocument/onTypeFormatting` — the newline and the semicolon.
///
/// Two things about it are unlike every other formatting entry, and both
/// follow from its trigger being a keystroke rather than a command:
///
/// * **It never speaks.** A formatter refusal is `[]` and silence, where
/// `textDocument/formatting` shows an ERROR and `willSaveWaitUntil`
/// shows one per save. Mid-edit code the engine declines is the *normal*
/// case here, not a failure worth a popup on every semicolon.
/// * **It never warns about a broken `lucisv.toml` either.** That warning
/// is deduped per buffer *state*, and `set_document` re-arms it — so a
/// request that by definition follows the `didChange` the user's own
/// keystroke produced would re-arm and re-show it on every character.
/// The user is told on their next explicit format or save, which are the
/// two moments they asked lucisv for something.
///
/// The settings ladder is the one `textDocument/formatting` climbs,
/// `tabSize` rung included: unlike `willSaveWaitUntil`, this request does
/// carry `FormattingOptions`.
fn on_type_formatting(
&mut self,
params: DocumentOnTypeFormattingParams,
) -> Result<Value, Failure> {
let at = params.text_document_position;
let Some(doc) = self.workspace.document(&at.text_document.uri) else {
return to_value(Vec::<lsp_types::TextEdit>::new());
};
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let edits = on_type::on_type_formatting(doc, at.position, &params.ch, &settings.config);
to_value(edits)
}
/// `textDocument/willSaveWaitUntil` — format the buffer the client is
/// about to write, for the editors that have no format-on-save of their
/// own.
///
/// `null` unless `lucisv.formatOnSave` is on. A capable client sends this
/// before *every* save, so declining has to be the cheap path — and an
/// editor that already formats on save (VS Code's `editor.formatOnSave`,
/// which runs `textDocument/formatting`) would otherwise format twice.
///
/// When it is on, this is `textDocument/formatting` with a different
/// trigger: the same engine, the same settings ladder, the same
/// all-or-nothing contract — one whole-document edit built from verified
/// output, or no edit at all. The save's `reason` is not read: manual,
/// after-delay and focus-out are all saves, and the user asked for their
/// saves to be formatted. The text is the buffer the server holds, because
/// the request carries none and the client has not written yet.
fn will_save_wait_until(
&mut self,
params: WillSaveTextDocumentParams,
) -> Result<Value, Failure> {
if !self.workspace.client_settings().format_on_save {
return Ok(Value::Null);
}
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
// No `FormattingOptions` on this request — the protocol carries none —
// so the ladder runs without its `tabSize` rung.
let settings =
format::settings_without_editor_options(doc, self.workspace.client_settings());
let result = format::formatting(doc, &settings.config);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// Say once per change of a file that its `lucisv.toml` could not be read.
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
if let Some(problem) = problem {
if self.config_warnings.insert(uri.clone()) {
self.show_message(
MessageType::WARNING,
format!("lucisv: {problem} — formatting with default settings"),
);
}
}
}
/// One edit, none, or — when the formatter refused — none plus the reason.
///
/// It never emits partial output (CLAUDE.md invariant #1), so neither do
/// we. Diagnostics are not used for the failure: they belong to the parse
/// pass and are cleared on the next keystroke, which would erase an
/// explicit format failure the user asked for.
fn edits(
&mut self,
result: Result<Option<lsp_types::TextEdit>, String>,
) -> Result<Value, Failure> {
match result {
Ok(Some(edit)) => to_value(vec![edit]),
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
Err(message) => {
self.show_message(MessageType::ERROR, format!("lucisv: cannot format — {message}"));
to_value(Vec::<lsp_types::TextEdit>::new())
}
}
}
/// Deliver a command's `WorkspaceEdit` the way the client can take it.
///
/// The protocol has no place for an edit in an `executeCommand` *result*:
/// a client applies what a server pushes with `workspace/applyEdit`, and
/// drops the result on the floor. So the edit is pushed and the result is
/// `null` — except for a client that never advertised `workspace.applyEdit`,
/// which gets the old return-the-edit behavior because for that one it is
/// the only behavior that could ever work.
///
/// The push goes out *before* the command's own response, which the loop
/// sends when this returns. The protocol allows a server to request at any
/// time, and a client that waited for the command result before applying
/// the edit would deadlock on any server that does this — VS Code and
/// Neovim both apply it immediately.
fn deliver(&mut self, command: &str, edit: WorkspaceEdit) -> Result<Value, Failure> {
if !self.abilities.apply_edit {
return to_value(edit);
}
let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit };
let id = self.send_request(ApplyWorkspaceEdit::METHOD, params);
self.applying.insert(id, command.to_string());
Ok(Value::Null)
}
/// Answer `lucisv.showInstantiations` with its sites, and — for a client
/// that can be sent one — push a `window/showDocument` for the first of
/// them, so clicking the lens actually moves a cursor.
///
/// `executeCommand`'s *result* cannot navigate: it goes back to whatever
/// invoked the command, and no editor moves on one. So the locations are
/// the answer for a caller that wants the list, and the push is what makes
/// the lens do something in an editor. Only the **first** site is shown:
/// `window/showDocument` opens one document, and the protocol has no
/// server-initiated "peek these seven places" — that is a VS Code command,
/// and this repo's extension declares none. The client's answer is
/// ignorable and falls through `response`'s `applying` lookup, as the
/// progress `create`'s does.
fn show_instantiations(&mut self, locations: Vec<Location>) -> Result<Value, Failure> {
if let Some(first) = locations.first().filter(|_| self.abilities.show_document) {
let params = ShowDocumentParams {
uri: first.uri.clone(),
external: None,
take_focus: Some(true),
selection: Some(first.range),
};
self.send_request(ShowDocument::METHOD, params);
}
to_value(locations)
}
// ------------------------------------------------------------------
// semantic tokens
// ------------------------------------------------------------------
/// The whole buffer's tokens, stamped and remembered.
///
/// A client may mix `full` and `full/delta` freely — the protocol lets it
/// — so this answer is remembered exactly as a delta's is, and its
/// `resultId` is as good a starting point for the next delta.
fn semantic_tokens_full(&mut self, uri: &Uri) -> Option<SemanticTokens> {
let data = tokens::semantic_tokens(self.workspace.document(uri)?);
let result_id = self.remember_tokens(uri, data.clone());
Some(SemanticTokens { result_id: Some(result_id), data })
}
/// What changed since the answer the client says it holds.
///
/// A `previousResultId` that does not name the answer we remember — a
/// stale one, a buffer we have no state for, one from before a
/// `didClose` — is answered with a full set instead. The protocol allows
/// either, and a delta against data we cannot see would be a guess.
fn semantic_tokens_delta(
&mut self,
uri: &Uri,
previous: &str,
) -> Option<SemanticTokensFullDeltaResult> {
let new = tokens::semantic_tokens(self.workspace.document(uri)?);
let known = self.tokens.get(uri).filter(|answer| answer.result_id == previous);
let edits = known.map(|answer| tokens::delta(&answer.data, &new));
let result_id = Some(self.remember_tokens(uri, new.clone()));
Some(match edits {
Some(edits) => {
SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta { result_id, edits })
}
None => SemanticTokensFullDeltaResult::Tokens(SemanticTokens { result_id, data: new }),
})
}
/// Stamp an answer with a fresh id and keep it as the one the next delta
/// is computed against. One buffer holds one answer: a client that asks
/// again has moved on from the previous one.
fn remember_tokens(&mut self, uri: &Uri, data: Vec<SemanticToken>) -> String {
self.token_results += 1;
let result_id = self.token_results.to_string();
self.tokens.insert(uri.clone(), TokenAnswer { result_id: result_id.clone(), data });
result_id
}
// ------------------------------------------------------------------
// pull diagnostics
// ------------------------------------------------------------------
/// One buffer's diagnostics, or an unchanged report when nothing that
/// feeds them has moved since the client's last pull.
fn document_report(&self, uri: &Uri, previous: Option<String>) -> DocumentDiagnosticReport {
let result_id = self.result_id();
if previous.as_deref() == Some(result_id.as_str()) {
let unchanged = UnchangedDocumentDiagnosticReport { result_id };
return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
related_documents: None,
unchanged_document_diagnostic_report: unchanged,
});
}
let full = FullDocumentDiagnosticReport {
result_id: Some(result_id),
items: self.diagnostics_of(uri),
};
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
related_documents: None,
full_document_diagnostic_report: full,
})
}
/// Every open buffer's diagnostics, in URI order so two pulls of the same
/// state read the same way.
///
/// Open buffers are the whole scope: this server has never diagnosed a
/// file it was not shown, and pulling would be the wrong place to start —
/// linting the workspace on a keystroke-driven request is a rescan of
/// every file per pull. The limit is stated in the feature README.
fn workspace_report(&self, previous: &[PreviousResultId]) -> WorkspaceDiagnosticReport {
let result_id = self.result_id();
let mut uris = self.workspace.open_uris();
uris.sort();
let items = uris
.into_iter()
.map(|uri| {
let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id);
if known {
let unchanged =
UnchangedDocumentDiagnosticReport { result_id: result_id.clone() };
return WorkspaceDocumentDiagnosticReport::Unchanged(
WorkspaceUnchangedDocumentDiagnosticReport {
uri,
version: None,
unchanged_document_diagnostic_report: unchanged,
},
);
}
let full = FullDocumentDiagnosticReport {
result_id: Some(result_id.clone()),
items: self.diagnostics_of(&uri),
};
WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport {
uri,
version: None,
full_document_diagnostic_report: full,
})
})
.collect();
WorkspaceDiagnosticReport { items }
}
/// What a report is stamped with: the generation everything was computed
/// against. Coarse on purpose — a change anywhere costs one extra full
/// report elsewhere, and a stale "unchanged" would cost a wrong squiggle.
fn result_id(&self) -> String {
self.generation.to_string()
}
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
self.workspace.document(uri).map(diagnostics::all).unwrap_or_default()
}
// ------------------------------------------------------------------
// notifications
// ------------------------------------------------------------------
fn notification(&mut self, notification: Notification) {
let method = notification.method.clone();
match method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
let uri = p.text_document.uri;
self.set_document(uri.clone(), p.text_document.text);
// With no workspace root the index's scope *is* the open
// buffers' own directories, so opening a file widens it.
// With a root, nothing about the scope changed and the
// save path still owns rebuilding.
if self.workspace.has_roots() {
self.publish(&uri);
} else {
self.reindex();
}
}
}
DidChangeTextDocument::METHOD => {
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
// Incremental sync: the changes are ranges into the buffer
// we hold, applied in order. A full-sync client's
// rangeless change still replaces the whole buffer, so
// "the last one wins" stays true for it. One notification
// is one `set_document` — one reparse, one generation
// bump — however many ranges it carried.
if p.content_changes.is_empty() {
return;
}
let uri = p.text_document.uri;
let base = self.workspace.document(&uri).map_or("", |doc| doc.text.as_str());
let text = sync::apply_changes(base, &p.content_changes);
self.set_document(uri.clone(), text);
self.publish(&uri);
}
}
DidSaveTextDocument::METHOD => {
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
}
// A save is one of the things that rebuild the index; the
// others are a change to `lucisv.exclude`/`lucisv.filelist`
// below, and a watched file changing on disk. The
// staleness window that is left is in the feature README.
self.reindex();
}
}
// Something changed on disk that no buffer told us about — a `git
// pull`, a checkout, a generated file, an externally edited
// filelist. One rebuild per *notification*, never one per file:
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
self.reindex();
}
}
}
// The `lucisv.*` settings, pushed at startup and on every change.
// Nothing here trusts the payload — `settings::from_payload`
// drops whatever it cannot use.
DidChangeConfiguration::METHOD => {
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
let pushed = settings::from_payload(&p.settings);
let watched = self.workspace.filelist_path();
// Only `exclude` and `filelist` change which files exist
// as far as this server is concerned; the other two are
// read afresh by the next formatting request and need no
// invalidation.
if self.workspace.set_client_settings(pushed) {
self.reindex();
}
// The watched filelist path is baked into the
// registration, so a new one needs a new registration.
if self.workspace.filelist_path() != watched {
self.register_watchers();
}
}
}
DidCloseTextDocument::METHOD => {
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
let uri = p.text_document.uri;
self.config_warnings.remove(&uri);
// The remembered token answer goes with the buffer: the
// client drops what it was holding too, and nothing may
// grow with the number of files ever opened.
self.tokens.remove(&uri);
self.workspace.close_document(&uri);
// Clear what we drew: the buffer is gone.
self.send_diagnostics(uri, Vec::new());
}
}
_ => {}
}
}
// ------------------------------------------------------------------
// responses to what we asked
// ------------------------------------------------------------------
/// What the client answered.
///
/// Only a `workspace/applyEdit` answer is read. Nothing else this server
/// asks of the client has an answer worth acting on: one that refuses the
/// file-watcher (un)registration simply keeps the save-only staleness
/// model; one that errors a `window/workDoneProgress/create` renders no
/// bar and ignores the `$/progress` that named that token, per spec; one
/// that declines a `workspace/codeLens/refresh` keeps the counts it has,
/// and the next save asks again; and one that could not open a
/// `window/showDocument` has already told the user so itself. None of
/// those ids is ever in `applying`, so they all fall out here.
fn response(&mut self, response: Response) {
let Some(command) = self.applying.remove(&response.id) else { return };
// A refusal is worth saying out loud: the user ran a command, watched
// nothing happen, and would otherwise have no idea why. An answer that
// does not parse is a refusal too — nothing was seen to be applied.
let reason = match response.response_result {
Ok(value) => match serde_json::from_value::<ApplyWorkspaceEditResponse>(value) {
Ok(applied) if applied.applied => return,
Ok(applied) => applied.failure_reason,
Err(problem) => Some(problem.to_string()),
},
Err(error) => Some(error.message),
};
let message = match reason {
Some(reason) => {
format!("lucisv: {command} — the editor did not apply the edit: {reason}")
}
None => format!("lucisv: {command} — the editor did not apply the edit."),
};
self.show_message(MessageType::ERROR, message);
}
// ------------------------------------------------------------------
// outgoing
// ------------------------------------------------------------------
/// Ask the client to watch the source files and the filelist for us,
/// replacing any registration already in force.
///
/// Silent for a client that cannot be asked — that one keeps the save-only
/// staleness model, which is what it had before this feature existed.
fn register_watchers(&mut self) {
if !self.abilities.file_watching {
return;
}
// Unregister first, so a client that keys watchers by id is never
// holding two registrations that both fire for `**/*.sv`.
if let Some(id) = self.watchers.take() {
let params = UnregistrationParams { unregisterations: vec![watch::unregistration(id)] };
self.send_request(UnregisterCapability::METHOD, params);
}
let filelist = self.workspace.filelist_path();
let registration = watch::registration(self.registrations, filelist.as_deref());
self.registrations += 1;
self.watchers = Some(registration.id.clone());
let params = RegistrationParams { registrations: vec![registration] };
self.send_request(RegisterCapability::METHOD, params);
}
/// Ask the client something, reporting the id it will answer on — a
/// repeated id is a protocol error, so this only ever counts up.
fn send_request(&mut self, method: &str, params: impl serde::Serialize) -> RequestId {
let id = RequestId::from(format!("lucisv-{}", self.request_ids));
self.request_ids += 1;
let request = Request::new(id.clone(), method.to_string(), params);
// A closed channel means the client is gone; there is nobody left to
// report the failure to.
let _ = self.connection.sender.send(Message::Request(request));
id
}
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
/// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk.
fn reindex(&mut self) {
let bar = self.begin_indexing();
let warnings = self.workspace.rebuild_index();
self.end_indexing(bar);
// A rescan can change any module's instantiation count, so every lens
// a client is holding may now read wrong. Sent after the bar comes
// down, for the same reason the bar comes down before the republishes:
// the bar names the scan, and everything after it is work done on the
// scan's result.
self.refresh_code_lenses();
// Every open buffer's diagnostics are computed against the index, so a
// pulling client's cached answers are all stale from here.
self.generation += 1;
self.report_scope(warnings);
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
}
/// Put a progress bar up for the rescan that is about to run, and report
/// the token it must be taken down with. `None` for a client that cannot
/// show one — the spec forbids creating progress it never asked for.
///
/// The `begin` goes out immediately after the `create`, without waiting
/// for its answer: the rescan blocks this thread the moment this returns,
/// so waiting would mean the bar appears only once the work it describes
/// is over. The spec allows it, and a client that errors the `create`
/// ignores the `$/progress` that follows.
///
/// No percentage and no intermediate report: the rescan is one opaque call
/// into `Workspace`, and an invented percentage is worse than none.
fn begin_indexing(&mut self) -> Option<ProgressToken> {
if !self.abilities.work_done_progress {
return None;
}
let token = ProgressToken::String(format!("lucisv-index-{}", self.indexings));
self.indexings += 1;
let params = WorkDoneProgressCreateParams { token: token.clone() };
self.send_request(WorkDoneProgressCreate::METHOD, params);
self.progress(
token.clone(),
WorkDoneProgress::Begin(WorkDoneProgressBegin {
title: INDEXING_TITLE.to_string(),
// Nothing already running in this server can be cancelled: the
// loop is one thread and a rescan runs to completion — the
// `$/cancelRequest` support only answers requests still
// queued. Saying so is what keeps a cancel button the user
// could press off the bar.
cancellable: Some(false),
..Default::default()
}),
);
Some(token)
}
/// Take the bar down, naming what the rescan found. The count is the
/// index's own file list, which is the only number this costs nothing to
/// know. Called the moment the rescan returns, before the scope warnings
/// and the republishes — the bar names the scan, and what follows it is
/// per-open-buffer work the user already pays on every keystroke.
fn end_indexing(&self, token: Option<ProgressToken>) {
let Some(token) = token else { return };
let files = self.workspace.index().files().len();
let plural = if files == 1 { "" } else { "s" };
let message = Some(format!("{files} file{plural} indexed"));
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message }));
}
/// Ask the client to re-request its code lenses, because the rescan just
/// finished may have changed every instantiation count in every buffer it
/// is showing.
///
/// Silent for a client that did not advertise
/// `workspace.codeLens.refreshSupport` — the request is server-initiated
/// and the spec makes that capability the gate. Nothing is sent at startup
/// either: no buffer is open there, so there are no lenses to invalidate.
/// The answer is ignorable and rides `response`'s fall-through path.
fn refresh_code_lenses(&mut self) {
if !self.abilities.code_lens_refresh {
return;
}
self.send_request(CodeLensRefresh::METHOD, ());
}
/// One `$/progress` notification for a token the client already knows.
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
let params = ProgressParams { token, value: ProgressParamsValue::WorkDone(value) };
self.notify(Progress::METHOD, params);
}
/// Say what went wrong while working out which files to index — a
/// filelist naming a file that has moved, an unset variable, an option
/// lucisv does not know.
///
/// Every one is logged, but only the first is *shown*: a filelist that has
/// drifted from the tree can easily carry forty stale paths, and forty
/// popups would be worse than the problem. Said once per rebuild, which is
/// once per save — the same rhythm the `lucisv.toml` warning has.
fn report_scope(&self, warnings: Vec<String>) {
for warning in &warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
let Some(first) = warnings.first() else { return };
let rest = warnings.len() - 1;
let message = match rest {
0 => format!("lucisv: {first}"),
_ => format!("lucisv: {first} (and {rest} more — see the lucisv log)"),
};
self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message });
}
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
/// has moved on, and a config problem is worth saying once more.
fn set_document(&mut self, uri: Uri, text: String) {
self.config_warnings.remove(&uri);
self.workspace.set_document(uri, text);
self.generation += 1;
}
/// Publish everything known about a buffer — parse errors and lint
/// warnings — in one notification. Two publishes for one version would
/// leave only the second on screen, since LSP replaces rather than merges.
fn publish(&self, uri: &Uri) {
// `send_diagnostics` would drop this anyway for a pulling client; the
// early return is so the parse+lint pass is not run for nobody, once
// per open buffer, on every index rebuild.
if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() {
return;
}
self.send_diagnostics(uri.clone(), self.diagnostics_of(uri));
}
/// Push one buffer's diagnostics — unless the client pulls them.
///
/// A client that advertised `textDocument.diagnostic` owns the timing and
/// the lifecycle of every diagnostic it shows: it asks when it wants them
/// and drops them when it closes the document, so a push would be a second
/// set of squiggles arriving on a schedule it did not choose. This is the
/// one gate that keeps the two models from ever running for one client —
/// the `didClose` clear goes through here too, for the same reason.
fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
if self.abilities.pull_diagnostics {
return;
}
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
self.notify(PublishDiagnostics::METHOD, params);
}
fn show_message(&self, typ: MessageType, message: String) {
self.notify(ShowMessage::METHOD, ShowMessageParams { typ, message: message.clone() });
self.notify(LogMessage::METHOD, LogMessageParams { typ, message });
}
fn notify(&self, method: &str, params: impl serde::Serialize) {
let notification = Notification::new(method.to_string(), params);
// A closed channel means the client is gone; there is nobody left to
// report the failure to.
let _ = self.connection.sender.send(Message::Notification(notification));
}
/// The byte offset an LSP position names in an open document.
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
}
}
// ----------------------------------------------------------------------
// cancellation
// ----------------------------------------------------------------------
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
/// answer to that question private, so it is asked here by method name — the
/// same name `handle_shutdown` matches on.
fn is_shutdown(message: &Message) -> bool {
matches!(message, Message::Request(request) if request.method == Shutdown::METHOD)
}
/// `first` plus everything already waiting on the queue behind it — the
/// client's backlog, in arrival order. Never blocks: what is not there yet
/// belongs to the next burst.
fn burst(queue: &std::sync::mpsc::Receiver<Message>, first: Message) -> Vec<Message> {
let mut batch = vec![first];
while let Ok(message) = queue.try_recv() {
batch.push(message);
}
batch
}
/// The ids this burst cancels: every `$/cancelRequest` in it that names a
/// request the burst *also* carries.
///
/// A cancel naming anything else is dropped right here — it refers to a
/// request answered in some earlier burst, or to one this server never
/// received, and either way there is nothing left to cancel. That is what
/// keeps this from becoming a set that grows for the life of the session.
fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
let queued: HashSet<&RequestId> = batch
.iter()
.filter_map(|message| match message {
Message::Request(request) => Some(&request.id),
_ => None,
})
.collect();
batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect()
}
/// The request id a `$/cancelRequest` names, or `None` for any other message.
/// Both id forms the protocol allows are read; a cancel whose params do not
/// parse is dropped, because there is no id to act on.
fn cancelled_id(message: &Message) -> Option<RequestId> {
let Message::Notification(notification) = message else { return None };
if notification.method != Cancel::METHOD {
return None;
}
let params: CancelParams = serde_json::from_value(notification.params.clone()).ok()?;
Some(match params.id {
NumberOrString::Number(number) => RequestId::from(number),
NumberOrString::String(text) => RequestId::from(text),
})
}
/// What a cancelled request is answered with. Every request gets exactly one
/// response, cancelled or not — the protocol's own `RequestCancelled`
/// (-32800), which a client reads as "the one you asked me to drop" rather
/// than as a failure worth showing the user.
fn cancelled_response(id: RequestId) -> Response {
Response::new_err(
id,
lsp_server::ErrorCode::RequestCanceled as i32,
"lucisv: request cancelled by the client".to_string(),
)
}
// ----------------------------------------------------------------------
// decoding and failures
// ----------------------------------------------------------------------
/// Why a request could not be answered, in the protocol's own terms.
enum Failure {
MethodNotFound(String),
InvalidParams(String),
Internal(String),
/// The request was well-formed and the server declined it, with a reason
/// meant for the user — LSP's `RequestFailed`.
Request(String),
}
impl Failure {
fn into_response(self, id: RequestId) -> Response {
let (code, message) = match self {
Failure::MethodNotFound(method) => (
lsp_server::ErrorCode::MethodNotFound as i32,
format!("unhandled method: {method}"),
),
Failure::InvalidParams(message) => {
(lsp_server::ErrorCode::InvalidParams as i32, message)
}
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
Failure::Request(message) => {
(lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}"))
}
};
Response::new_err(id, code, message)
}
}
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
}
fn to_value(value: impl serde::Serialize) -> Result<Value, Failure> {
serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string()))
}
/// A notification's params, or `Err` when they do not parse — a malformed
/// notification is dropped, because there is no id to answer it on.
fn extract<P: DeserializeOwned>(
notification: Notification,
) -> Result<P, ExtractError<Notification>> {
let method = notification.method.clone();
notification.extract(&method)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use lsp_types::{FileChangeType, FileEvent};
use crate::uri::path_to_uri;
/// A scratch workspace root, removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_watch_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
.expect("write");
}
fn write(&self, rel: &str, text: &str) {
std::fs::write(self.path.join(rel), text).expect("write");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A real `Server` on an in-memory connection, plus the client end of it —
/// so a test can drive a notification and read every message it produced.
struct Session {
server: Server,
client: Connection,
}
impl Session {
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
Session::with(roots, ClientAbilities { file_watching, ..Default::default() })
}
/// A session against a client that said exactly `abilities`.
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
let (server_end, client) = Connection::memory();
let server = Server::new(server_end, roots, abilities);
Session { server, client }
}
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
self.server.notification(Notification::new(method.to_string(), params));
}
/// Drive one request through the real dispatch, as the loop would.
fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response {
let id = RequestId::from(format!("test-{method}"));
self.server.request(Request::new(id, method.to_string(), params))
}
/// A request's result, or the reason it was refused.
fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value {
match self.request(method, params).response_result {
Ok(value) => value,
Err(error) => panic!("{method} failed: {error:?}"),
}
}
/// Answer the last request the server made of us.
fn answer(&mut self, id: RequestId, result: impl serde::Serialize) {
self.server.response(Response::new_ok(id, result));
}
/// Everything the server has said since the last drain.
fn drain(&self) -> Vec<Message> {
self.client.receiver.try_iter().collect()
}
/// The requests the server has made of the client, as (method, params).
fn requests(&self) -> Vec<(String, Value)> {
self.sent().into_iter().map(|request| (request.method, request.params)).collect()
}
/// The requests the server has made of the client, ids included.
fn sent(&self) -> Vec<Request> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Request(request) => Some(request),
_ => None,
})
.collect()
}
/// Every progress message since the last drain, in order, as
/// (step, token) — one `create` per request, one `begin`/`report`/`end`
/// per `$/progress`. Order and token are the whole protocol here.
fn progress(&self) -> Vec<(&'static str, String)> {
self.drain().into_iter().filter_map(progress_step).collect()
}
/// The `message` on every `$/progress` end since the last drain.
fn ended(&self) -> Vec<Option<String>> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams =
serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
match work {
WorkDoneProgress::End(end) => Some(end.message),
_ => None,
}
}
_ => None,
})
.collect()
}
/// What the server showed the user since the last drain, as
/// (type, message).
fn shown(&self) -> Vec<(MessageType, String)> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == ShowMessage::METHOD => {
let params: ShowMessageParams =
serde_json::from_value(n.params).expect("show message params");
Some((params.typ, params.message))
}
_ => None,
})
.collect()
}
/// How many diagnostics publishes the server pushed since the last
/// drain. With exactly one open buffer this counts index rebuilds:
/// `reindex` republishes every open document, once.
fn publishes(&self) -> usize {
self.drain()
.iter()
.filter(|message| match message {
Message::Notification(n) => n.method == PublishDiagnostics::METHOD,
_ => false,
})
.count()
}
/// The diagnostics the server pushed since the last drain.
fn published(&self) -> Vec<PublishDiagnosticsParams> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
Some(serde_json::from_value(n.params).expect("publish params"))
}
_ => None,
})
.collect()
}
fn open(&mut self, path: &Path, text: &str) -> Uri {
let uri = path_to_uri(path).expect("uri");
self.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": {
"uri": uri, "languageId": "systemverilog",
"version": 1, "text": text,
}
}),
);
uri
}
/// Drive one burst through the real loop body — the whole of `run`
/// except the receiving — reporting whether the client shut us down.
fn batch(&mut self, messages: Vec<Message>) -> bool {
self.server.process_batch(messages).expect("the burst is handled")
}
/// The responses the server sent since the last drain, in order.
fn answers(&self) -> Vec<Response> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Response(response) => Some(response),
_ => None,
})
.collect()
}
fn watched(&mut self, paths: &[PathBuf]) {
let changes: Vec<FileEvent> = paths
.iter()
.map(|path| FileEvent {
uri: path_to_uri(path).expect("uri"),
typ: FileChangeType::CHANGED,
})
.collect();
self.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
}
/// One message's place in the progress protocol, or `None` when it is not
/// progress at all.
fn progress_step(message: Message) -> Option<(&'static str, String)> {
match message {
Message::Request(request) if request.method == WorkDoneProgressCreate::METHOD => {
let params: WorkDoneProgressCreateParams =
serde_json::from_value(request.params).expect("create params");
Some(("create", token_text(&params.token)))
}
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams =
serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
let step = match work {
WorkDoneProgress::Begin(_) => "begin",
WorkDoneProgress::Report(_) => "report",
WorkDoneProgress::End(_) => "end",
};
Some((step, token_text(&params.token)))
}
_ => None,
}
}
fn token_text(token: &ProgressToken) -> String {
match token {
ProgressToken::String(text) => text.clone(),
ProgressToken::Number(number) => number.to_string(),
}
}
/// A client that shows a progress bar and nothing else.
fn watching_progress() -> ClientAbilities {
ClientAbilities { work_done_progress: true, ..Default::default() }
}
#[test]
fn the_startup_index_build_runs_under_the_first_bar() {
// It is the slowest rescan of the session, and it happens after
// `initialize_finish` — the earliest moment a server request is legal.
let tree = Tree::new("progressstartup");
tree.package("rtl/a.sv", "a");
let session = Session::with(vec![tree.path.clone()], watching_progress());
assert_eq!(
session.progress(),
vec![
("create", "lucisv-index-0".to_string()),
("begin", "lucisv-index-0".to_string()),
("end", "lucisv-index-0".to_string()),
]
);
}
#[test]
fn a_save_puts_a_bar_up_and_takes_it_down_again() {
let tree = Tree::new("progresssave");
tree.package("rtl/a.sv", "a");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
// One create, one begin, one end — the save's own token, not the
// startup one.
assert_eq!(
session.progress(),
vec![
("create", "lucisv-index-1".to_string()),
("begin", "lucisv-index-1".to_string()),
("end", "lucisv-index-1".to_string()),
]
);
}
#[test]
fn the_bar_says_how_many_files_were_indexed() {
// The one number this costs nothing to know: the index's own file
// list. Anything richer would mean plumbing a count through
// `rebuild_index`.
let tree = Tree::new("progresscount");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
let session = Session::with(vec![tree.path.clone()], watching_progress());
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())]);
let one = Tree::new("progresscountone");
one.package("rtl/a.sv", "a");
let session = Session::with(vec![one.path.clone()], watching_progress());
assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`");
}
#[test]
fn the_bar_is_down_before_the_republish() {
// Pinned because either order is defensible and a reader would
// wonder: the bar names the *scan*, so it ends the moment the scan
// returns — the republish that follows is per-open-buffer work the
// user already pays on every keystroke.
let tree = Tree::new("progressorder");
tree.package("rtl/a.sv", "a");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let order: Vec<String> = session
.drain()
.into_iter()
.filter_map(|message| match &message {
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
Some("publish".to_string())
}
_ => progress_step(message).map(|(step, _)| step.to_string()),
})
.collect();
assert_eq!(order, vec!["create", "begin", "end", "publish"]);
}
#[test]
fn a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all() {
// The spec forbids server-initiated progress without the capability,
// so this is not a cosmetic difference: it is a protocol violation
// avoided.
let tree = Tree::new("progressnone");
tree.package("rtl/a.sv", "a");
let mut session = Session::new(vec![tree.path.clone()], true);
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
assert!(session.progress().is_empty(), "not even at startup");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert!(session.progress().is_empty(), "and not on a save either");
// The watcher registration is the only thing such a client is asked.
let session = Session::new(vec![tree.path.clone()], false);
assert!(session.requests().is_empty(), "nothing at all is asked of it");
}
#[test]
fn every_rescan_path_gets_its_own_bar_and_its_own_token() {
// The three non-startup callers of `reindex`: a save, a watched file,
// and a changed scope. One begin/end pair each, and no token twice.
let tree = Tree::new("progresspaths");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
session.watched(&[tree.path.join("rtl/a.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
);
let steps = session.progress();
let begins: Vec<&String> =
steps.iter().filter(|(step, _)| *step == "begin").map(|(_, token)| token).collect();
let ends: Vec<&String> =
steps.iter().filter(|(step, _)| *step == "end").map(|(_, token)| token).collect();
assert_eq!(
begins,
vec!["lucisv-index-1", "lucisv-index-2", "lucisv-index-3"],
"{steps:#?}"
);
assert_eq!(ends, begins, "every bar that went up came down");
assert!(steps.iter().all(|(step, _)| *step != "report"), "no invented percentages");
}
#[test]
fn a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit() {
// Both request kinds are in flight at once. The progress answers —
// one `Ok`, one `Err` — must fall straight through `response`, and the
// one `applyEdit` answer must still be the one that speaks.
let abilities =
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
let (tree, mut session, params) = propagating("progressapplyedit", abilities);
let _ = session.drain();
let result = session.result(ExecuteCommand::METHOD, params);
assert!(result.is_null(), "the edit was pushed, not returned");
// Force a rescan while the edit is outstanding, so a progress create
// sits between the push and its answer.
session.watched(&[tree.path.join("sub.sv")]);
let sent = session.sent();
let edit = sent
.iter()
.find(|request| request.method == ApplyWorkspaceEdit::METHOD)
.expect("the push");
let creates: Vec<&Request> =
sent.iter().filter(|r| r.method == WorkDoneProgressCreate::METHOD).collect();
assert_eq!(creates.len(), 1, "one rescan, one create: {sent:#?}");
// Answer the create both ways a client can, then refuse the edit.
session.answer(creates[0].id.clone(), serde_json::json!(null));
session.server.response(Response::new_err(
creates[0].id.clone(),
lsp_server::ErrorCode::MethodNotFound as i32,
"no progress here".to_string(),
));
assert!(session.shown().is_empty(), "a create answer says nothing to the user");
session.answer(edit.id.clone(), serde_json::json!({ "applied": false }));
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
}
#[test]
fn a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too() {
// The reverse interleaving from the test above: here the outstanding
// `applyEdit` is answered first, and the progress `create` for a
// rescan that started while it was outstanding answers only after.
// Same fall-through path in `response`, opposite arrival order — both
// must leave the refusal-reporting untouched.
let abilities =
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
let (tree, mut session, params) = propagating("progressapplyedit2", abilities);
let _ = session.drain();
let result = session.result(ExecuteCommand::METHOD, params);
assert!(result.is_null(), "the edit was pushed, not returned");
session.watched(&[tree.path.join("sub.sv")]);
let sent = session.sent();
let edit = sent
.iter()
.find(|request| request.method == ApplyWorkspaceEdit::METHOD)
.expect("the push");
let create = sent
.iter()
.find(|request| request.method == WorkDoneProgressCreate::METHOD)
.expect("the create");
// The edit resolves first, cleanly...
session.answer(edit.id.clone(), serde_json::json!({ "applied": true }));
assert!(session.shown().is_empty(), "an accepted edit says nothing to the user");
// ...and only afterward does the create answer arrive, for a bar that
// came down long ago. It must still fall straight through.
session.server.response(Response::new_ok(create.id.clone(), serde_json::json!(null)));
assert!(session.shown().is_empty(), "a late create answer says nothing either");
}
#[test]
fn the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down() {
// `Server::new` now asks a fully-capable client two things at
// startup: the progress create/begin/end around `open_roots`, then
// `register_watchers`. This pins the order the restructuring must
// preserve — the watcher request must not land in the middle of the
// bar it was rewritten to make room for.
let tree = Tree::new("progressandwatchers");
tree.package("rtl/a.sv", "a");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::with(vec![tree.path.clone()], abilities);
let order: Vec<String> = session
.drain()
.into_iter()
.filter_map(|message| match &message {
Message::Request(request) if request.method == RegisterCapability::METHOD => {
Some("register".to_string())
}
_ => progress_step(message).map(|(step, _)| step.to_string()),
})
.collect();
assert_eq!(order, vec!["create", "begin", "end", "register"], "{order:?}");
}
#[test]
fn a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either() {
// The existing off-test drives only startup and a save. `begin_indexing`
// is called from the same `reindex()` on all three rescan triggers, but
// the other two deserve their own witness rather than resting on that
// being obvious from reading the code.
let tree = Tree::new("progressnonewatch");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
let mut session = Session::new(vec![tree.path.clone()], true);
let _ = session.drain();
session.watched(&[tree.path.join("rtl/a.sv")]);
assert!(session.progress().is_empty(), "not on a watched file change");
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
);
assert!(session.progress().is_empty(), "not on a changed filelist either");
}
#[test]
fn a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_crashing() {
// No roots and no open buffers: `sibling_files` has nothing to walk,
// so the index is empty. The end message must still be honest — and
// the plural rule still holds, "0 files" and not "0 file".
let session = Session::with(Vec::new(), watching_progress());
assert_eq!(session.ended(), vec![Some("0 files indexed".to_string())]);
}
/// How many times the index holds a package of this name.
fn indexed(session: &Session, name: &str) -> usize {
session.server.workspace.index().member(name, "K").len()
}
#[test]
fn a_client_that_did_not_ask_is_never_sent_a_registration() {
// Such a client keeps the save-only staleness model, and must not be
// sent a request it has no handler for.
let tree = Tree::new("noregister");
let session = Session::new(vec![tree.path.clone()], false);
assert!(session.requests().is_empty(), "nothing may be asked of it");
}
#[test]
fn a_client_that_asked_is_registered_after_initialized() {
let tree = Tree::new("register");
let session = Session::new(vec![tree.path.clone()], true);
let requests = session.requests();
assert_eq!(requests.len(), 1, "{requests:#?}");
assert_eq!(requests[0].0, RegisterCapability::METHOD);
assert_eq!(
requests[0].1,
serde_json::json!({
"registrations": [{
"id": "lucisv-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": {
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
},
}]
})
);
}
#[test]
fn a_configured_filelist_is_watched_too() {
let tree = Tree::new("registerfilelist");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let session = Session::new(vec![tree.path.clone()], true);
let requests = session.requests();
let watchers = &requests[0].1["registrations"][0]["registerOptions"]["watchers"];
assert_eq!(
watchers,
&serde_json::json!([
{ "globPattern": "**/*.{v,vh,sv,svh}" },
{ "globPattern": tree.path.join("files.f").to_str().expect("utf-8") },
]),
"the filelist is watched by its own path"
);
}
/// A `lucisv.filelist` push, in the shape a client sends it.
fn filelist_push(path: &str) -> Value {
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
}
#[test]
fn a_new_filelist_setting_replaces_the_registration() {
// The watched path is baked into the registration, so the old one must
// go and a new one take its place — otherwise the new filelist is
// exactly the file nobody is watching.
let tree = Tree::new("rewatch");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
tree.write("other.f", "rtl/a.sv\n");
let mut session = Session::new(vec![tree.path.clone()], true);
assert_eq!(session.requests().len(), 1, "the registration made at startup");
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-0");
assert_eq!(requests[1].0, RegisterCapability::METHOD);
let registration = &requests[1].1["registrations"][0];
assert_eq!(registration["id"], "lucisv-watched-files-1", "a fresh id");
assert_eq!(
registration["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("files.f").to_str().expect("utf-8").to_string()
);
// The same value again moves nothing, so nothing is re-registered.
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
assert!(session.requests().is_empty(), "re-pushing the same path is not a change");
// A different one is.
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-1");
assert_eq!(
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("other.f").to_str().expect("utf-8").to_string()
);
}
#[test]
fn a_client_that_did_not_ask_is_not_re_registered_either() {
let tree = Tree::new("norewatch");
tree.write("files.f", "\n");
let mut session = Session::new(vec![tree.path.clone()], false);
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
assert!(session.requests().is_empty());
}
#[test]
fn one_notification_rebuilds_the_index_once_however_many_files_it_names() {
// The `git checkout` shape. Rebuilding per event would re-scan the
// workspace once per changed file for a single answer.
let tree = Tree::new("oncepernotification");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
for i in 0..40 {
tree.package(&format!("rtl/f{i}.sv"), &format!("p{i}"));
}
let changed: Vec<PathBuf> =
(0..40).map(|i| tree.path.join(format!("rtl/f{i}.sv"))).collect();
session.watched(&changed);
assert_eq!(session.publishes(), 1, "one rebuild for the whole list");
assert_eq!(indexed(&session, "p0"), 1, "and it really did rebuild");
assert_eq!(indexed(&session, "p39"), 1);
}
#[test]
fn a_created_file_reaches_the_index_with_no_save_anywhere() {
let tree = Tree::new("created");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(indexed(&session, "pulled"), 0, "premise: not there yet");
tree.package("rtl/pulled.sv", "pulled");
session.watched(&[tree.path.join("rtl/pulled.sv")]);
assert_eq!(indexed(&session, "pulled"), 1, "the `git pull` case");
// ... and a deletion is a change in the other direction.
std::fs::remove_file(tree.path.join("rtl/pulled.sv")).expect("remove");
session.watched(&[tree.path.join("rtl/pulled.sv")]);
assert_eq!(indexed(&session, "pulled"), 0, "the `git checkout` case");
}
#[test]
fn an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing() {
// The ladder re-applies during the rebuild, so an unlisted file stays
// unlisted — and one rebuild for a stray in-tree source is cheaper than
// deciding, per event, whether the filelist names it.
let tree = Tree::new("outsidescope");
tree.package("rtl/a.sv", "a");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "rtl/a.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
session.watched(&[tree.path.join("rtl/unlisted.sv")]);
assert_eq!(indexed(&session, "a"), 1, "the listed file survives the rebuild");
assert_eq!(indexed(&session, "unlisted"), 0, "and the unlisted one stays out");
}
#[test]
fn an_unrelated_file_event_costs_no_rebuild() {
let tree = Tree::new("stray");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
session.watched(&[tree.path.join("README.md"), tree.path.join("target/build.log")]);
assert_eq!(session.publishes(), 0, "a stray event is dropped, not re-scanned");
session.notify(
DidChangeWatchedFiles::METHOD,
DidChangeWatchedFilesParams { changes: Vec::new() },
);
assert_eq!(session.publishes(), 0, "and so is an empty notification");
}
#[test]
fn an_open_buffer_still_beats_disk_after_a_watched_file_rebuild() {
// The rule the rebuild has always had, checked on the new path into
// it: an external change must never clobber what the user is looking
// at. Here the file on disk is *also* the open one, rewritten behind
// the editor's back — the buffer still wins.
let tree = Tree::new("overlay");
tree.package("rtl/open.sv", "on_disk");
let path = tree.path.join("rtl/open.sv");
let mut session = Session::new(vec![tree.path.clone()], true);
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
tree.package("rtl/open.sv", "rewritten_on_disk");
session.watched(std::slice::from_ref(&path));
assert_eq!(indexed(&session, "in_buffer"), 1, "the buffer wins the rebuild");
assert_eq!(indexed(&session, "rewritten_on_disk"), 0, "disk loses");
assert_eq!(indexed(&session, "on_disk"), 0, "and the stale copy is gone");
let doc = session.server.workspace.document(&uri).expect("still open");
assert!(doc.text.contains("in_buffer"), "and the buffer's own text is untouched");
}
#[test]
fn the_uri_helper_and_the_watch_filter_agree_about_the_filelist() {
// `touches_scope` compares paths, and the path it compares against is
// whatever `filelist_path` resolved — a mismatch would silently stop
// filelist edits from rebuilding anything.
let tree = Tree::new("filelistevent");
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.write("files.f", "rtl/a.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
let _ = session.drain();
assert_eq!(indexed(&session, "b"), 0, "premise: not listed yet");
tree.write("files.f", "rtl/a.sv\nrtl/b.sv\n");
session.watched(&[tree.path.join("files.f")]);
assert_eq!(session.publishes(), 1, "the filelist's own edit rebuilds");
assert_eq!(indexed(&session, "b"), 1, "and the newly listed file is in");
}
#[test]
fn a_malformed_watched_files_notification_is_dropped() {
let tree = Tree::new("malformed");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
let _ = session.drain();
session.notify(DidChangeWatchedFiles::METHOD, serde_json::json!({ "changes": "nonsense" }));
assert_eq!(session.publishes(), 0, "no id to answer on, so nothing happens");
}
#[test]
fn a_non_file_uri_in_an_event_is_ignored() {
let tree = Tree::new("nonfileuri");
tree.package("rtl/open.sv", "open_pkg");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(
&tree.path.join("rtl/open.sv"),
"package open_pkg;\n localparam K = 1;\nendpackage\n",
);
let _ = session.drain();
let changes = vec![FileEvent {
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
typ: FileChangeType::CREATED,
}];
session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
assert_eq!(session.publishes(), 0);
}
// ------------------------------------------------------------------
// `workspace/applyEdit`
// ------------------------------------------------------------------
const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
/// A two-module workspace with `top.sv` open, and the arguments that ask
/// for the one port its instantiation is missing.
fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) {
let tree = Tree::new(name);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("top.sv"), TOP);
let _ = session.drain();
let params = serde_json::json!({
"command": ports::PROPAGATE_PORTS,
"arguments": [uri, { "line": 2, "character": 6 }],
});
(tree, session, params)
}
#[test]
fn a_command_pushes_its_edit_when_the_client_can_apply_one() {
// The bug this fixes: the edit used to be the request *result*, which
// the protocol does not define and every stock client drops.
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
let (_tree, mut session, params) = propagating("applyedit", abilities);
let result = session.result(ExecuteCommand::METHOD, params);
assert_eq!(result, Value::Null, "the edit is not the result any more");
let sent = session.sent();
assert_eq!(sent.len(), 1, "{sent:#?}");
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
assert_eq!(
sent[0].params["label"],
serde_json::json!(format!("lucisv: {}", ports::PROPAGATE_PORTS)),
"the undo stack needs a name for it"
);
let changes = sent[0].params["edit"]["changes"].as_object().expect("changes");
let edits = changes.values().next().expect("one file edited");
assert_eq!(edits[0]["newText"], ", .rst(rst)", "{:#?}", sent[0].params);
}
#[test]
fn a_client_that_cannot_apply_edits_still_gets_the_edit_back() {
// The documented fallback: for such a client, returning the edit is
// the only thing that could ever work.
let (_tree, mut session, params) = propagating("noapplyedit", ClientAbilities::default());
let result = session.result(ExecuteCommand::METHOD, params);
let changes = result["changes"].as_object().expect("the edit is the result");
let edits = changes.values().next().expect("one file edited");
assert_eq!(edits[0]["newText"], ", .rst(rst)");
assert!(session.sent().is_empty(), "and nothing is pushed at it");
}
#[test]
fn an_edit_the_editor_refused_is_reported_to_the_user() {
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
let (_tree, mut session, params) = propagating("refused", abilities);
session.result(ExecuteCommand::METHOD, params);
let sent = session.sent();
let id = sent[0].id.clone();
session.answer(
id,
serde_json::json!({ "applied": false, "failureReason": "the file is read-only" }),
);
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
assert!(shown[0].1.contains("the file is read-only"), "{}", shown[0].1);
}
#[test]
fn an_edit_the_editor_applied_is_said_nothing_about() {
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
let (_tree, mut session, params) = propagating("applied", abilities);
session.result(ExecuteCommand::METHOD, params);
let id = session.sent()[0].id.clone();
session.answer(id.clone(), serde_json::json!({ "applied": true }));
assert!(session.shown().is_empty(), "success is silent");
// And the id is spent: a duplicate answer says nothing either.
session.answer(id, serde_json::json!({ "applied": false }));
assert!(session.shown().is_empty(), "an answer to nothing is ignored");
}
#[test]
fn a_malformed_apply_edit_answer_is_reported_as_a_refusal() {
// QA attack: "a response that does not parse is a refusal" is stated
// in the Assumptions but was only exercised through `Err` results and
// a well-typed `applied: false`. This drives the branch where the
// payload is `Ok` JSON that does not deserialize as
// `ApplyWorkspaceEditResponse` at all (missing the required `applied`
// field) — the honest-refusal path, not a panic or a silent success.
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
let (_tree, mut session, params) = propagating("malformedapplyedit", abilities);
session.result(ExecuteCommand::METHOD, params);
let id = session.sent()[0].id.clone();
session.answer(id, serde_json::json!({ "notApplied": "whatever" }));
let shown = session.shown();
assert_eq!(shown.len(), 1, "an unparseable answer must still surface: {shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
}
#[test]
fn a_response_with_a_jsonrpc_error_is_reported_too() {
// The `Err` half of `response_result` — a client that rejects the
// `applyEdit` request outright at the JSON-RPC level, rather than
// answering it with `applied: false`.
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
let (_tree, mut session, params) = propagating("rpcerror", abilities);
session.result(ExecuteCommand::METHOD, params);
let id = session.sent()[0].id.clone();
session.server.response(Response::new_err(id, 1, "internal error".to_string()));
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.contains("internal error"), "{}", shown[0].1);
}
#[test]
fn a_watcher_registration_answer_is_still_ignored() {
// The one response that was always ignored must stay ignored now that
// responses are read at all — including an error one.
let tree = Tree::new("registeranswer");
let mut session = Session::new(vec![tree.path.clone()], true);
let id = session.sent()[0].id.clone();
session.answer(id.clone(), Value::Null);
session.server.response(Response::new_err(id, 1, "no thanks".to_string()));
assert!(session.shown().is_empty(), "nothing to tell the user");
}
// ------------------------------------------------------------------
// pull diagnostics
// ------------------------------------------------------------------
/// A client that pulls diagnostics rather than being pushed them.
fn pulling() -> ClientAbilities {
ClientAbilities { pull_diagnostics: true, ..Default::default() }
}
/// A buffer with one parse error and one lint finding in it.
const BROKEN: &str = "module m;\n\twire ;\nendmodule\n";
fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value {
session.result(
DocumentDiagnosticRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"identifier": diagnostics::SOURCE,
"previousResultId": previous,
}),
)
}
#[test]
fn a_pulling_client_is_never_pushed_diagnostics() {
// Never both models for one client: the second set of squiggles would
// arrive on a schedule the client did not choose.
let tree = Tree::new("pullnopush");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let path = tree.path.join("m.sv");
let uri = session.open(&path, BROKEN);
assert_eq!(session.publishes(), 0, "`didOpen` pushed nothing");
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": BROKEN }],
}),
);
assert_eq!(session.publishes(), 0, "nor did a change");
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert_eq!(session.publishes(), 0, "nor a save's republish");
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert_eq!(session.publishes(), 0, "and the close clears nothing it never drew");
}
#[test]
fn a_pushing_client_keeps_being_pushed() {
let tree = Tree::new("pushstays");
let mut session = Session::new(vec![tree.path.clone()], false);
session.open(&tree.path.join("m.sv"), BROKEN);
assert_eq!(session.publishes(), 1, "unchanged from before this feature");
}
#[test]
fn a_pull_is_full_once_and_unchanged_until_something_moves() {
let tree = Tree::new("pullunchanged");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let first = document_pull(&mut session, &uri, None);
assert_eq!(first["kind"], "full");
assert!(!first["items"].as_array().expect("items").is_empty(), "{first:#?}");
let result_id = first["resultId"].as_str().expect("a result id").to_string();
let again = document_pull(&mut session, &uri, Some(&result_id));
assert_eq!(again["kind"], "unchanged", "nothing moved: {again:#?}");
assert_eq!(again["resultId"], serde_json::json!(result_id), "and it stays namable");
// A buffer change moves it.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module m;\n wire a;\nendmodule\n" }],
}),
);
let after = document_pull(&mut session, &uri, Some(&result_id));
assert_eq!(after["kind"], "full", "the buffer changed: {after:#?}");
assert!(after["items"].as_array().expect("items").is_empty(), "and it is clean now");
assert_ne!(after["resultId"], serde_json::json!(result_id), "a new stamp");
}
#[test]
fn an_index_rebuild_moves_the_result_id_too() {
// `inter_file_dependencies: true` is a promise: a save rebuilds the
// index, and what the index says can change what a *different* buffer
// reports. A stale "unchanged" there would be a wrong squiggle.
let tree = Tree::new("pullreindex");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let stamp = document_pull(&mut session, &uri, None)["resultId"]
.as_str()
.expect("a result id")
.to_string();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let after = document_pull(&mut session, &uri, Some(&stamp));
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
}
#[test]
fn a_pull_for_a_buffer_that_is_not_open_is_empty_rather_than_an_error() {
let tree = Tree::new("pullclosed");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
let report = document_pull(&mut session, &uri, None);
assert_eq!(report["kind"], "full");
assert!(report["items"].as_array().expect("items").is_empty());
}
#[test]
fn the_workspace_pull_reports_every_open_buffer_and_honours_its_stamps() {
let tree = Tree::new("workspacepull");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let first = session.open(&tree.path.join("a.sv"), BROKEN);
let second = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
);
let items = report["items"].as_array().expect("items").clone();
assert_eq!(items.len(), 2, "{report:#?}");
assert!(items.iter().all(|item| item["kind"] == "full"), "{report:#?}");
let uris: Vec<&str> = items.iter().map(|item| item["uri"].as_str().unwrap_or("")).collect();
assert!(uris.contains(&first.as_str()) && uris.contains(&second.as_str()), "{uris:?}");
let mut sorted = uris.clone();
sorted.sort_unstable();
assert_eq!(uris, sorted, "URI order, so two pulls of one state read alike");
let stamp = items[0]["resultId"].as_str().expect("a result id").to_string();
// Re-asked with what the client already holds, both come back unchanged.
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({
"identifier": diagnostics::SOURCE,
"previousResultIds": [
{ "uri": first, "value": stamp },
{ "uri": second, "value": stamp },
],
}),
);
let items = report["items"].as_array().expect("items");
assert_eq!(items.len(), 2);
assert!(items.iter().all(|item| item["kind"] == "unchanged"), "{items:#?}");
// A stamp from another generation is not the one we hold.
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({
"identifier": diagnostics::SOURCE,
"previousResultIds": [{ "uri": first, "value": "0" }],
}),
);
let items = report["items"].as_array().expect("items");
assert!(items.iter().all(|item| item["kind"] == "full"), "{items:#?}");
}
#[test]
fn an_empty_workspace_answers_a_well_formed_empty_report() {
// QA attack: no open buffers at all — does `workspace/diagnostic`
// still answer a well-formed (if empty) report, rather than an error
// or a missing field?
let tree = Tree::new("workspaceemptypull");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
);
assert_eq!(report["items"], serde_json::json!([]), "{report:#?}");
}
#[test]
fn a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless() {
// QA attack: the client's `previousResultIds` can name a document it
// has since closed (it does not have to prune its own cache eagerly).
// That URI is no longer among the open buffers `workspace_report`
// walks, so it must simply be absent from the answer — not an error,
// not a phantom entry.
let tree = Tree::new("workspaceclosedstamp");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let first = session.open(&tree.path.join("a.sv"), BROKEN);
let closed = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
let stamp = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
)["items"][0]["resultId"]
.as_str()
.expect("a result id")
.to_string();
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": closed } }),
);
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({
"identifier": diagnostics::SOURCE,
"previousResultIds": [
{ "uri": first, "value": stamp },
{ "uri": closed, "value": stamp },
],
}),
);
let items = report["items"].as_array().expect("items");
assert_eq!(items.len(), 1, "the closed uri is gone, not phantom-reported: {items:#?}");
assert_eq!(items[0]["uri"], first.as_str(), "{items:#?}");
}
#[test]
fn a_previous_result_id_for_a_uri_never_seen_is_ignored() {
// QA attack: a `previousResultIds` entry naming a document this
// server never opened (a client warm-starting from a stale cache, or
// simply a typo'd uri) must not confuse the match-up for the uris
// that *are* open.
let tree = Tree::new("workspaceneverseenstamp");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let opened = session.open(&tree.path.join("a.sv"), BROKEN);
let never_seen = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({
"identifier": diagnostics::SOURCE,
"previousResultIds": [{ "uri": never_seen, "value": "0" }],
}),
);
let items = report["items"].as_array().expect("items");
assert_eq!(items.len(), 1, "{items:#?}");
assert_eq!(items[0]["uri"], opened.as_str(), "{items:#?}");
assert_eq!(items[0]["kind"], "full");
}
#[test]
fn both_models_say_exactly_the_same_thing_about_a_buffer() {
// One computation, two deliveries. A second conversion path would be
// a second set of off-by-one bugs.
let tree = Tree::new("samediagnostics");
let mut pushed = Session::new(vec![tree.path.clone()], false);
pushed.open(&tree.path.join("m.sv"), BROKEN);
let published = pushed.published();
assert_eq!(published.len(), 1);
let mut pulled = Session::with(vec![tree.path.clone()], pulling());
let uri = pulled.open(&tree.path.join("m.sv"), BROKEN);
let report = document_pull(&mut pulled, &uri, None);
assert_eq!(
report["items"],
serde_json::to_value(&published[0].diagnostics).expect("diagnostics"),
);
}
// ------------------------------------------------------------------
// `textDocument/selectionRange`
// ------------------------------------------------------------------
#[test]
fn a_selection_range_request_answers_one_chain_per_position() {
let tree = Tree::new("selection");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
let result = session.result(
SelectionRangeRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"positions": [{ "line": 1, "character": 2 }, { "line": 0, "character": 0 }],
}),
);
let chains = result.as_array().expect("one chain per position");
assert_eq!(chains.len(), 2, "{result:#?}");
assert!(chains[0]["parent"].is_object(), "the innermost step has a parent");
}
#[test]
fn a_selection_range_request_for_an_unopened_buffer_answers_null() {
let tree = Tree::new("selectionclosed");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
let result = session.result(
SelectionRangeRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"positions": [{ "line": 0, "character": 0 }],
}),
);
assert_eq!(result, Value::Null);
}
// ------------------------------------------------------------------
// `textDocument/linkedEditingRange`
// ------------------------------------------------------------------
#[test]
fn a_linked_editing_request_answers_both_halves_of_a_closing_label() {
let tree = Tree::new("linked");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule : m\n");
// The cursor on the header name.
let result = session.result(
LinkedEditingRange::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": 7 },
}),
);
let ranges = result["ranges"].as_array().expect("a range list").clone();
assert_eq!(ranges.len(), 2, "{result:#?}");
assert_eq!(ranges[0]["start"], serde_json::json!({ "line": 0, "character": 7 }));
assert_eq!(ranges[1]["start"], serde_json::json!({ "line": 1, "character": 12 }));
assert!(result["wordPattern"].is_string(), "the SV word pattern is sent: {result:#?}");
// A position on no name at all declines, rather than answering an
// empty list.
let nothing = session.result(
LinkedEditingRange::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": 0 },
}),
);
assert_eq!(nothing, Value::Null);
}
#[test]
fn a_linked_editing_request_for_an_unopened_buffer_answers_null() {
let tree = Tree::new("linkedclosed");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
let result = session.result(
LinkedEditingRange::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": 0 },
}),
);
assert_eq!(result, Value::Null);
}
// ------------------------------------------------------------------
// `textDocument/codeLens`
// ------------------------------------------------------------------
/// A workspace holding `sub` and two instantiations of it, with `sub.sv`
/// open — the shape every lens test below asks about.
fn lens_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.write("sub.sv", "module sub;\nendmodule\n");
tree.write("top.sv", "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
tree
}
#[test]
fn a_code_lens_request_counts_the_workspaces_instantiations() {
let tree = lens_tree("lens");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let result = session
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let lenses = result.as_array().expect("a lens list").clone();
assert_eq!(lenses.len(), 1, "{result:#?}");
assert_eq!(lenses[0]["command"]["title"], "2 instantiations");
assert_eq!(lenses[0]["command"]["command"], lens::SHOW_INSTANTIATIONS);
assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["sub"]));
assert_eq!(lenses[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 7 }));
assert!(lenses[0]["data"].is_null(), "nothing is left for a resolve");
}
#[test]
fn a_code_lens_request_for_an_unopened_buffer_answers_null() {
let tree = lens_tree("lensclosed");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
let result = session
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert_eq!(result, Value::Null);
}
#[test]
fn the_show_instantiations_command_answers_every_site() {
let tree = lens_tree("lenscommand");
let mut session = Session::new(vec![tree.path.clone()], false);
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let result = session.result(
ExecuteCommand::METHOD,
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
);
let locations = result.as_array().expect("a location list").clone();
assert_eq!(locations.len(), 2, "{result:#?}");
assert!(locations[0]["uri"].as_str().expect("uri").ends_with("top.sv"));
assert_eq!(
locations[0]["range"]["start"],
serde_json::json!({ "line": 1, "character": 2 })
);
assert_eq!(
locations[1]["range"]["start"],
serde_json::json!({ "line": 2, "character": 2 })
);
// Nothing was pushed: this client cannot be shown a document.
assert!(session.requests().is_empty(), "no showDocument for a client without it");
}
#[test]
fn the_show_instantiations_command_pushes_a_show_document_when_it_can() {
let tree = lens_tree("lensshow");
let abilities = ClientAbilities { show_document: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
let result = session.result(
ExecuteCommand::METHOD,
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
);
assert_eq!(result.as_array().expect("locations").len(), 2, "and still the whole list");
let asked = session.requests();
assert_eq!(asked.len(), 1, "{asked:#?}");
assert_eq!(asked[0].0, ShowDocument::METHOD);
assert!(asked[0].1["uri"].as_str().expect("uri").ends_with("top.sv"));
assert_eq!(
asked[0].1["selection"]["start"],
serde_json::json!({ "line": 1, "character": 2 })
);
assert_eq!(asked[0].1["takeFocus"], true);
}
#[test]
fn a_module_with_no_instantiations_pushes_nothing_and_shows_nothing() {
let tree = Tree::new("lensempty");
tree.write("lonely.sv", "module lonely;\nendmodule\n");
let abilities = ClientAbilities { show_document: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("lonely.sv"), "module lonely;\nendmodule\n");
let _ = session.drain();
let result = session
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert_eq!(result[0]["command"]["title"], "no instantiations");
assert_eq!(result[0]["command"]["command"], "", "display-only");
let empty = session.result(
ExecuteCommand::METHOD,
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["lonely"] }),
);
assert_eq!(empty, serde_json::json!([]));
assert!(session.requests().is_empty(), "nothing to show, nothing pushed");
}
#[test]
fn the_show_instantiations_command_declines_arguments_it_cannot_read() {
let tree = lens_tree("lensbadargs");
let mut session = Session::new(vec![tree.path.clone()], false);
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let error = session
.request(
ExecuteCommand::METHOD,
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS }),
)
.response_result
.expect_err("declined");
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
assert!(error.message.contains("module name"), "{error:?}");
}
#[test]
fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
let tree = lens_tree("lensrefresh");
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
assert!(session.requests().is_empty(), "nothing to refresh at startup: no buffer is open");
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// Every rescan trigger, one refresh each.
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
session.watched(&[tree.path.join("top.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "exclude": ["nothing"] } } }),
);
let methods: Vec<String> =
session.requests().into_iter().map(|(method, _)| method).collect();
assert_eq!(
methods,
vec![CodeLensRefresh::METHOD; 3],
"one per rescan, on the save, watched-file and config paths"
);
}
#[test]
fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
let tree = lens_tree("lensnorefresh");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
session.watched(&[tree.path.join("top.sv")]);
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
#[test]
fn the_refresh_rides_after_the_indexing_bar_comes_down() {
// The documented order: the bar names the scan, and the refresh is
// work done on the scan's result — as the republishes are.
let tree = lens_tree("lensorder");
let abilities = ClientAbilities {
code_lens_refresh: true,
work_done_progress: true,
..Default::default()
};
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let order: Vec<String> = session
.drain()
.into_iter()
.filter_map(|message| match message {
Message::Request(request) if request.method == CodeLensRefresh::METHOD => {
Some("refresh".to_string())
}
other => progress_step(other).map(|(step, _)| step.to_string()),
})
.collect();
assert_eq!(order, ["create", "begin", "end", "refresh"]);
}
#[test]
fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
// `refresh_code_lenses()` is called once in `reindex()`, before the
// loop that republishes every open buffer's diagnostics — not once
// per buffer that loop republishes. Two open buffers make that
// distinction observable: a refresh-per-publish regression would
// send two.
let tree = lens_tree("qa_lensrefresh_multi");
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
session.open(
&tree.path.join("top.sv"),
"module top;\n sub u_a ();\n sub u_b ();\nendmodule\n",
);
let _ = session.drain();
session.notify(
DidSaveTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let methods: Vec<String> =
session.requests().into_iter().map(|(method, _)| method).collect();
assert_eq!(methods, vec![CodeLensRefresh::METHOD], "one refresh, not one per open buffer");
}
#[test]
fn qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding() {
// Both `deliver` (applyEdit) and `show_instantiations` (showDocument)
// push a server-initiated request and rely on the same mechanism —
// `response()` only reacts to an id it finds in `applying`, and only
// `deliver` ever inserts one. Two requests outstanding at once, one of
// each kind, must not cross-contaminate: a showDocument answer must
// not be mistaken for the applyEdit one (or vice versa), whichever
// order the client answers in.
let tree = Tree::new("qa_interleave");
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let abilities =
ClientAbilities { apply_edit: true, show_document: true, ..Default::default() };
let mut session = Session::with(vec![tree.path.clone()], abilities);
let top_uri = session.open(&tree.path.join("top.sv"), TOP);
session.open(&tree.path.join("sub.sv"), SUB);
let _ = session.drain();
// First outstanding request: an applyEdit push from a port command.
let propagate = session.result(
ExecuteCommand::METHOD,
serde_json::json!({
"command": ports::PROPAGATE_PORTS,
"arguments": [top_uri, { "line": 2, "character": 6 }],
}),
);
assert_eq!(propagate, Value::Null);
// Second outstanding request: a showDocument push from the lens's
// own command, over the same `sub` instantiation.
let sites = session.result(
ExecuteCommand::METHOD,
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
);
assert_eq!(sites.as_array().expect("locations").len(), 1);
let sent = session.sent();
assert_eq!(sent.len(), 2, "{sent:#?}");
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
assert_eq!(sent[1].method, ShowDocument::METHOD);
let apply_id = sent[0].id.clone();
let show_id = sent[1].id.clone();
// Answer the showDocument push FIRST, out of send order — it carries
// no `applied` field at all, so if `response()` ever matched it to
// the applyEdit command by anything other than its own id, this would
// either panic or wrongly report a failed edit.
session.answer(show_id, serde_json::json!({ "success": true }));
assert!(session.shown().is_empty(), "the showDocument answer must not be interpreted");
// Now answer the applyEdit push — a real success — and confirm it is
// still routed correctly to its own command.
session.answer(apply_id, serde_json::json!({ "applied": true }));
assert!(session.shown().is_empty(), "a successful apply reports nothing");
}
// ------------------------------------------------------------------
// incremental text sync
// ------------------------------------------------------------------
/// One `didChange`, carrying whatever changes were given.
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": changes,
}),
);
}
/// The text the server currently holds for a buffer.
fn buffer(session: &Session, uri: &Uri) -> String {
session.server.workspace.document(uri).expect("an open buffer").text.clone()
}
#[test]
fn incremental_changes_land_the_same_buffer_as_one_full_change() {
let tree = Tree::new("incrementalsame");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
// Three ranges, each positioned against what the last one left.
change(
&mut session,
&uri,
2,
serde_json::json!([
{ "range": { "start": { "line": 1, "character": 0 },
"end": { "line": 1, "character": 0 } }, "text": "\n" },
{ "range": { "start": { "line": 1, "character": 0 },
"end": { "line": 1, "character": 0 } }, "text": " wire " },
{ "range": { "start": { "line": 1, "character": 7 },
"end": { "line": 1, "character": 7 } }, "text": "w;" },
]),
);
let composed = "module m;\n wire w;\nendmodule\n";
assert_eq!(buffer(&session, &uri), composed);
// The same buffer reached by a full-sync client, for comparison.
let mut full = Session::new(vec![tree.path.clone()], false);
let other = full.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
change(&mut full, &other, 2, serde_json::json!([{ "text": composed }]));
assert_eq!(buffer(&full, &other), composed);
// And the answers computed from it agree, not just the text.
assert_eq!(
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
),
full.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": other },
"options": { "tabSize": 2, "insertSpaces": true },
}),
),
);
}
#[test]
fn one_notification_is_one_generation_bump_however_many_ranges() {
// The pull-diagnostics `resultId` is this counter. One reparse and one
// stamp per notification: a bump per range would make every keystroke
// look like several to a pulling client, and none would make a
// changed buffer answer "unchanged".
let tree = Tree::new("incrementalgeneration");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
let before = session.server.generation;
change(
&mut session,
&uri,
2,
serde_json::json!([
{ "range": { "start": { "line": 0, "character": 9 },
"end": { "line": 0, "character": 9 } }, "text": "\n wire a;" },
{ "range": { "start": { "line": 1, "character": 9 },
"end": { "line": 1, "character": 9 } }, "text": "\n wire b;" },
{ "range": { "start": { "line": 2, "character": 7 },
"end": { "line": 2, "character": 8 } }, "text": "c" },
]),
);
assert_eq!(session.server.generation, before + 1, "one stamp per notification");
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire c;\nendmodule\n");
// An empty batch is not a change: nothing to reparse, nothing to stamp.
let stamp = session.server.generation;
change(&mut session, &uri, 3, serde_json::json!([]));
assert_eq!(session.server.generation, stamp, "an empty batch moves nothing");
}
#[test]
fn a_full_sync_clients_batch_still_lets_the_last_change_win() {
// A client that ignores the new capability and keeps sending whole
// buffers must behave exactly as it did before this feature.
let tree = Tree::new("incrementalfullsync");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
change(
&mut session,
&uri,
2,
serde_json::json!([
{ "text": "module a;\nendmodule\n" },
{ "text": "module b;\nendmodule\n" },
{ "text": "module c;\nendmodule\n" },
]),
);
assert_eq!(buffer(&session, &uri), "module c;\nendmodule\n");
}
#[test]
fn a_change_naming_a_buffer_that_was_never_opened_is_taken_as_written() {
// Out of protocol, but a full-text change used to be adopted whatever
// the state was, and still is: there is no base text to be wrong
// about. A *ranged* change against nothing lands its text at the
// start, which is the clamping rule, not a special case.
let tree = Tree::new("incrementalunopened");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
change(&mut session, &uri, 1, serde_json::json!([{ "text": "module m;\nendmodule\n" }]));
assert_eq!(buffer(&session, &uri), "module m;\nendmodule\n");
}
#[test]
fn a_ranged_change_over_multi_byte_text_edits_the_right_columns() {
// The whole reason positions are converted rather than counted: the
// comment above the edited line is four characters and nine bytes.
let tree = Tree::new("incrementalunicode");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri =
session.open(&tree.path.join("m.sv"), "// é ✓ 🎉\nmodule m;\n wire a;\nendmodule\n");
change(
&mut session,
&uri,
2,
serde_json::json!([{
"range": { "start": { "line": 2, "character": 7 },
"end": { "line": 2, "character": 8 } },
"text": "renamed",
}]),
);
assert_eq!(buffer(&session, &uri), "// é ✓ 🎉\nmodule m;\n wire renamed;\nendmodule\n");
}
#[test]
fn a_ranged_change_republishes_diagnostics_for_what_it_produced() {
let tree = Tree::new("incrementalpublish");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
let _ = session.published();
// Delete the `a`, leaving `wire ;` — a parse error.
change(
&mut session,
&uri,
2,
serde_json::json!([{
"range": { "start": { "line": 1, "character": 7 },
"end": { "line": 1, "character": 8 } },
"text": "",
}]),
);
let published = session.published();
assert_eq!(published.len(), 1, "one publish per notification: {published:#?}");
assert!(!published[0].diagnostics.is_empty(), "the broken buffer is reported");
// Put it back: the diagnostics clear.
change(
&mut session,
&uri,
3,
serde_json::json!([{
"range": { "start": { "line": 1, "character": 7 },
"end": { "line": 1, "character": 7 } },
"text": "a",
}]),
);
let published = session.published();
assert_eq!(published.len(), 1);
assert!(published[0].diagnostics.is_empty(), "{published:#?}");
}
// ------------------------------------------------------------------
// `textDocument/onTypeFormatting`
// ------------------------------------------------------------------
/// One `onTypeFormatting` for a buffer: the character typed, and the
/// position the client reports for the cursor after it.
fn on_type(session: &mut Session, uri: &Uri, typed: &str, line: u32, character: u32) -> Value {
on_type_with(session, uri, typed, line, character, serde_json::json!({}))
}
fn on_type_with(
session: &mut Session,
uri: &Uri,
typed: &str,
line: u32,
character: u32,
options: Value,
) -> Value {
let mut all = serde_json::json!({ "tabSize": 2, "insertSpaces": true });
if let (Some(all), Some(extra)) = (all.as_object_mut(), options.as_object()) {
for (key, value) in extra {
all.insert(key.clone(), value.clone());
}
}
session.result(
OnTypeFormatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"ch": typed,
"options": all,
}),
)
}
#[test]
fn a_typed_newline_re_indents_the_line_it_opened() {
// The dispatch arm, end to end: a real request, decoded by the real
// decoder, answered by the real handler.
let tree = Tree::new("ontypenewline");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session
.open(&tree.path.join("m.sv"), "module m;\n always_comb begin\n\n end\nendmodule\n");
let edits = on_type(&mut session, &uri, "\n", 2, 0);
assert_eq!(edits[0]["newText"], " ", "{edits:#?}");
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 2, "character": 0 }));
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 2, "character": 0 }));
assert!(session.shown().is_empty(), "a keystroke says nothing to the user");
}
#[test]
fn a_typed_semicolon_lays_out_the_statement_through_the_range_engine() {
let tree = Tree::new("ontypesemi");
let mut session = Session::new(vec![tree.path.clone()], false);
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
let uri = session.open(&tree.path.join("m.sv"), text);
let typed = on_type(&mut session, &uri, ";", 1, 11);
assert_eq!(typed[0]["newText"], "module m;\n wire a;\n wire b;\nendmodule\n");
// The same answer `textDocument/rangeFormatting` gives for that line,
// byte for byte: this path is that request with a different trigger.
let ranged = session.result(
RangeFormatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": { "start": { "line": 1, "character": 0 },
"end": { "line": 1, "character": 0 } },
"options": { "tabSize": 2, "insertSpaces": true },
}),
);
assert_eq!(typed, ranged);
assert!(session.shown().is_empty());
}
#[test]
fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
// The deliberate contrast with `textDocument/formatting` and the save
// hook, both of which show an ERROR on a refusal. Mid-edit code the
// engine declines is the *normal* case on a keystroke, and a modal the
// user cannot type past would arrive on every semicolon.
let tree = Tree::new("ontypequiet");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
// ...and the whole-document request on the same buffer still does say
// something, so the silence is this path's decision and not a
// regression in `edits()`.
let _ = formatting_result(&mut session, &uri);
assert_eq!(session.shown().len(), 1, "the explicit request still reports");
}
#[test]
fn a_broken_config_is_never_reported_from_a_keystroke() {
// `warn_about_config`'s dedup is cleared by `set_document`, and an
// on-type request follows the `didChange` the user's own keystroke
// produced — so warning here would mean one popup per character. The
// user is told on their next explicit format instead.
let tree = Tree::new("ontypeconfig");
std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git");
std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
let _ = session.drain();
for _ in 0..3 {
let edits = on_type(&mut session, &uri, "\n", 1, 0);
assert_eq!(edits[0]["newText"], " ", "it still formats with the defaults");
assert!(session.shown().is_empty(), "and still says nothing");
}
// The explicit request is where the user hears about it.
let _ = formatting_result(&mut session, &uri);
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:?}");
assert!(shown[0].1.contains("unknown key `bogus`"), "{shown:?}");
}
#[test]
fn a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does() {
// Unlike `willSaveWaitUntil`, this request carries `FormattingOptions`,
// so the editor's own tab size is a rung — outranked by a pushed
// `lucisv.indent`, exactly as `format::settings_for` documents.
let tree = Tree::new("ontypesettings");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
let tabbed = serde_json::json!({ "tabSize": 4 });
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed.clone());
assert_eq!(edits[0]["newText"], " ", "rung 3, the editor's tab size");
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
);
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed);
assert_eq!(edits[0]["newText"], " ", "rung 2 outranks it");
// Hard tabs are not a width this formatter can honour, so rung 3 drops
// out entirely and the built-in default answers.
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": {} } }),
);
let hard = serde_json::json!({ "tabSize": 4, "insertSpaces": false });
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, hard);
assert_eq!(edits[0]["newText"], " ", "never a tab, and never a guess");
}
#[test]
fn a_keystroke_in_a_buffer_the_server_does_not_hold_answers_an_empty_array() {
// `[]` rather than `null`: the protocol's answer for "no edits", and
// what every other request on this path already returns.
let tree = Tree::new("ontypeunopened");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
assert_eq!(on_type(&mut session, &uri, "\n", 1, 0), serde_json::json!([]));
assert_eq!(on_type(&mut session, &uri, ";", 1, 0), serde_json::json!([]));
assert!(session.shown().is_empty());
}
#[test]
fn a_trigger_character_this_server_never_advertised_answers_nothing() {
let tree = Tree::new("ontypeunknown");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
for typed in ["}", ")", "e"] {
assert_eq!(on_type(&mut session, &uri, typed, 1, 11), serde_json::json!([]), "{typed}");
}
assert!(session.shown().is_empty());
}
// ------------------------------------------------------------------
// `textDocument/willSaveWaitUntil`
// ------------------------------------------------------------------
/// The `lucisv.formatOnSave` push a client makes, on or off.
fn format_on_save(on: bool) -> Value {
serde_json::json!({ "settings": { "lucisv": { "formatOnSave": on } } })
}
/// One `willSaveWaitUntil` for a buffer, for the reason given (1 = manual,
/// 2 = after delay, 3 = focus out).
fn will_save(session: &mut Session, uri: &Uri, reason: u8) -> Value {
session.result(
WillSaveWaitUntil::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "reason": reason }),
)
}
/// What `textDocument/formatting` answers for the same buffer, asking for
/// the 2-space tab an editor defaults to — which is also the built-in
/// indent, so the two paths resolve to the same settings.
fn formatting_result(session: &mut Session, uri: &Uri) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
)
}
#[test]
fn the_save_hook_declines_until_format_on_save_is_pushed() {
let tree = Tree::new("willsaveoff");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
// The default: a client that never pushed the setting is answered
// `null`, and told nothing at all.
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "off by default");
assert!(session.shown().is_empty(), "a decline is silent");
// Pushed on, mid-session, with no restart.
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits[0]["newText"], "module m;\n wire a;\nendmodule\n", "{edits:#?}");
// And off again: the hook goes back to declining.
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "turned back off");
}
#[test]
fn toggling_format_on_save_neither_rescans_nor_bumps_the_generation() {
// QA (2026-08-26): `lucisv.formatOnSave` is read afresh by every save,
// like `indent`/`lineLength` already are by every format — it must not
// cost a re-walk of the workspace, and (since a rescan is what bumps
// it) must not move the generation counter a pull-diagnostics client's
// `resultId` is stamped with either. `only_an_exclude_change_asks_for_a_rescan`
// (state.rs) pins the same thing one layer down; this pins it through
// the real notification handler.
let tree = Tree::new("willsavenoreindex");
tree.package("kept.sv", "kept_pkg");
let mut session = Session::new(vec![tree.path.clone()], false);
let before = session.server.generation;
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
assert_eq!(session.server.generation, before, "turning it on moved nothing");
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
assert_eq!(session.server.generation, before, "turning it off moved nothing either");
}
#[test]
fn the_save_hook_answers_exactly_what_the_formatting_request_answers() {
// The whole contract: this is `textDocument/formatting` with a
// different trigger, so the bytes must be identical — not merely
// equivalent.
let tree = Tree::new("willsavesame");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri =
session.open(&tree.path.join("m.sv"), "module m;\nwire a;\n wire b;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
assert_eq!(will_save(&mut session, &uri, 1), formatting_result(&mut session, &uri));
}
#[test]
fn every_save_reason_is_a_save() {
// Manual, after-delay and focus-out all format: the user asked for
// their saves to be formatted, and all three write the file.
let tree = Tree::new("willsavereason");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
for reason in [1, 2, 3] {
let edits = will_save(&mut session, &uri, reason);
assert_eq!(
edits[0]["newText"], "module m;\n wire a;\nendmodule\n",
"reason {reason}: {edits:#?}"
);
}
}
#[test]
fn the_save_hook_answers_null_for_a_buffer_it_does_not_hold() {
// The request carries no text — the client has not written yet — so a
// buffer the server never saw is one it cannot format.
let tree = Tree::new("willsaveclosed");
let mut session = Session::new(vec![tree.path.clone()], false);
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
assert_eq!(will_save(&mut session, &uri, 1), Value::Null);
assert!(session.shown().is_empty(), "and nothing is said about it");
}
#[test]
fn an_already_formatted_buffer_is_saved_with_no_edits() {
// The same `[]` the formatting request gives for `Ok(None)`: an edit
// that changes nothing still moves the cursor in some editors.
let tree = Tree::new("willsaveclean");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits, serde_json::json!([]), "{edits:#?}");
assert_eq!(edits, formatting_result(&mut session, &uri), "the same as the request's");
}
#[test]
fn a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown() {
// CLAUDE.md invariant #1 on the save path: no partial output, ever.
// The message repeats per save on purpose — a save the user asked to
// be formatted, that was not, is worth saying every time it happens.
let tree = Tree::new("willsavebroken");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
for save in 1..=2 {
let edits = will_save(&mut session, &uri, 1);
assert_eq!(edits, serde_json::json!([]), "save {save}: no edit at all");
let shown = session.shown();
assert_eq!(shown.len(), 1, "save {save}: {shown:#?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.starts_with("lucisv: cannot format — "), "{}", shown[0].1);
}
}
#[test]
fn applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do() {
// The formatter's own idempotency, asserted through this path: the
// buffer the client writes is a fixed point, so a save right after a
// save cannot keep rewriting the file.
let tree = Tree::new("willsaveidempotent");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(
&tree.path.join("m.sv"),
"module m;\nwire a;\n assign a = 1;\nendmodule\n",
);
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let edits = will_save(&mut session, &uri, 1);
let formatted = edits[0]["newText"].as_str().expect("newText").to_string();
// The client applies the edit and writes; the buffer it holds is what
// the next save asks about.
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
assert_eq!(buffer(&session, &uri), formatted);
assert_eq!(will_save(&mut session, &uri, 1), serde_json::json!([]), "a fixed point");
}
/// What `textDocument/formatting` answers for the given `tabSize`.
fn formatting_with_tab_size(session: &mut Session, uri: &Uri, tab_size: u32) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": tab_size, "insertSpaces": true },
}),
)
}
#[test]
fn the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent() {
// QA (2026-08-26): the documented gap in Assumptions/Handshakes,
// constructed for real. No `lucisv.toml`, no `lucisv.indent` pushed,
// and an editor whose tab size is 4: a manual format honors rung 3
// (the editor's `tabSize`) and indents 4; the save hook has no rung 3
// to consult at all and falls straight to the built-in default, 2.
let tree = Tree::new("willsavetabgap");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let manual = formatting_with_tab_size(&mut session, &uri, 4);
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
let saved = will_save(&mut session, &uri, 1);
assert_eq!(saved[0]["newText"], "module m;\n wire a;\nendmodule\n", "{saved:#?}");
assert_ne!(manual, saved, "the documented gap is real, not just written down");
}
#[test]
fn a_lucisv_toml_erases_the_tab_size_gap() {
// QA (2026-08-26): with a checked-in config, rung 1 outranks both the
// editor's `tabSize` and the built-in default, so the two paths agree
// exactly again — no `lucisv.toml`, and this would be the previous
// test.
let tree = Tree::new("willsavetabgapclosed");
tree.write("lucisv.toml", "indent = 4\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
// A wildly different editor tab size changes nothing: the config wins.
let manual = formatting_with_tab_size(&mut session, &uri, 8);
let saved = will_save(&mut session, &uri, 1);
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
assert_eq!(manual, saved, "the config makes the two paths agree exactly");
}
#[test]
fn a_broken_config_still_saves_with_defaults_and_warns_once() {
// QA (2026-08-26): the interaction attack-surface 4 calls out —
// `formatOnSave` on, the buffer itself fine, but `lucisv.toml` broken.
// The save must not be sacrificed to a typo in a file the user is not
// even editing: it formats with the built-in defaults, and the
// warning follows the same per-file-change dedup a broken config
// already gets everywhere else, so a save loop cannot turn it into
// spam the way the formatter-refusal ERROR deliberately can.
//
// The buffer is already at the built-in default (2-space indent), so
// neither save produces an edit and — crucially — neither save is
// followed by the client-applies-the-edit `didChange` that would
// itself re-arm the warning (`set_document` clears
// `config_warnings`). That is what isolates the dedup this test is
// actually about from the unrelated re-arming a *changed* buffer gets.
let tree = Tree::new("willsavebrokenconfig");
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
let first = will_save(&mut session, &uri, 1);
assert_eq!(first, serde_json::json!([]), "the buffer needed no edit: {first:#?}");
let shown = session.shown();
assert_eq!(shown.len(), 1, "{shown:#?}");
assert_eq!(shown[0].0, MessageType::WARNING);
assert!(shown[0].1.contains("formatting with default settings"), "{}", shown[0].1);
// A second save of the same still-broken config, with nothing having
// changed the buffer in between, says nothing new.
let second = will_save(&mut session, &uri, 1);
assert_eq!(second, serde_json::json!([]), "{second:#?}");
assert!(session.shown().is_empty(), "the warning does not repeat per save");
}
#[test]
fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save() {
// QA (2026-08-26) finding, not a fix: `warn_about_config`'s dedup is
// keyed on `set_document`, and `set_document` is exactly what runs
// when the client applies a save hook's edit and the resulting
// `didChange` reaches the server (see
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`,
// which does this on purpose to model the real sequence). So "warns
// once" (Assumptions, work log) only holds once the buffer stops
// needing edits — a save that *itself* reformats the buffer re-arms
// the same warning for the very next save, because that save is
// preceded by a `didChange` the dedup treats as a fresh state. Two
// back-to-back saves of a buffer that needs reformatting under a
// broken config warn twice, not once; the third (once the buffer is a
// fixed point and no further `didChange` lands) is finally silent.
// This is consistent with the doc comment on `warn_about_config`
// ("once per change of a file") — it is the *save hook's own* prose
// ("warns once") that does not spell out this edge, and a future
// reader relying on literally one warning per broken config should
// know better.
let tree = Tree::new("willsavebrokenconfigrearm");
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
let _ = session.drain();
let first = will_save(&mut session, &uri, 1);
let formatted = first[0]["newText"].as_str().expect("newText").to_string();
assert_eq!(formatted, "module m;\n wire a;\nendmodule\n", "{first:#?}");
assert_eq!(session.shown().len(), 1, "the first save warns");
// The client applies the edit and writes, exactly as
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`
// does — this is what re-arms the dedup.
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
let second = will_save(&mut session, &uri, 1);
assert_eq!(second, serde_json::json!([]), "already formatted: {second:#?}");
assert_eq!(session.shown().len(), 1, "the second save warns again, not zero times");
// No further `didChange` follows a no-op save, so the third finally
// stays quiet — the dedup this test is not disputing.
let third = will_save(&mut session, &uri, 1);
assert_eq!(third, serde_json::json!([]));
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
}
// ------------------------------------------------------------------
// semantic tokens: full, range, full/delta
// ------------------------------------------------------------------
fn full_tokens(session: &mut Session, uri: &Uri) -> Value {
session.result(
SemanticTokensFullRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
)
}
fn delta_tokens(session: &mut Session, uri: &Uri, previous: &str) -> Value {
session.result(
SemanticTokensFullDeltaRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"previousResultId": previous,
}),
)
}
fn range_tokens(session: &mut Session, uri: &Uri, from: (u32, u32), to: (u32, u32)) -> Value {
session.result(
SemanticTokensRangeRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": from.0, "character": from.1 },
"end": { "line": to.0, "character": to.1 },
},
}),
)
}
/// A `data` array as the client reads it: flat numbers.
fn numbers(value: &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()
}
/// The client's side of a delta: splice each edit into the data it holds.
fn applied(previous: &[u64], answer: &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(numbers).unwrap_or_default();
data.splice(start..end, inserted);
}
data
}
const TOKEN_SOURCE: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
#[test]
fn a_full_token_answer_is_stamped_so_a_delta_can_name_it() {
let tree = Tree::new("tokensfull");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let full = full_tokens(&mut session, &uri);
assert!(full["resultId"].is_string(), "{full:#?}");
assert!(!numbers(&full["data"]).is_empty(), "the buffer really has tokens");
assert_eq!(
session.server.tokens[&uri].result_id,
full["resultId"].as_str().expect("resultId"),
"the answer is remembered under the id it was stamped with"
);
}
#[test]
fn a_delta_after_a_change_reconstructs_the_new_token_set_exactly() {
// The whole invariant, end to end through the dispatch: what the
// client is left holding after applying the edits must be what a
// fresh full answer would have given it.
let tree = Tree::new("tokensdelta");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let held = numbers(&first["data"]);
let previous = first["resultId"].as_str().expect("resultId").to_string();
change(
&mut session,
&uri,
2,
serde_json::json!([{ "text": "module m;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n" }]),
);
let answer = delta_tokens(&mut session, &uri, &previous);
assert!(answer.get("edits").is_some(), "a known id gets edits: {answer:#?}");
let reconstructed = applied(&held, &answer);
let now = full_tokens(&mut session, &uri);
assert_eq!(reconstructed, numbers(&now["data"]), "the edits must reconstruct the truth");
}
#[test]
fn a_delta_over_an_unchanged_buffer_is_an_empty_edit_list() {
let tree = Tree::new("tokensnochange");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let previous = first["resultId"].as_str().expect("resultId").to_string();
let answer = delta_tokens(&mut session, &uri, &previous);
assert_eq!(answer["edits"], serde_json::json!([]), "{answer:#?}");
assert_ne!(answer["resultId"], first["resultId"], "and it is a new answer to name");
}
#[test]
fn a_delta_naming_an_id_we_do_not_hold_is_answered_in_full() {
let tree = Tree::new("tokensstale");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
// Never asked for a full answer: there is nothing to diff against.
let cold = delta_tokens(&mut session, &uri, "1");
assert!(cold.get("edits").is_none(), "no state, no edits: {cold:#?}");
assert!(!numbers(&cold["data"]).is_empty(), "{cold:#?}");
// And an id that has since been superseded — the client fell behind,
// or another id's answer overwrote this one.
let _ = full_tokens(&mut session, &uri);
let stale = delta_tokens(&mut session, &uri, "not-an-id-we-ever-sent");
assert!(stale.get("edits").is_none(), "a stale id, a full answer: {stale:#?}");
assert!(stale["resultId"].is_string(), "which is itself nameable: {stale:#?}");
}
#[test]
fn closing_a_buffer_drops_the_answer_a_delta_would_be_computed_against() {
// Memory: nothing may grow with the number of files ever opened. The
// observable half is that a delta naming the old id gets a full set.
let tree = Tree::new("tokensclose");
let mut session = Session::new(vec![tree.path.clone()], false);
let path = tree.path.join("m.sv");
let uri = session.open(&path, TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let previous = first["resultId"].as_str().expect("resultId").to_string();
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert!(!session.server.tokens.contains_key(&uri), "the state went with the buffer");
session.open(&path, TOKEN_SOURCE);
let answer = delta_tokens(&mut session, &uri, &previous);
assert!(answer.get("edits").is_none(), "the old id names nothing now: {answer:#?}");
}
#[test]
fn a_range_answer_covers_the_lines_it_names_and_nothing_else() {
let tree = Tree::new("tokensrange");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let whole = numbers(&full_tokens(&mut session, &uri)["data"]);
let everything = range_tokens(&mut session, &uri, (0, 0), (99, 0));
assert_eq!(numbers(&everything["data"]), whole, "a range over everything is the full set");
let one_line = range_tokens(&mut session, &uri, (1, 0), (2, 0));
let data = numbers(&one_line["data"]);
assert!(!data.is_empty() && data.len() < whole.len(), "{one_line:#?}");
assert_eq!(data[0], 1, "the first token's deltaLine is absolute from the file start");
let nothing = range_tokens(&mut session, &uri, (2, 0), (2, 0));
assert_eq!(numbers(&nothing["data"]), Vec::<u64>::new(), "an empty range: {nothing:#?}");
}
#[test]
fn a_range_request_is_not_the_answer_a_later_delta_is_computed_against() {
// A range answer is a partial view, so remembering it would make the
// next delta a diff against something the client never held whole.
let tree = Tree::new("tokensrangestate");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let previous = first["resultId"].as_str().expect("resultId").to_string();
let ranged = range_tokens(&mut session, &uri, (1, 0), (2, 0));
assert!(ranged.get("resultId").is_none(), "nothing to name: {ranged:#?}");
let answer = delta_tokens(&mut session, &uri, &previous);
assert_eq!(answer["edits"], serde_json::json!([]), "the full answer still stands");
}
#[test]
fn every_token_request_for_a_buffer_that_is_not_open_answers_null() {
let tree = Tree::new("tokensunopened");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = crate::uri::path_to_uri(&tree.path.join("never.sv")).expect("uri");
assert!(full_tokens(&mut session, &uri).is_null());
assert!(delta_tokens(&mut session, &uri, "1").is_null());
assert!(range_tokens(&mut session, &uri, (0, 0), (9, 0)).is_null());
assert!(session.server.tokens.is_empty(), "and nothing was remembered about it");
}
#[test]
fn no_token_request_bumps_the_diagnostics_generation() {
// Every token request is read-only. Bumping the generation would
// invalidate a pulling client's whole diagnostic cache each time the
// editor repainted a viewport.
let tree = Tree::new("tokensgeneration");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let before = session.server.generation;
let first = full_tokens(&mut session, &uri);
let previous = first["resultId"].as_str().expect("resultId").to_string();
let _ = delta_tokens(&mut session, &uri, &previous);
let _ = range_tokens(&mut session, &uri, (0, 0), (9, 0));
assert_eq!(session.server.generation, before, "nothing about diagnostics moved");
// Said the way the client would see it: a pull stamped before the
// token requests is still `unchanged` after them.
let pull = document_pull(&mut session, &uri, None);
let stamp = pull["resultId"].as_str().expect("resultId").to_string();
let _ = full_tokens(&mut session, &uri);
let again = document_pull(&mut session, &uri, Some(&stamp));
assert_eq!(again["kind"], "unchanged", "{again:#?}");
}
// ------------------------------------------------------------------
// QA (2026-08-26): state-lifecycle attack surfaces
// ------------------------------------------------------------------
#[test]
fn qa_two_open_buffers_ids_do_not_cross_contaminate() {
// Buffer A's resultId presented against buffer B must not be
// mistaken for one of B's own — they share one counter, so the
// strings can coincide only by the map being keyed on the wrong
// thing.
let tree = Tree::new("tokenstwobuffers");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri_a = session.open(&tree.path.join("a.sv"), TOKEN_SOURCE);
let uri_b = session.open(&tree.path.join("b.sv"), "module other;\n wire z;\nendmodule\n");
let full_a = full_tokens(&mut session, &uri_a);
let full_b = full_tokens(&mut session, &uri_b);
let id_a = full_a["resultId"].as_str().expect("resultId").to_string();
let id_b = full_b["resultId"].as_str().expect("resultId").to_string();
assert_ne!(id_a, id_b, "two answers, two distinct ids");
// A's id, asked of B: B has no memory of ever answering that id, so
// this must be a full answer, not edits computed against A's data.
let cross = delta_tokens(&mut session, &uri_b, &id_a);
assert!(cross.get("edits").is_none(), "A's id names nothing for B: {cross:#?}");
// That full answer itself mints a fresh id and becomes B's new
// remembered answer (every answer does, full or delta) — so it is
// *that* id, not `id_b`, that now names B's data.
let cross_id = cross["resultId"].as_str().expect("resultId").to_string();
assert_ne!(cross_id, id_b, "a fresh id was minted for the cross-request's own answer");
let _ = id_b; // superseded by `cross_id`; kept above only to assert distinctness of the two original ids
let same = delta_tokens(&mut session, &uri_b, &cross_id);
assert_eq!(same["edits"], serde_json::json!([]), "B's latest id still names B's data");
// And closing A must not disturb B's remembered answer.
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri_a } }),
);
assert!(!session.server.tokens.contains_key(&uri_a));
assert!(session.server.tokens.contains_key(&uri_b), "B's state is untouched by A's close");
}
#[test]
fn qa_full_delta_full_delta_stays_consistent_across_edits() {
// Mixing the two requests repeatedly, the way a real client would:
// each new answer must be nameable by the next delta, regardless of
// whether the previous answer was a `full` or a `full/delta`.
let tree = Tree::new("tokensmixedcycle");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
let mut held = numbers(&first["data"]);
let edits_after = [
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
];
for (i, text) in edits_after.iter().enumerate() {
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
let answer = delta_tokens(&mut session, &uri, &previous);
assert!(answer.get("edits").is_some(), "step {i}: known id gets edits: {answer:#?}");
held = applied(&held, &answer);
let truth = full_tokens(&mut session, &uri);
assert_eq!(held, numbers(&truth["data"]), "step {i}: delta chain matches the truth");
// The `full` answer just taken is itself a fresh, valid base for
// the next delta in the cycle.
previous = truth["resultId"].as_str().expect("resultId").to_string();
held = numbers(&truth["data"]);
}
}
/// A flat `data` array computed straight off the document, bypassing the
/// request dispatch entirely — so checking against it does not depend on
/// the very `tokens`/`token_results` bookkeeping under test.
fn ground_truth(session: &Session, uri: &Uri) -> Vec<u64> {
let doc = session.server.workspace.document(uri).expect("open");
tokens::semantic_tokens(doc)
.iter()
.flat_map(|t| {
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
})
.map(u64::from)
.collect()
}
#[test]
fn qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between() {
// A client need not re-request `full` just because it received a
// `full/delta` answer: that answer's own `resultId` must itself be a
// valid base for the *next* delta. Every `full_tokens` call in the
// test above also re-remembers the answer, which would silently
// paper over a bug where only a *full* answer's id chains correctly
// — so this test never calls `full` again after the first one.
let tree = Tree::new("tokensdeltachain");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
let first = full_tokens(&mut session, &uri);
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
let mut held = numbers(&first["data"]);
let edits_after = [
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
];
for (i, text) in edits_after.iter().enumerate() {
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
let answer = delta_tokens(&mut session, &uri, &previous);
assert!(
answer.get("edits").is_some(),
"step {i}: the chained id is still known: {answer:#?}"
);
held = applied(&held, &answer);
previous = answer["resultId"].as_str().expect("resultId").to_string();
assert_eq!(held, ground_truth(&session, &uri), "step {i}: the chain matches the truth");
}
}
// ------------------------------------------------------------------
// $/cancelRequest — docs/features/cancel-request/README.md
// ------------------------------------------------------------------
/// A `textDocument/documentSymbol` request, queued. Any request would do;
/// this one is cheap and its answer names what the buffer holds, which is
/// what the ordering test needs.
fn ask(id: i32, uri: &Uri) -> Message {
Message::Request(Request::new(
RequestId::from(id),
DocumentSymbolRequest::METHOD.to_string(),
serde_json::json!({ "textDocument": { "uri": uri } }),
))
}
/// A `$/cancelRequest` naming `id`, exactly as a client sends it — the id
/// is passed as raw JSON so both protocol forms can be tested.
fn cancel(id: Value) -> Message {
Message::Notification(Notification::new(
Cancel::METHOD.to_string(),
serde_json::json!({ "id": id }),
))
}
/// A whole-buffer `didChange`, queued.
fn changed(uri: &Uri, version: u32, text: &str) -> Message {
Message::Notification(Notification::new(
DidChangeTextDocument::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": [{ "text": text }],
}),
))
}
/// The protocol's `RequestCancelled`.
const CANCELLED: i32 = -32800;
/// Every response since the last drain, as (id, error code or `None`).
fn outcomes(session: &Session) -> Vec<(RequestId, Option<i32>)> {
session
.answers()
.into_iter()
.map(|response| {
let code = response.response_result.err().map(|error| error.code);
(response.id, code)
})
.collect()
}
/// The top-level symbol names in a `documentSymbol` answer.
fn symbol_names(result: &Value) -> Vec<String> {
result
.as_array()
.expect("an array of symbols")
.iter()
.map(|symbol| symbol["name"].as_str().expect("a name").to_string())
.collect()
}
/// A session with one open buffer, drained of the startup traffic.
fn cancelling_session(name: &str, text: &str) -> (Tree, Session, Uri) {
let tree = Tree::new(name);
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), text);
let _ = session.drain();
(tree, session, uri)
}
const ONE_MODULE: &str = "module m;\nendmodule\n";
#[test]
fn a_request_cancelled_in_the_same_burst_is_answered_cancelled() {
// The point of the whole feature: the client asked and changed its
// mind while the server was busy elsewhere, so the answer costs
// nothing to produce.
let (_tree, mut session, uri) = cancelling_session("cancelsame", ONE_MODULE);
let shutdown = session.batch(vec![ask(1, &uri), cancel(serde_json::json!(1))]);
assert!(!shutdown, "a cancel is not a shutdown");
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
}
#[test]
fn a_cancel_dequeued_before_its_request_still_cancels_it() {
// The batch is scanned as a whole before any of it runs, so a cancel
// the transport happened to deliver first is not a cancel that
// arrived too early.
let (_tree, mut session, uri) = cancelling_session("cancelfirst", ONE_MODULE);
session.batch(vec![cancel(serde_json::json!(1)), ask(1, &uri)]);
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
}
#[test]
fn a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone() {
let (_tree, mut session, uri) = cancelling_session("cancelone", ONE_MODULE);
session.batch(vec![ask(1, &uri), ask(2, &uri), cancel(serde_json::json!(1))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
"id 2 was answered normally, and in its own place in the queue"
);
}
#[test]
fn a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot() {
// A cancel that arrives in a later burst than its request is too late
// — that request was answered already — and remembering it would be a
// set that grows for the life of the session. The identical id in the
// burst after proves nothing was kept: real clients never reuse an
// id, so only a leak could cancel this one.
let (_tree, mut session, uri) = cancelling_session("cancellate", ONE_MODULE);
let shutdown = session.batch(vec![cancel(serde_json::json!(1))]);
assert!(!shutdown);
assert_eq!(outcomes(&session), vec![], "a lone cancel is answered with nothing at all");
session.batch(vec![ask(1, &uri)]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), None)],
"the dropped cancel did not survive into the next burst"
);
}
#[test]
fn a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered() {
// The invariant the burst must not break: order. A `didChange` the
// client sent before its request has to be in effect when that
// request is answered, exactly as it would be one message at a time.
let (_tree, mut session, uri) = cancelling_session("cancelorder", ONE_MODULE);
session.batch(vec![changed(&uri, 2, "module renamed;\nendmodule\n"), ask(1, &uri)]);
let answers = session.answers();
assert_eq!(answers.len(), 1);
let result = answers[0].response_result.clone().expect("an answer");
assert_eq!(symbol_names(&result), vec!["renamed".to_string()]);
}
#[test]
fn a_cancel_never_cancels_a_notification() {
// Notifications carry no id and get no response, so nothing in a
// burst can suppress one — whatever id the cancel names.
let (_tree, mut session, uri) = cancelling_session("cancelnotify", ONE_MODULE);
session.batch(vec![
changed(&uri, 2, "module renamed;\nendmodule\n"),
cancel(serde_json::json!(1)),
cancel(serde_json::json!("textDocument/didChange")),
]);
assert_eq!(buffer(&session, &uri), "module renamed;\nendmodule\n");
assert_eq!(outcomes(&session), vec![], "no ids were cancelled, so no responses");
}
#[test]
fn a_shutdown_is_honoured_however_it_is_cancelled() {
// The spec lets a server answer a cancelled request normally, and for
// `shutdown` that is the only safe reading: a client that cannot shut
// the server down leaks a process. `handle_shutdown` runs before the
// cancelled set is consulted, so the cancel never gets a say.
let (_tree, mut session, _uri) = cancelling_session("cancelshutdown", ONE_MODULE);
// `handle_shutdown` waits for the `exit` that follows; queue it the
// way a real client's would already be queued.
session
.client
.sender
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
.expect("queue exit");
let request = Message::Request(Request::new(
RequestId::from(9),
Shutdown::METHOD.to_string(),
Value::Null,
));
let shutdown = session.batch(vec![request, cancel(serde_json::json!(9))]);
assert!(shutdown, "the loop exits");
assert_eq!(
outcomes(&session),
vec![(RequestId::from(9), None)],
"shutdown was answered, and answered successfully"
);
}
#[test]
fn cancelling_one_request_twice_answers_it_once() {
let (_tree, mut session, uri) = cancelling_session("canceltwice", ONE_MODULE);
session.batch(vec![
ask(1, &uri),
cancel(serde_json::json!(1)),
cancel(serde_json::json!(1)),
ask(2, &uri),
]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
"the second cancel changed nothing — id 2 is not collateral damage"
);
}
#[test]
fn a_cancel_id_may_be_a_number_or_a_string() {
// The protocol allows both, and a client that numbers its requests
// with strings is not exotic.
let (_tree, mut session, uri) = cancelling_session("cancelstring", ONE_MODULE);
let request = Message::Request(Request::new(
RequestId::from("abc".to_string()),
DocumentSymbolRequest::METHOD.to_string(),
serde_json::json!({ "textDocument": { "uri": &uri } }),
));
session.batch(vec![request, cancel(serde_json::json!("abc"))]);
assert_eq!(outcomes(&session), vec![(RequestId::from("abc".to_string()), Some(CANCELLED))]);
session.batch(vec![ask(7, &uri), cancel(serde_json::json!(7))]);
assert_eq!(outcomes(&session), vec![(RequestId::from(7), Some(CANCELLED))]);
// A string that spells a number is not the number: `RequestId` keeps
// the two apart, and so must the cancel.
session.batch(vec![ask(8, &uri), cancel(serde_json::json!("8"))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(8), None)],
"the string \"8\" does not cancel the number 8"
);
}
#[test]
fn a_malformed_cancel_is_dropped_rather_than_guessed_at() {
let (_tree, mut session, uri) = cancelling_session("cancelmalformed", ONE_MODULE);
let broken = Message::Notification(Notification::new(
Cancel::METHOD.to_string(),
serde_json::json!({ "id": { "nested": true } }),
));
session.batch(vec![ask(1, &uri), broken]);
assert_eq!(outcomes(&session), vec![(RequestId::from(1), None)]);
}
#[test]
fn is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name() {
// The forwarder stops forwarding the moment it sees this return
// `true`. A malformed or adversarial client sending a *notification*
// named "shutdown" must not trip it — that would silently stall the
// whole backlog, with `handle_shutdown` never having run to explain
// why.
let request = Message::Request(Request::new(
RequestId::from(1),
Shutdown::METHOD.to_string(),
Value::Null,
));
let notification =
Message::Notification(Notification::new(Shutdown::METHOD.to_string(), Value::Null));
let other_request = Message::Request(Request::new(
RequestId::from(2),
DocumentSymbolRequest::METHOD.to_string(),
Value::Null,
));
assert!(is_shutdown(&request));
assert!(
!is_shutdown(&notification),
"a notification named shutdown is not the shutdown request"
);
assert!(!is_shutdown(&other_request));
}
#[test]
fn burst_collects_everything_already_queued_in_arrival_order() {
// `burst` is what turns "one blocking receive" into "the whole
// backlog" — the only place FIFO order could be broken. Nothing here
// touches `Server`, so the check is on the free function alone.
let (sender, receiver) = std::sync::mpsc::channel();
sender
.send(Message::Notification(Notification::new("second".to_string(), Value::Null)))
.expect("send");
sender
.send(Message::Notification(Notification::new("third".to_string(), Value::Null)))
.expect("send");
let first = Message::Notification(Notification::new("first".to_string(), Value::Null));
let batch = burst(&receiver, first);
let methods: Vec<&str> = batch
.iter()
.map(|message| match message {
Message::Notification(notification) => notification.method.as_str(),
_ => "?",
})
.collect();
assert_eq!(
methods,
vec!["first", "second", "third"],
"the blocked-for message first, then the backlog, in order"
);
}
#[test]
fn the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown() {
// The handoff this whole feature depends on: once the forwarder has
// pushed a `shutdown` request onto the queue, it must not call `recv`
// on `connection.receiver` again — that channel is where
// `handle_shutdown` reads the `exit` that follows. An eager forwarder
// would steal it and strand the handshake for thirty seconds.
let (_tree, session, _uri) = cancelling_session("forwarderstop", ONE_MODULE);
let shutdown_id = RequestId::from(9);
session
.client
.sender
.send(Message::Request(Request::new(
shutdown_id.clone(),
Shutdown::METHOD.to_string(),
Value::Null,
)))
.expect("queue shutdown");
session
.client
.sender
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
.expect("queue exit");
let queue = session.server.queue();
let forwarded =
queue.recv_timeout(std::time::Duration::from_secs(1)).expect("shutdown is forwarded");
assert!(matches!(&forwarded, Message::Request(request) if request.id == shutdown_id));
// Give the forwarder thread every chance to (wrongly) keep reading
// before asserting that it did not.
std::thread::sleep(std::time::Duration::from_millis(50));
assert!(
queue.try_recv().is_err(),
"the forwarder must not forward anything after the shutdown request"
);
// The `exit` is still sitting on the real connection, unread — right
// where `handle_shutdown` looks for it.
let direct = session
.server
.connection
.receiver
.recv_timeout(std::time::Duration::from_secs(1))
.expect("exit is still there for handle_shutdown to read");
assert!(
matches!(&direct, Message::Notification(notification) if notification.method == "exit")
);
}
#[test]
fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
// `lucisv-0`, `lucisv-1`, … are ids the server hands out for requests
// it sends *to* the client (`applyEdit`, watcher registration,
// progress `create`) — they come back as a `Message::Response`, a
// different match arm entirely from the `Message::Request`s a burst
// scans for cancellable ids. A client cancelling one by name has
// nothing to reach.
let (_tree, mut session, uri) = cancelling_session("cancelserverid", ONE_MODULE);
let server_id = session.server.send_request("workspace/applyEdit", serde_json::json!({}));
assert_eq!(server_id, RequestId::from("lucisv-0".to_string()));
session.batch(vec![ask(1, &uri), cancel(serde_json::json!("lucisv-0"))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), None)],
"the client's own request was untouched by a cancel naming a server-initiated id"
);
// The server-initiated request can still be answered normally — the
// cancel did not intercept it.
session.answer(server_id, Value::Null);
}
}