Co-Authored-By: Claude Fable 5 <[email protected]> # Conflicts: # crates/lucisv_server/src/main.rs
8830 lines
414 KiB
Rust
8830 lines
414 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 std::path::Path;
|
|
|
|
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
|
|
use lsp_types::notification::{
|
|
Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
|
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
|
DidRenameFiles, 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, WillRenameFiles,
|
|
WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration, WorkspaceDiagnosticRequest,
|
|
WorkspaceSymbolRequest,
|
|
};
|
|
use lsp_types::{
|
|
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
|
|
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind,
|
|
CodeActionParams, CodeLensParams, CompletionParams, ConfigurationItem, ConfigurationParams,
|
|
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
|
|
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
|
|
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams,
|
|
DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams,
|
|
DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams,
|
|
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
|
|
ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams,
|
|
GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams,
|
|
LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position,
|
|
PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
|
|
ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport,
|
|
RelatedUnchangedDocumentDiagnosticReport, RenameFilesParams, RenameParams,
|
|
SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta,
|
|
SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
|
|
SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams,
|
|
ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, TypeHierarchyPrepareParams,
|
|
TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport,
|
|
UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin,
|
|
WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkDoneProgressReport,
|
|
WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult,
|
|
WorkspaceDocumentDiagnosticReport, WorkspaceEdit, WorkspaceFolder,
|
|
WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse,
|
|
WorkspaceUnchangedDocumentDiagnosticReport,
|
|
};
|
|
use serde::de::DeserializeOwned;
|
|
use serde_json::Value;
|
|
|
|
use crate::settings::ClientSettings;
|
|
use crate::state::{IndexEvent, Scan, Workspace};
|
|
use crate::{
|
|
code_action, completion, design_hierarchy, diagnostics, file_ops, folding, format, hierarchy,
|
|
hover, includes, inlay, inline, large, 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,
|
|
/// Whether the client answers `workspace/configuration` — the pull model
|
|
/// for settings. A client that said nothing is only ever *pushed*
|
|
/// settings, which is what every client got before this was read.
|
|
pub configuration: bool,
|
|
/// Whether the client understands a server-cancelled semantic-tokens
|
|
/// request (`textDocument.semanticTokens.serverCancelSupport`). Decides
|
|
/// which error code declines `semanticTokens/full` on a large buffer —
|
|
/// see `docs/features/large-file-mode/README.md`.
|
|
pub token_server_cancel: bool,
|
|
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
|
/// a notification whenever the installed workspace index changes.
|
|
pub hierarchy_view: 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 requests the server has made of the client whose answers it will
|
|
/// act on, by the id they were sent with. Everything *not* in here is a
|
|
/// request whose answer is ignorable, which is what makes `response`'s
|
|
/// fall-through correct rather than lossy.
|
|
pending: HashMap<RequestId, Pending>,
|
|
/// 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,
|
|
/// Revision of the completed index exposed to the custom hierarchy view.
|
|
hierarchy_revision: 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,
|
|
/// Buffers that are text-current but analysis-stale: the newest applied
|
|
/// text for each, in first-dirtied order. A `didChange` lands here instead
|
|
/// of running a reparse, and every one of them is flushed — analyzed,
|
|
/// republished — by the first thing that needs the analysis: the next
|
|
/// request, the next non-`didChange` notification, or the quiet-period
|
|
/// timer in `run`. See `docs/features/change-debounce/README.md`.
|
|
dirty: Vec<(Uri, String)>,
|
|
/// Everything the client has sent, forwarded off the transport's
|
|
/// rendezvous channel by [`forward`]. Held here rather than made in `run`
|
|
/// because a **scan** drains it too: the loop must not go quiet for the
|
|
/// length of one (`docs/features/scan-interleave/README.md`).
|
|
queue: std::sync::mpsc::Receiver<Message>,
|
|
/// Whether a scan is running. A message answered mid-scan can ask for
|
|
/// another one, and this is what turns that into the flag below rather
|
|
/// than a scan inside a scan.
|
|
scanning: bool,
|
|
/// A rescan asked for while a scan was running. Coalesced: any number of
|
|
/// requests is one more scan when this one ends, whatever asked for them.
|
|
rescan_wanted: bool,
|
|
/// Whether the scan now running is one a *message* asked for. The startup
|
|
/// scan is not — nothing was queued ahead of it — and that is the whole
|
|
/// difference between a request answered mid-scan and one that waits. See
|
|
/// [`Server::must_wait`].
|
|
answering_a_rescan: bool,
|
|
/// Whether the client has shut the server down. Set by a `shutdown`
|
|
/// answered mid-scan, which stops the scan where it stands and keeps `run`
|
|
/// from taking another message.
|
|
stopped: bool,
|
|
/// Messages a mid-scan drain would have answered out of order, kept in
|
|
/// arrival order until the rescan they are queued behind has run. See
|
|
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
|
/// own.
|
|
held: Vec<Message>,
|
|
/// `--verbose`: whether every operation says how long it took, in the
|
|
/// client's log channel. Off is the shipped state and the whole of what it
|
|
/// costs is the branch that reads this field — see
|
|
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
|
|
verbose: bool,
|
|
}
|
|
|
|
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
|
/// typing has stopped, before the quiet-period timer flushes them anyway. The
|
|
/// coalescing this buys — one reparse per burst instead of one per keystroke —
|
|
/// is worth nothing if diagnostics never arrive until the next request does.
|
|
const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);
|
|
|
|
/// How many files a scan must have to be worth answering messages in the
|
|
/// middle of.
|
|
///
|
|
/// **The whole trade of `docs/features/scan-interleave/README.md`, in one
|
|
/// number.** A mid-scan answer reads the index as far as the scan has built
|
|
/// it, so it can be *less* than the answer the same request would get a
|
|
/// moment later — and that is only ever worth it when "a moment later" is a
|
|
/// wait a person can feel. Below this, a scan is over in a few milliseconds
|
|
/// (the 860-file corpus is 340 ms, so sixty-four files is under thirty), and
|
|
/// trading a complete answer for those milliseconds would be a bad bargain;
|
|
/// above it, the measured wait is hundreds of milliseconds and the trade is
|
|
/// the point of the round.
|
|
///
|
|
/// A count rather than a clock deliberately: a rule about elapsed time makes
|
|
/// what a server answers depend on how loaded the machine was, which is
|
|
/// exactly the property a test suite — and a bug report — cannot work with.
|
|
/// The known limit of counting is a workspace of a *few very large* files,
|
|
/// which is under this bar and can still take a second; that is written down
|
|
/// as a deliberate not-done rather than papered over with a second rule.
|
|
const INTERLEAVE_ABOVE: usize = 64;
|
|
|
|
/// 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";
|
|
|
|
/// A request the server sent the client and still owes itself an answer to.
|
|
///
|
|
/// One map rather than one per kind: `response` then has a single lookup and
|
|
/// a single `match`, and adding a third kind is a variant the compiler makes
|
|
/// you handle rather than a map somebody forgets to consult.
|
|
enum Pending {
|
|
/// A `workspace/applyEdit`, remembering the command that asked for it so
|
|
/// a refusal can be named to the user.
|
|
ApplyEdit(String),
|
|
/// A `workspace/configuration` asking for the `lucisv` section.
|
|
Configuration,
|
|
}
|
|
|
|
/// One semantic-token answer, kept so the next delta request can be answered
|
|
/// against it.
|
|
struct TokenAnswer {
|
|
result_id: String,
|
|
data: Vec<SemanticToken>,
|
|
}
|
|
|
|
impl Server {
|
|
/// The server, with its first index built.
|
|
///
|
|
/// The startup scan runs at the **default** settings — including the
|
|
/// folder scope — because neither settings door can deliver anything
|
|
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
|
|
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
|
|
/// has always cost one.
|
|
pub fn new(
|
|
connection: Connection,
|
|
roots: Vec<std::path::PathBuf>,
|
|
abilities: ClientAbilities,
|
|
storage: Option<std::path::PathBuf>,
|
|
verbose: bool,
|
|
) -> Server {
|
|
Server::started(
|
|
connection,
|
|
roots,
|
|
abilities,
|
|
ClientSettings::default(),
|
|
storage,
|
|
verbose,
|
|
Vec::new(),
|
|
)
|
|
}
|
|
|
|
/// [`Server::new`] with a client's settings already in hand — the seam the
|
|
/// tests start a session from. Only a test has any settings this early:
|
|
/// one whose subject is not the scope says so here rather than driving a
|
|
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
|
/// buys.
|
|
///
|
|
/// `queued` is what the client had already sent when the server was built
|
|
/// — the opening burst, put straight onto the queue the startup scan
|
|
/// drains. Empty for [`Server::new`]; a test fills it because racing the
|
|
/// forwarder thread for it would make the test a coin toss rather than a
|
|
/// check.
|
|
fn started(
|
|
connection: Connection,
|
|
roots: Vec<std::path::PathBuf>,
|
|
abilities: ClientAbilities,
|
|
client: ClientSettings,
|
|
storage: Option<std::path::PathBuf>,
|
|
verbose: bool,
|
|
queued: Vec<Message>,
|
|
) -> Server {
|
|
// Started before the first scan, not in `run`: the scan below answers
|
|
// whatever the client has already sent, and it can only do that off a
|
|
// queue that is already being filled.
|
|
let (forwarded, queue) = forward(&connection);
|
|
for message in queued {
|
|
let _ = forwarded.send(message);
|
|
}
|
|
let mut server = Server {
|
|
connection,
|
|
workspace: Workspace::default(),
|
|
config_warnings: HashSet::new(),
|
|
abilities,
|
|
watchers: None,
|
|
registrations: 0,
|
|
request_ids: 0,
|
|
pending: HashMap::new(),
|
|
generation: 0,
|
|
hierarchy_revision: 0,
|
|
tokens: HashMap::new(),
|
|
token_results: 0,
|
|
indexings: 0,
|
|
dirty: Vec::new(),
|
|
queue,
|
|
scanning: false,
|
|
rescan_wanted: false,
|
|
answering_a_rescan: false,
|
|
stopped: false,
|
|
held: Vec::new(),
|
|
verbose,
|
|
};
|
|
// Nothing has been built yet, so there is no rebuild to owe: the
|
|
// `true` this returns for a non-default `client` is the rebuild that
|
|
// is about to happen anyway.
|
|
let _ = server.workspace.set_client_settings(client);
|
|
// Before the first build, because it is one rung of the ladder that
|
|
// decides where that build reads its cache from
|
|
// (`docs/features/index-persistence/README.md`).
|
|
server.workspace.set_storage_path(storage);
|
|
// 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.
|
|
//
|
|
// And it answers messages while it runs, which is what stops the first
|
|
// request of a session waiting out the whole scan
|
|
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
|
// therefore reached with the client's opening burst already handled —
|
|
// and skipped altogether if that burst shut the server down.
|
|
server.workspace.adopt_roots(roots);
|
|
let warnings = server.scan_until_settled(false);
|
|
if server.stopped {
|
|
return server;
|
|
}
|
|
server.hierarchy_index_changed();
|
|
// A buffer can now be *opened* during the startup scan, and what was
|
|
// published for it then was computed against a half-built index. This
|
|
// is the same debt a rescan pays at the end of `reindex`, owed here
|
|
// for the first time because before this round no buffer could exist
|
|
// at this point. Nothing at all is sent when nothing is open, which is
|
|
// every session whose client did not get a `didOpen` in edgeways.
|
|
if !server.workspace.open_uris().is_empty() {
|
|
server.refresh_code_lenses();
|
|
server.generation += 1;
|
|
for uri in server.workspace.open_uris() {
|
|
server.publish(&uri);
|
|
}
|
|
}
|
|
server.report_scope(warnings);
|
|
server.register_watchers();
|
|
// The pull half of the settings model. Asked here because this is the
|
|
// same moment the watchers are registered — the earliest legal one —
|
|
// and answered later, in the loop: the settings therefore arrive
|
|
// *after* the first index build, exactly as a pushed
|
|
// `didChangeConfiguration` always has (it cannot arrive before
|
|
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
|
|
// costs one extra rescan when it lands; nothing is stale in between,
|
|
// it is simply the default scope until the client answers.
|
|
server.request_configuration();
|
|
server
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
|
/// flushed here rather than left waiting for a request that may never
|
|
/// come — diagnostics are the one answer the client never asks for.
|
|
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
|
use std::sync::mpsc::RecvTimeoutError;
|
|
loop {
|
|
// A `shutdown` the startup scan answered has already been through
|
|
// `handle_shutdown`; there is nothing left to receive and nothing
|
|
// left to answer.
|
|
if self.stopped {
|
|
return Ok(());
|
|
}
|
|
// Whatever a scan set aside is answered before anything newer is
|
|
// taken — the rescan those messages were queued behind has run,
|
|
// and they are older than everything still on the queue. Handling
|
|
// them here rather than at the end of the scan is what keeps this
|
|
// a loop instead of a scan inside a scan inside a scan.
|
|
if !self.held.is_empty() {
|
|
let batch = std::mem::take(&mut self.held);
|
|
if self.process_batch(batch)? {
|
|
return Ok(());
|
|
}
|
|
continue;
|
|
}
|
|
let message = if self.dirty.is_empty() {
|
|
match self.queue.recv() {
|
|
Ok(message) => message,
|
|
Err(_) => return Ok(()),
|
|
}
|
|
} else {
|
|
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
|
|
Ok(message) => message,
|
|
Err(RecvTimeoutError::Timeout) => {
|
|
self.flush_dirty();
|
|
continue;
|
|
}
|
|
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
|
}
|
|
};
|
|
let batch = burst(&self.queue, message);
|
|
if self.process_batch(batch)? {
|
|
return Ok(());
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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);
|
|
// Where this burst's own held messages have to be spliced in. A scan
|
|
// this burst starts can hold messages of its *own* — ones that arrived
|
|
// while it ran, and therefore after everything still in this burst —
|
|
// so what is held from here goes in front of those and behind whatever
|
|
// was already waiting when the burst began.
|
|
let already_waiting = self.held.len();
|
|
// The `$/cancelRequest`s this burst has already carried, kept only
|
|
// long enough to put them back if a request behind them has to wait.
|
|
let mut consumed_cancels: Vec<Message> = Vec::new();
|
|
let mut messages = batch.into_iter();
|
|
while let Some(message) = messages.next() {
|
|
// A request that must wait takes everything behind it with it, or
|
|
// the burst's arrival order would not survive the wait —
|
|
// `shutdown` included, because a request sent before a shutdown
|
|
// is a request the client is still owed an answer to.
|
|
if self.must_wait() && matches!(message, Message::Request(_)) {
|
|
self.say_held(&message);
|
|
// The cancels this burst carried were consumed on the way
|
|
// here, and `cancelled_in` runs again over the held batch — so
|
|
// they go back in front of what they cancel rather than being
|
|
// lost. A cancel naming nothing in the held batch is dropped
|
|
// there exactly as it was dropped here.
|
|
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
|
|
rest.push(message);
|
|
rest.extend(messages);
|
|
rest.extend(self.held.split_off(already_waiting));
|
|
self.held.extend(rest);
|
|
return Ok(false);
|
|
}
|
|
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. Kept only so that a request behind
|
|
// one that has to wait takes its cancel with it.
|
|
Message::Notification(notification) if notification.method == Cancel::METHOD => {
|
|
consumed_cancels.push(Message::Notification(notification));
|
|
}
|
|
Message::Notification(notification) => self.notification(notification),
|
|
Message::Response(response) => self.response(response),
|
|
}
|
|
}
|
|
Ok(false)
|
|
}
|
|
|
|
/// Whether a request reaching the dispatch right now must wait instead of
|
|
/// being answered.
|
|
///
|
|
/// **This is the order contract, and it is the one thing interleaving a
|
|
/// scan with the message loop must not cost.** The loop has always
|
|
/// promised that everything queued *ahead* of a request is applied before
|
|
/// that request is answered — a `didChange` before a completion, and
|
|
/// equally a `didOpen` that widened the scope, a `didSave`, a changed
|
|
/// setting or an added workspace folder before a go-to-definition. Those
|
|
/// four ask for a rescan, and "applied" for them means the rescan has
|
|
/// **run**: one message at a time, the server would have finished it
|
|
/// before ever taking the request. Three clauses, one rule:
|
|
///
|
|
/// * `answering_a_rescan` — this scan is one a message asked for, so
|
|
/// every request that arrives while it runs arrived *after* that
|
|
/// message and is owed its effect;
|
|
/// * `rescan_wanted` — a message in this very burst has just asked for
|
|
/// one, and the requests behind it in the burst are owed the same;
|
|
/// * `held` — a request is already waiting, and answering a newer one
|
|
/// ahead of it would reorder them just as badly.
|
|
///
|
|
/// What is left answered mid-scan is exactly what is queued behind
|
|
/// *nothing*: the opening burst of a session, whose scan is the server's
|
|
/// own startup and not something a message asked for. That is the case
|
|
/// the round is about, and it is the one a user feels
|
|
/// (`docs/features/scan-interleave/README.md`).
|
|
fn must_wait(&self) -> bool {
|
|
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
|
|
}
|
|
|
|
/// Whether the installed index covers the whole scope with no indexing
|
|
/// work outstanding — what the hierarchy snapshot reports as `complete`.
|
|
///
|
|
/// **Both clauses, not just `scanning`.** `!self.scanning` alone would be
|
|
/// answering "is a scan running *this instant*", and a snapshot taken
|
|
/// between a finished scan and a rescan already asked for would call a
|
|
/// stale index complete. Today [`Server::must_wait`] makes that
|
|
/// unreachable — a request arriving with `rescan_wanted` set or anything
|
|
/// `held` is set aside rather than answered, so a snapshot only ever
|
|
/// reaches this function when both are already clear, and `rescan_wanted`
|
|
/// is in any case only ever set while `scanning` is true. Saying it here
|
|
/// anyway costs nothing and means the honesty of the flag does not depend
|
|
/// on a scheduling invariant two hundred lines away staying true; a
|
|
/// hypothetical future exemption from `must_wait` would degrade the flag,
|
|
/// not break it. Pinned by
|
|
/// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`.
|
|
fn index_is_complete(&self) -> bool {
|
|
!self.scanning && !self.must_wait()
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// requests
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Answer one request, timing it when `--verbose` asked.
|
|
///
|
|
/// **The line goes out before the response it describes.** The dispatch is
|
|
/// here and the response is sent by the caller, so a wrapper can only
|
|
/// speak first — which is also what keeps the measurement to exactly the
|
|
/// handler, with none of the transport in it. Nothing keys off the order:
|
|
/// a `window/logMessage` carries no id, and a client pairs the response
|
|
/// with its request by id whatever arrived in between.
|
|
fn request(&mut self, request: Request) -> Response {
|
|
let Some(started) = self.timer() else { return self.answer_request(request) };
|
|
let method = request.method.clone();
|
|
let response = self.answer_request(request);
|
|
self.timing(format!("{method} answered in {}", ms(started)));
|
|
response
|
|
}
|
|
|
|
fn answer_request(&mut self, request: Request) -> Response {
|
|
// A request answers from a buffer's analysis, so any change the client
|
|
// has already sent is in effect before it is answered — the order
|
|
// contract the loop has always promised. Here is also where a typing
|
|
// burst is coalesced: the changes before this request all become one
|
|
// `set_document` in `flush_dirty`.
|
|
self.flush_dirty();
|
|
let id = request.id.clone();
|
|
let method = request.method.clone();
|
|
// The large-file fast path answers first, and for most methods it
|
|
// answers "nothing" before any handler is entered. Everything it lets
|
|
// through is either cheap on an empty analysis or is the one request
|
|
// that does real work on a large buffer — see
|
|
// `docs/features/large-file-mode/README.md` for the whole table.
|
|
if let Some(answer) = self.large_file_answer(&method, &request.params) {
|
|
return match answer {
|
|
Ok(value) => Response::new_ok(id, value),
|
|
Err(failure) => failure.into_response(id),
|
|
};
|
|
}
|
|
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)),
|
|
// LSP 3.18's multi-range form of the line above — `n` ranges, one
|
|
// round trip, one answer. Answered whether or not the capability
|
|
// was widened for this client: a request we can serve is not
|
|
// refused because the client asked without saying it would.
|
|
format::RANGES_FORMATTING => decode(request).and_then(|p| self.ranges_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`.
|
|
//
|
|
// On a buffer over `lucisv.largeFile.threshold` this is the *only*
|
|
// colouring request that answers, and it lexes the window rather
|
|
// than filtering the document's tokens — there are none.
|
|
SemanticTokensRangeRequest::METHOD => {
|
|
decode(request).and_then(|p: SemanticTokensRangeParams| {
|
|
let data = match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) if doc.large => tokens::semantic_tokens_in_window(doc, p.range),
|
|
Some(doc) => tokens::semantic_tokens_in_range(doc, p.range),
|
|
None => return Ok(Value::Null),
|
|
};
|
|
to_value(SemanticTokensRangeResult::Tokens(SemanticTokens {
|
|
result_id: None,
|
|
data,
|
|
}))
|
|
})
|
|
}
|
|
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),
|
|
}
|
|
}),
|
|
design_hierarchy::METHOD => to_value(design_hierarchy::snapshot(
|
|
&self.workspace,
|
|
self.hierarchy_revision,
|
|
self.index_is_complete(),
|
|
)),
|
|
// 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))
|
|
})
|
|
}
|
|
// The client is about to rename files and asks what that costs.
|
|
// Every `` `include`` that *resolves* to one of them is re-spelled
|
|
// so it still resolves afterwards; one that no include path can
|
|
// reach is left exactly as written and named in a warning, because
|
|
// inventing a path that resolves to nothing would be worse than
|
|
// the stale one. `null` when there is nothing to do.
|
|
WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| {
|
|
let rewrite = file_ops::will_rename(&self.workspace, &p.files);
|
|
self.report_scope(rewrite.warnings);
|
|
match rewrite.edit {
|
|
Some(edit) => to_value(edit),
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
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),
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the large-file fast path
|
|
// ------------------------------------------------------------------
|
|
|
|
/// What a buffer over `lucisv.largeFile.threshold` answers `method`, or
|
|
/// `None` when the normal dispatch may run.
|
|
///
|
|
/// Four groups, and the reason each is what it is:
|
|
///
|
|
/// * **`semanticTokens/full` and `/full/delta` are declined with an
|
|
/// error.** Answering them with an empty set would be worse than not
|
|
/// answering: VS Code marks a model whose *document* provider returned
|
|
/// anything at all as having complete semantic tokens, and its viewport
|
|
/// contribution then never asks for a range again — the file would lose
|
|
/// all colour. An error leaves the model incomplete, so the range
|
|
/// provider keeps painting. The evidence for both halves is in
|
|
/// `docs/features/large-file-mode/README.md`.
|
|
/// * **The formatting requests refuse out loud.** A user pressed a key and
|
|
/// is owed a reason; silence there reads as a broken formatter. The
|
|
/// exceptions are the two the user did not press: `onTypeFormatting`
|
|
/// (a keystroke, and it never speaks) and `willSaveWaitUntil` (every
|
|
/// save), which decline the way they already decline.
|
|
/// * **`definition` and `references` scan the buffer.** The only two
|
|
/// answers a text scan can honestly give, and the whole reason the
|
|
/// buffer's text is still in memory.
|
|
/// * **Everything else answers nothing, fast** — and most of it is not
|
|
/// listed here at all: a fast-path `Document` holds the analysis of an
|
|
/// *empty* file, so those handlers already answer empty without knowing
|
|
/// this mode exists. Named below are only the ones that would otherwise
|
|
/// read the text itself.
|
|
fn large_file_answer(
|
|
&mut self,
|
|
method: &str,
|
|
params: &Value,
|
|
) -> Option<Result<Value, Failure>> {
|
|
// One boolean before anything is parsed: this runs ahead of every
|
|
// request, and a session with no large buffer in it — which is every
|
|
// session but one — must not pay a URI parse for the privilege.
|
|
if !self.workspace.has_large_documents() {
|
|
return None;
|
|
}
|
|
let uri = document_uri(params)?;
|
|
if !self.workspace.document(&uri).is_some_and(|doc| doc.large) {
|
|
return None;
|
|
}
|
|
let answer = match method {
|
|
SemanticTokensFullRequest::METHOD | SemanticTokensFullDeltaRequest::METHOD => {
|
|
Err(self.tokens_declined())
|
|
}
|
|
Formatting::METHOD | RangeFormatting::METHOD | format::RANGES_FORMATTING => {
|
|
self.edits(Err(TOO_LARGE.to_string()))
|
|
}
|
|
// Silent, both of them: one fires on every keystroke and one on
|
|
// every save.
|
|
OnTypeFormatting::METHOD => to_value(Vec::<lsp_types::TextEdit>::new()),
|
|
WillSaveWaitUntil::METHOD => Ok(Value::Null),
|
|
// A rename would rewrite every *other* file and leave this one
|
|
// untouched — the buffer is not in the index and not in
|
|
// `sources()` — so it is refused rather than half-applied.
|
|
// `prepareRename` declines quietly, so the box never opens.
|
|
PrepareRenameRequest::METHOD => Ok(Value::Null),
|
|
Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())),
|
|
// These three read the buffer's text rather than its analysis: the
|
|
// include scan, the `` `include`` line lookup a hover does, and
|
|
// the fix application a code action tries.
|
|
HoverRequest::METHOD => Ok(Value::Null),
|
|
DocumentLinkRequest::METHOD => to_value(Vec::<lsp_types::DocumentLink>::new()),
|
|
CodeActionRequest::METHOD => to_value(Vec::<lsp_types::CodeActionOrCommand>::new()),
|
|
GotoDefinition::METHOD => self.large_definition(&uri, params),
|
|
References::METHOD => self.large_references(&uri, params),
|
|
_ => return None,
|
|
};
|
|
Some(answer)
|
|
}
|
|
|
|
/// The error `semanticTokens/full` is declined with.
|
|
///
|
|
/// `ServerCancelled` for a client that advertised `serverCancelSupport`,
|
|
/// which is the code the spec reserves for exactly this and the code
|
|
/// `vscode-languageclient` turns into a `CancellationError`;
|
|
/// `ContentModified` for one that did not, which the same client turns
|
|
/// into the same `CancellationError` (semantic tokens are on its
|
|
/// `retryOnContentModified` list) and which every 3.16 client already
|
|
/// understands.
|
|
fn tokens_declined(&self) -> Failure {
|
|
let code = match self.abilities.token_server_cancel {
|
|
true => lsp_server::ErrorCode::ServerCancelled,
|
|
false => lsp_server::ErrorCode::ContentModified,
|
|
};
|
|
Failure::Declined(code, TOO_LARGE.to_string())
|
|
}
|
|
|
|
/// `textDocument/definition` on a large buffer: the first occurrence of
|
|
/// the name under the cursor that a declaring keyword introduces.
|
|
fn large_definition(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
|
let locations = self
|
|
.large_scan(uri, params, |doc, offset| {
|
|
large::definition(doc, offset).into_iter().collect()
|
|
})
|
|
.unwrap_or_default();
|
|
to_value(GotoDefinitionResponse::Array(locations))
|
|
}
|
|
|
|
/// `textDocument/references` on a large buffer: every whole-word
|
|
/// occurrence of the name under the cursor, capped.
|
|
fn large_references(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
|
let include = params
|
|
.get("context")
|
|
.and_then(|context| context.get("includeDeclaration"))
|
|
.and_then(Value::as_bool)
|
|
.unwrap_or(true);
|
|
let locations = self
|
|
.large_scan(uri, params, |doc, offset| large::references(doc, offset, include))
|
|
.unwrap_or_default();
|
|
to_value(locations)
|
|
}
|
|
|
|
/// Run one of the fast path's scans at the position `params` names, and
|
|
/// turn its spans into locations in the same file.
|
|
fn large_scan(
|
|
&self,
|
|
uri: &Uri,
|
|
params: &Value,
|
|
scan: impl Fn(&crate::state::Document, u32) -> Vec<vlog_parser::TextRange>,
|
|
) -> Option<Vec<Location>> {
|
|
let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?;
|
|
let doc = self.workspace.document(uri)?;
|
|
let positions = doc.positions();
|
|
let offset = positions.offset(position);
|
|
// Both scans answer in ascending order, so one monotonic cursor
|
|
// measures each line once — a thousand hits on one netlist line would
|
|
// otherwise re-measure that line a thousand times over.
|
|
let mut walker = positions.walker();
|
|
Some(
|
|
scan(doc, offset)
|
|
.into_iter()
|
|
.map(|span| Location { uri: uri.clone(), range: walker.range(span) })
|
|
.collect(),
|
|
)
|
|
}
|
|
|
|
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(), ¶ms.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(), ¶ms.options);
|
|
let result = format::range_formatting(doc, &settings.config, params.range);
|
|
self.warn_about_config(&uri, settings.problem);
|
|
self.edits(result)
|
|
}
|
|
|
|
/// `textDocument/rangesFormatting` — LSP 3.18's multi-range form.
|
|
///
|
|
/// Line for line the handler above, with `ranges` where it has `range`:
|
|
/// the same settings ladder, the same engine, the same `edits` and the
|
|
/// same config warning. That is the point of the feature — a client asking
|
|
/// for five ranges gets one verified answer instead of five requests whose
|
|
/// edits it would have to reconcile itself. See
|
|
/// `docs/features/lsp-318-extras/README.md`.
|
|
fn ranges_formatting(
|
|
&mut self,
|
|
params: format::RangesFormattingParams,
|
|
) -> 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(), ¶ms.options);
|
|
let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges);
|
|
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(), ¶ms.options);
|
|
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.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.pending.insert(id, Pending::ApplyEdit(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
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Handle one notification, timing it when `--verbose` asked. A
|
|
/// notification has no response, so there is no ordering question here:
|
|
/// the line follows the work.
|
|
fn notification(&mut self, notification: Notification) {
|
|
let Some(started) = self.timer() else { return self.handle_notification(notification) };
|
|
let method = notification.method.clone();
|
|
self.handle_notification(notification);
|
|
self.timing(format!("{method} handled in {}", ms(started)));
|
|
}
|
|
|
|
fn handle_notification(&mut self, notification: Notification) {
|
|
let method = notification.method.clone();
|
|
// A closing buffer's pending text is dropped *before* the flush, not
|
|
// in the `didClose` arm below it: the flush would otherwise analyze
|
|
// and publish diagnostics for a file the client has stopped looking
|
|
// at, only for the close handler to clear them again a line later.
|
|
// Every other dirty buffer still flushes, as it must — closing one
|
|
// file says nothing about the rest (QA, change-debounce CD-1).
|
|
if method == DidCloseTextDocument::METHOD {
|
|
if let Some(uri) = closing_uri(¬ification) {
|
|
self.dirty.retain(|(pending, _)| *pending != uri);
|
|
}
|
|
}
|
|
// Everything but a `didChange` needs the buffers' analyses current —
|
|
// a `didSave` rebuilds the index on top of them — so the same flush a
|
|
// request gets happens here, with the one exception that *is* the
|
|
// thing being deferred.
|
|
if method != DidChangeTextDocument::METHOD {
|
|
self.flush_dirty();
|
|
}
|
|
match method.as_str() {
|
|
DidOpenTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
|
let uri = p.text_document.uri;
|
|
// Opening a file in a folder the index does not cover
|
|
// *widens the scope*, so the folders it added are indexed
|
|
// and folded into the index beside what is already there;
|
|
// the widen rides the same bar and the same generation bump
|
|
// every other rescan trigger does. Opening one the scope
|
|
// already covers changes nothing about which files exist,
|
|
// and the save path still owns rebuilding.
|
|
//
|
|
// Only a *pure add* takes the cheap path, and `widen_of` is
|
|
// where that is decided: anything else — a scope directory
|
|
// that left, which nothing does today — falls back to the
|
|
// whole rescan (`docs/features/index-scope/README.md`).
|
|
//
|
|
// This is the rootless rule from before 2026-08-27,
|
|
// generalized: rung 3 is now the default rung with a root
|
|
// too, so "did this file widen the scope" is the one test,
|
|
// and it answers "no" for the filelist and whole-workspace
|
|
// rungs, which an open buffer cannot widen.
|
|
let before = self.workspace.scope_dirs();
|
|
self.set_document(uri.clone(), p.text_document.text);
|
|
match widen_of(&before, &self.workspace.scope_dirs()) {
|
|
Widen::Nothing => self.publish(&uri),
|
|
Widen::Added(dirs) => self.reindex_widened(dirs),
|
|
Widen::Whole => self.reindex(),
|
|
}
|
|
}
|
|
}
|
|
DidChangeTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
|
// Incremental sync: the changes are ranges into the buffer
|
|
// we hold — the newest applied text, which while dirty is
|
|
// the pending one, not the last analyzed one — applied in
|
|
// order. A full-sync client's rangeless change still
|
|
// replaces the whole buffer, so "the last one wins" stays
|
|
// true for it. A burst of changes is coalesced into one
|
|
// `set_document` — one reparse, one generation bump — when
|
|
// the buffer is flushed; see `mark_dirty`.
|
|
if p.content_changes.is_empty() {
|
|
return;
|
|
}
|
|
let uri = p.text_document.uri;
|
|
let text = {
|
|
let base = self
|
|
.dirty
|
|
.iter()
|
|
.find(|(pending, _)| *pending == uri)
|
|
.map(|(_, text)| text.as_str())
|
|
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
|
.unwrap_or("");
|
|
sync::apply_changes(base, &p.content_changes)
|
|
};
|
|
self.mark_dirty(uri, text);
|
|
}
|
|
}
|
|
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.
|
|
//
|
|
// A save names exactly one file, which is the case the
|
|
// index can replace in place — so this is where the
|
|
// incremental path earns its keep, and the whole rebuild is
|
|
// the fallback for a file the index does not already hold.
|
|
let one = crate::uri::uri_to_path(&p.text_document.uri);
|
|
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
|
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()) {
|
|
// One file named is the incremental case; a checkout
|
|
// filling the list, or the filelist itself moving, is
|
|
// the whole rebuild.
|
|
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
|
|
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
|
self.reindex();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// The client moved or removed files itself. The same nudge a
|
|
// watched-file event gives, filtered by the same predicate, and
|
|
// deliberately not deduplicated against it: a client is free to
|
|
// send both, and a second rebuild is a pure re-read of the tree —
|
|
// it costs one scan and one diagnostics generation, never a
|
|
// different answer.
|
|
DidRenameFiles::METHOD => {
|
|
if let Ok(p) = extract::<RenameFilesParams>(notification) {
|
|
self.reindex_for(file_ops::renamed(&p.files));
|
|
}
|
|
}
|
|
DidDeleteFiles::METHOD => {
|
|
if let Ok(p) = extract::<DeleteFilesParams>(notification) {
|
|
self.reindex_for(file_ops::deleted(&p.files));
|
|
}
|
|
}
|
|
// The `lucisv.*` settings, pushed at startup and on every change.
|
|
// Nothing here trusts the payload — `settings::from_payload`
|
|
// drops whatever it cannot use.
|
|
//
|
|
// An **empty** payload is not a settings payload at all: it is the
|
|
// 3.17 client saying "something changed, ask me for what you
|
|
// need", so a client that can be asked is asked and nothing is
|
|
// applied until it answers. A client that cannot be asked keeps
|
|
// the behaviour it has always had — an empty payload is no
|
|
// opinion about anything, which resolves to the defaults.
|
|
DidChangeConfiguration::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
|
|
if settings::says_nothing(&p.settings) && self.abilities.configuration {
|
|
self.request_configuration();
|
|
return;
|
|
}
|
|
self.apply_settings(settings::from_payload(&p.settings));
|
|
}
|
|
}
|
|
// The user added or removed a workspace folder mid-session. One
|
|
// rescan per *notification* — an event carries both lists, and
|
|
// the progress bar, the code-lens refresh and the diagnostics
|
|
// generation all ride along inside `reindex()`. An event that
|
|
// changes nothing (a folder already held, one never held, an
|
|
// empty event) rescans nothing.
|
|
DidChangeWorkspaceFolders::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeWorkspaceFoldersParams>(notification) {
|
|
let watched = self.workspace.filelist_path();
|
|
let added = folder_paths(&p.event.added);
|
|
let removed = folder_paths(&p.event.removed);
|
|
if self.workspace.change_roots(added, &removed) {
|
|
self.reindex();
|
|
}
|
|
// A relative `lucisv.filelist` is anchored at the *first*
|
|
// root, so a folder change can move the watched path
|
|
// without anyone touching the setting. Same rule, same
|
|
// reason as a changed setting: the path is baked into the
|
|
// registration. The source glob itself is workspace-wide
|
|
// and needs no re-registration — see
|
|
// `docs/features/folders-and-config/README.md`.
|
|
if self.workspace.filelist_path() != watched {
|
|
self.register_watchers();
|
|
}
|
|
}
|
|
}
|
|
DidCloseTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
|
let uri = p.text_document.uri;
|
|
self.config_warnings.remove(&uri);
|
|
// The buffer's unanalyzed change is already gone — it was
|
|
// dropped at the top of this function, ahead of the flush
|
|
// that would otherwise have analyzed it.
|
|
//
|
|
// 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.
|
|
///
|
|
/// Two answers are read: a `workspace/applyEdit`'s and a
|
|
/// `workspace/configuration`'s. Nothing else this server asks of the
|
|
/// client has an answer worth acting on: one that refuses the
|
|
/// file-watcher (un)registration simply keeps the save-only staleness
|
|
/// model; one that errors a `window/workDoneProgress/create` renders no
|
|
/// bar and ignores the `$/progress` that named that token, per spec; one
|
|
/// that declines a `workspace/codeLens/refresh` keeps the counts it has,
|
|
/// and the next save asks again; and one that could not open a
|
|
/// `window/showDocument` has already told the user so itself. None of
|
|
/// those ids is ever in `pending`, so they all fall out here — in any
|
|
/// arrival order, since the id is the whole of the lookup.
|
|
fn response(&mut self, response: Response) {
|
|
match self.pending.remove(&response.id) {
|
|
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
|
Some(Pending::Configuration) => self.configured(response),
|
|
None => {}
|
|
}
|
|
}
|
|
|
|
/// Say so when the client did not apply an edit the server pushed.
|
|
fn applied(&mut self, command: String, response: Response) {
|
|
// A refusal is worth saying out loud: the user ran a command, watched
|
|
// nothing happen, and would otherwise have no idea why. An answer that
|
|
// does not parse is a refusal too — nothing was seen to be applied.
|
|
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);
|
|
}
|
|
|
|
/// Adopt the settings the client answered a `workspace/configuration`
|
|
/// with.
|
|
///
|
|
/// **Never an error path.** The answer is an array with one entry per
|
|
/// requested item, and this asked for exactly one — so entry 0 is the
|
|
/// `lucisv` section. Anything else the client can send (an error, a
|
|
/// `null` entry, an empty array, an object where an array belongs, a
|
|
/// string) means the same thing: the client has no settings for us, which
|
|
/// is the defaults. Nothing here is worth a popup — the user did not ask
|
|
/// for this request and cannot act on its failure.
|
|
fn configured(&mut self, response: Response) {
|
|
let answered = response.response_result.unwrap_or(Value::Null);
|
|
let section = answered.get(0).cloned().unwrap_or(Value::Null);
|
|
self.apply_settings(settings::from_section(§ion));
|
|
}
|
|
|
|
/// Adopt `lucisv.*` settings, from wherever they came, and pay whatever
|
|
/// they cost.
|
|
///
|
|
/// One applier for the push and the pull, so the two can never disagree
|
|
/// about what a setting *does* any more than `settings::from_payload` and
|
|
/// `from_section` can disagree about what it says.
|
|
fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
|
let watched = self.workspace.filelist_path();
|
|
// Only `exclude` and `filelist` change which files exist as far as
|
|
// this server is concerned; the other settings are read afresh by the
|
|
// next request that wants them and need no invalidation.
|
|
if self.workspace.set_client_settings(settings) {
|
|
self.reindex();
|
|
}
|
|
// The watched filelist path is baked into the registration, so a new
|
|
// one needs a new registration.
|
|
if self.workspace.filelist_path() != watched {
|
|
self.register_watchers();
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// outgoing
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Ask the client for the `lucisv` section of its settings.
|
|
///
|
|
/// Silent for a client that did not advertise `workspace.configuration` —
|
|
/// that one is only ever pushed settings, which is what every client got
|
|
/// before this existed. No `scopeUri`: this server holds one set of
|
|
/// settings for the whole session, not one per folder, so asking
|
|
/// per-resource would be asking for answers it has nowhere to put.
|
|
fn request_configuration(&mut self) {
|
|
if !self.abilities.configuration {
|
|
return;
|
|
}
|
|
let params = ConfigurationParams {
|
|
items: vec![ConfigurationItem {
|
|
scope_uri: None,
|
|
section: Some(settings::SECTION.to_string()),
|
|
}],
|
|
};
|
|
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
|
self.pending.insert(id, Pending::Configuration);
|
|
}
|
|
|
|
/// Ask the client to watch the source files and the filelist for us,
|
|
/// replacing any registration already in force.
|
|
///
|
|
/// 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, but only when the paths a file-operation notification named are
|
|
/// paths the index reads. The same test a watched-file notification gets.
|
|
fn reindex_for(&mut self, paths: Vec<std::path::PathBuf>) {
|
|
let filelist = self.workspace.filelist_path();
|
|
if file_ops::touches_scope(&paths, filelist.as_deref()) {
|
|
self.reindex();
|
|
}
|
|
}
|
|
|
|
/// [`Server::reindex`] for a trigger that named exactly **one** file, when
|
|
/// that file is one the index already holds. Reports whether it ran; a
|
|
/// `false` means the caller owes a whole rebuild.
|
|
///
|
|
/// Everything a rebuild does *after* the scan happens here too, for the
|
|
/// same reasons: the code-lens refresh (the file that moved may have
|
|
/// changed an instantiation count in any buffer), the diagnostics
|
|
/// generation bump (every open buffer's diagnostics are computed against
|
|
/// the index), and a republish of every open buffer. The republish stays
|
|
/// wholesale rather than narrowing to the buffers that could have moved:
|
|
/// a lint reads the index, so any buffer's diagnostics may have changed,
|
|
/// and narrowing it correctly needs a dependency graph this server does not
|
|
/// have. Worth doing later; wrong to guess at now.
|
|
///
|
|
/// Three things a whole rebuild does that this deliberately does not:
|
|
///
|
|
/// * **no progress bar.** The bar exists because a whole scan takes
|
|
/// perceptible seconds on a large workspace; one file is one parse, and a
|
|
/// bar that appears and vanishes inside a frame is noise, not progress.
|
|
/// * **no per-file log line.** Same reason, and the log's purpose — "which
|
|
/// files is this scan reading?" — is a question about a scan.
|
|
/// * **no scope warnings.** They come from *resolving* the scope, and the
|
|
/// scope was not re-resolved: nothing about which files exist changed, so
|
|
/// repeating a filelist's complaints would be repeating stale news.
|
|
fn reindex_one(&mut self, path: &Path) -> bool {
|
|
// Mid-scan the cheap path is not available and is not needed: the scan
|
|
// holds the text this file had when it started and will index *that*,
|
|
// so patching the half-built index here would be overwritten by older
|
|
// bytes a moment later. One more scan when this one ends is the whole
|
|
// answer, and it is the same flag every other mid-scan trigger sets.
|
|
// `true` because the caller's fallback — a whole rebuild, right now —
|
|
// is exactly what must not happen.
|
|
if self.scanning {
|
|
self.rescan_wanted = true;
|
|
return true;
|
|
}
|
|
let started = self.timer();
|
|
if !self.workspace.update_one(path) {
|
|
// No line: nothing was reindexed, and the caller is about to
|
|
// rebuild the whole index — which times itself.
|
|
return false;
|
|
}
|
|
self.refresh_code_lenses();
|
|
self.hierarchy_index_changed();
|
|
self.generation += 1;
|
|
for uri in self.workspace.open_uris() {
|
|
self.publish(&uri);
|
|
}
|
|
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
|
|
true
|
|
}
|
|
|
|
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
|
|
/// the scope: index those folders and fold them in, leaving every file
|
|
/// already indexed exactly as it is.
|
|
///
|
|
/// Everything after the scan is what a whole rescan does, for the same
|
|
/// reasons — the widen changes which names exist, so lenses, the
|
|
/// diagnostics generation and every open buffer's publish all move with it.
|
|
///
|
|
/// **Mid-scan this defers to one whole rescan rather than widening.** A
|
|
/// scan already running holds a work list taken from the *old* scope, and
|
|
/// folding a widen into it would mean two answers to "which files exist"
|
|
/// inside one scan; the follow-up scan the flag asks for reads the
|
|
/// persistent store for everything the running scan already parsed, so it
|
|
/// is the cheap kind. This is the same flag every other mid-scan trigger
|
|
/// sets, and it is what keeps the coalescing rule one rule
|
|
/// (`docs/features/scan-interleave/README.md`).
|
|
fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
|
|
if self.scanning {
|
|
self.rescan_wanted = true;
|
|
return;
|
|
}
|
|
let started = self.timer();
|
|
if started.is_some() {
|
|
// The folders by name: which folder a jump widened into is the one
|
|
// thing the file log below it does not say in one line.
|
|
let paths: Vec<String> = added.iter().map(|p| p.display().to_string()).collect();
|
|
let folders = added.len();
|
|
self.timing(format!(
|
|
"widen started: {folders} folder{} added: {}",
|
|
plural(folders),
|
|
paths.join(", ")
|
|
));
|
|
}
|
|
let bar = self.begin_indexing();
|
|
let mut scan =
|
|
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
|
|
let total = scan.total();
|
|
// No drain between the files: a widen is a rescan a message asked for,
|
|
// and `must_wait` would hold every request queued behind it anyway. It
|
|
// is also the point of the round that there is no longer a wait worth
|
|
// interleaving — a widen indexes one folder, not the whole scope.
|
|
loop {
|
|
let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| {
|
|
workspace.scan_step(&mut scan, watch)
|
|
};
|
|
if !self.watching(bar.as_ref(), step) {
|
|
break;
|
|
}
|
|
}
|
|
let (skipped, cached) = (scan.skipped(), scan.cached());
|
|
let warnings = self.workspace.finish_scan(scan);
|
|
self.end_indexing(bar, skipped, cached);
|
|
self.timed(started, |took| {
|
|
format!(
|
|
"widen finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
|
plural(total)
|
|
)
|
|
});
|
|
self.refresh_code_lenses();
|
|
self.hierarchy_index_changed();
|
|
self.generation += 1;
|
|
self.report_scope(warnings);
|
|
for uri in self.workspace.open_uris() {
|
|
self.publish(&uri);
|
|
}
|
|
}
|
|
|
|
/// 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`, a watched file changing on disk,
|
|
/// or a file the client renamed or deleted.
|
|
fn reindex(&mut self) {
|
|
// A rescan asked for by a message this scan answered is *this* scan's
|
|
// successor, not a scan inside it. See `scan_until_settled`.
|
|
if self.scanning {
|
|
self.rescan_wanted = true;
|
|
return;
|
|
}
|
|
let warnings = self.scan_until_settled(true);
|
|
if self.stopped {
|
|
return;
|
|
}
|
|
// 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();
|
|
self.hierarchy_index_changed();
|
|
// 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);
|
|
}
|
|
}
|
|
|
|
/// Scan, and go on scanning while the messages answered along the way keep
|
|
/// asking for one. Reports the last scan's scope warnings.
|
|
///
|
|
/// **The whole of the coalescing rule, and it is a loop rather than a
|
|
/// recursion on purpose.** A `didSave`, a widened scope, a changed
|
|
/// setting or a watched-file burst answered mid-scan sets
|
|
/// `rescan_wanted`; any number of them is one more scan. Finishing the
|
|
/// current scan and then running another was chosen over aborting and
|
|
/// restarting it because it needs no way to unwind a half-published index
|
|
/// and cannot loop for ever on its own — the follow-up scan reads the
|
|
/// persistent cache for every file the abandoned one already parsed, so
|
|
/// it is the cheap kind. Each scan gets its own progress token, which is
|
|
/// what a client showing a bar expects of two scans.
|
|
fn scan_until_settled(&mut self, mut asked_for: bool) -> Vec<String> {
|
|
self.scanning = true;
|
|
let warnings = loop {
|
|
self.answering_a_rescan = asked_for;
|
|
let warnings = self.scan_once();
|
|
if !std::mem::take(&mut self.rescan_wanted) || self.stopped {
|
|
break warnings;
|
|
}
|
|
// Every scan after the first one here is one a message asked for,
|
|
// whatever the first one was.
|
|
asked_for = true;
|
|
};
|
|
self.answering_a_rescan = false;
|
|
self.scanning = false;
|
|
warnings
|
|
}
|
|
|
|
/// One whole scan: the bar up, every file indexed with the client's
|
|
/// messages answered between two of them, the bar down.
|
|
///
|
|
/// A scan a `shutdown` interrupted stops where it stands and reports no
|
|
/// warnings: nothing after this may speak to a client that has gone. The
|
|
/// records of the files it did index are already in the persistent store —
|
|
/// they are written through per file — so the next session resumes from
|
|
/// them, exactly as it does after any other half-done scan.
|
|
fn scan_once(&mut self) -> Vec<String> {
|
|
// Before the bar and before the work list is built: resolving the
|
|
// scope and walking it is part of what a scan costs, and a number that
|
|
// left it out would be the wrong answer to "why was that slow?".
|
|
let started = self.timer();
|
|
let bar = self.begin_indexing();
|
|
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
|
|
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
|
let total = scan.total();
|
|
if started.is_some() {
|
|
// Whether it interleaves is said here because it is decided here,
|
|
// and because it is the answer to "why did my hover wait?" — a
|
|
// scan that does not interleave answers nothing until it is done.
|
|
let interleaving = if interleave { ", interleaved" } else { "" };
|
|
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
|
|
}
|
|
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
|
|
{
|
|
if interleave && self.answer_what_is_waiting(&mut scan) {
|
|
// Nothing after this may speak to a client that has gone, the
|
|
// timing line included.
|
|
return Vec::new();
|
|
}
|
|
}
|
|
let (skipped, cached) = (scan.skipped(), scan.cached());
|
|
let warnings = self.workspace.finish_scan(scan);
|
|
self.end_indexing(bar, skipped, cached);
|
|
self.timed(started, |took| {
|
|
format!(
|
|
"scan finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
|
plural(total)
|
|
)
|
|
});
|
|
warnings
|
|
}
|
|
|
|
/// Do one piece of a scan with the progress bar and the per-file log
|
|
/// watching it.
|
|
///
|
|
/// The fields are split apart because the watcher writes to the connection
|
|
/// while the workspace is borrowed mutably for the work it is watching —
|
|
/// the split `Server::new` used to make inline, made once here because a
|
|
/// scan is now several calls instead of one. A fresh `IndexWatch` per call
|
|
/// costs nothing and re-reads `lucisv.index.logFiles`, so a settings change
|
|
/// answered mid-scan is honoured by the very next file's log line.
|
|
fn watching<T>(
|
|
&mut self,
|
|
bar: Option<&ProgressToken>,
|
|
step: impl FnOnce(&mut Workspace, &mut dyn FnMut(IndexEvent)) -> T,
|
|
) -> T {
|
|
let Server { connection, workspace, .. } = self;
|
|
let mut watch = IndexWatch::new(connection, bar, workspace.client_settings());
|
|
step(workspace, &mut |event| watch.see(event))
|
|
}
|
|
|
|
/// Answer everything the client has already sent, against the index as far
|
|
/// as this scan has built it. Reports whether the client shut us down.
|
|
///
|
|
/// **This is the round's whole point, and its whole cost.** Polling costs
|
|
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
|
|
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
|
|
/// on pays one merge per burst to make the records it has taken since the
|
|
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
|
|
/// through the same `process_batch` the loop uses, so a `didChange` queued
|
|
/// ahead of a hover is applied before that hover is answered and a cancel
|
|
/// beside its request still answers it `RequestCancelled` — the order
|
|
/// contract is the loop's, unchanged, because it is the loop's code.
|
|
///
|
|
/// An error here is a client that has gone: there is nobody to report it
|
|
/// to and no reason to go on scanning, so it stops the scan the same way a
|
|
/// `shutdown` does.
|
|
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
|
|
let mut batch = Vec::new();
|
|
while let Ok(message) = self.queue.try_recv() {
|
|
batch.push(message);
|
|
}
|
|
if batch.is_empty() {
|
|
return false;
|
|
}
|
|
let opened = opened_in(&batch);
|
|
self.workspace.publish_scan(scan);
|
|
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
|
// The file the user has just opened is the one they are looking at, so
|
|
// it is indexed next rather than when the alphabet reaches it — the
|
|
// open-first rule, for a file opened after the work list was taken.
|
|
for path in opened {
|
|
scan.index_next(&path);
|
|
}
|
|
self.stopped
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// The `begin` carries no percentage: the first one that means anything
|
|
/// is the first file's, and it is `IndexWatch` that sends it. Every
|
|
/// percentage from there on is measured — `n` files of a work list whose
|
|
/// length was known before the first parse — never invented.
|
|
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.
|
|
///
|
|
/// `skipped` is how many files the size cap kept out, and it is named here
|
|
/// whether or not the per-file log is on: the log is the *detail*, and a
|
|
/// user who turned it off should still learn that part of their workspace
|
|
/// is not in the index. `cached` is how many were restored from the
|
|
/// persistent index cache rather than parsed, and is named for the
|
|
/// opposite reason — a scan that finished suspiciously fast should say
|
|
/// why (`docs/features/index-persistence/README.md`).
|
|
fn end_indexing(&self, token: Option<ProgressToken>, skipped: usize, cached: usize) {
|
|
let Some(token) = token else { return };
|
|
let files = self.workspace.index().files().len();
|
|
let plural = if files == 1 { "" } else { "s" };
|
|
let mut message = format!("{files} file{plural} indexed");
|
|
if cached > 0 {
|
|
message.push_str(&format!(", {cached} from cache"));
|
|
}
|
|
if skipped > 0 {
|
|
message.push_str(&format!(", {skipped} skipped"));
|
|
}
|
|
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message: Some(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. Since scan-interleave, the
|
|
/// startup scan can send it too: a `didOpen` answered mid-scan leaves a
|
|
/// buffer whose lenses were computed against the half-built index, and
|
|
/// `started` refreshes them once the bar comes down. 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, ());
|
|
}
|
|
|
|
/// Publish a new completed hierarchy revision after any index mutation.
|
|
fn hierarchy_index_changed(&mut self) {
|
|
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
|
|
if !self.abilities.hierarchy_view {
|
|
return;
|
|
}
|
|
notify_on(
|
|
&self.connection,
|
|
design_hierarchy::CHANGED_METHOD,
|
|
serde_json::json!({ "revision": self.hierarchy_revision }),
|
|
);
|
|
}
|
|
|
|
/// One `$/progress` notification for a token the client already knows.
|
|
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
|
|
progress_on(&self.connection, &token, value);
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// `workspace/willRenameFiles` reports through here too: an `` `include``
|
|
/// a rename strands is the same kind of news, said at the same volume, and
|
|
/// a rename that strands forty of them must not open forty popups.
|
|
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);
|
|
let was_large = self.workspace.document(&uri).is_some_and(|doc| doc.large);
|
|
self.workspace.set_document(uri.clone(), text);
|
|
self.generation += 1;
|
|
self.announce_fast_path(&uri, was_large);
|
|
}
|
|
|
|
/// Hold a buffer's newest text for later analysis. A change already held
|
|
/// is replaced in place, so the entry's position in the flush order — the
|
|
/// order the buffers were first dirtied in — survives a burst.
|
|
fn mark_dirty(&mut self, uri: Uri, text: String) {
|
|
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
|
|
Some(entry) => entry.1 = text,
|
|
None => self.dirty.push((uri, text)),
|
|
}
|
|
}
|
|
|
|
/// Analyze and republish every dirty buffer, oldest first. One flush is
|
|
/// one `set_document` per buffer, so a whole typing burst costs one
|
|
/// reparse per buffer it touched instead of one per keystroke.
|
|
fn flush_dirty(&mut self) {
|
|
if self.dirty.is_empty() {
|
|
return;
|
|
}
|
|
let started = self.timer();
|
|
let buffers = self.dirty.len();
|
|
for (uri, text) in std::mem::take(&mut self.dirty) {
|
|
self.set_document(uri.clone(), text);
|
|
self.publish(&uri);
|
|
}
|
|
self.timed(started, |took| {
|
|
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
|
});
|
|
}
|
|
|
|
/// Say once, in the output channel, that a buffer is on the large-file
|
|
/// fast path.
|
|
///
|
|
/// Once per *entry* into the mode, not once per notification: a keystroke
|
|
/// in a 100 MB buffer must not log a line, and a buffer edited past the
|
|
/// threshold mid-session must. Nothing is said on the way back out —
|
|
/// leaving the mode restores every answer, which is not news.
|
|
fn announce_fast_path(&self, uri: &Uri, was_large: bool) {
|
|
let Some(doc) = self.workspace.document(uri).filter(|doc| doc.large && !was_large) else {
|
|
return;
|
|
};
|
|
let what = match doc.path.as_deref() {
|
|
Some(path) => path.display().to_string(),
|
|
None => uri.as_str().to_string(),
|
|
};
|
|
let size = doc.text.len();
|
|
self.notify(
|
|
LogMessage::METHOD,
|
|
LogMessageParams {
|
|
typ: MessageType::INFO,
|
|
message: format!(
|
|
"lucisv: large-file fast path: {what} ({size} bytes) — \
|
|
syntax highlighting only, nothing is parsed or indexed"
|
|
),
|
|
},
|
|
);
|
|
}
|
|
|
|
/// 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) {
|
|
notify_on(&self.connection, method, params);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// timing (`--verbose`)
|
|
// ------------------------------------------------------------------
|
|
|
|
/// The clock a timing line reads, started **only** when `--verbose` asked
|
|
/// for one.
|
|
///
|
|
/// `None` is the whole of what verbose-off costs: one branch here, and
|
|
/// then no clock read, no `format!` and no notification anywhere below.
|
|
/// Every timing site starts with this.
|
|
fn timer(&self) -> Option<std::time::Instant> {
|
|
self.verbose.then(std::time::Instant::now)
|
|
}
|
|
|
|
/// One timing line for work that was being timed — and nothing at all,
|
|
/// closure included, for work that was not.
|
|
fn timed(&self, started: Option<std::time::Instant>, line: impl FnOnce(&str) -> String) {
|
|
let Some(started) = started else { return };
|
|
self.timing(line(&ms(started)));
|
|
}
|
|
|
|
/// One `timing:` line in the client's output channel.
|
|
///
|
|
/// `MessageType::LOG` and the same `window/logMessage` the per-file index
|
|
/// log uses — the channel is already this server's, and the one-word
|
|
/// prefix is what lets a reader (or a `grep`) pick these out of it. Sent
|
|
/// straight down the writer thread like every other notification, so it
|
|
/// cannot block on anything the loop is holding.
|
|
fn timing(&self, line: String) {
|
|
self.notify(
|
|
LogMessage::METHOD,
|
|
LogMessageParams { typ: MessageType::LOG, message: format!("timing: {line}") },
|
|
);
|
|
}
|
|
|
|
/// One line for a request the order contract makes wait, naming which of
|
|
/// [`Server::must_wait`]'s three clauses held it.
|
|
///
|
|
/// The question this answers is the one a slow-looking editor raises:
|
|
/// "was that request slow, or was it never started?". Silent for anything
|
|
/// that is not a request — nothing else waits.
|
|
fn say_held(&self, message: &Message) {
|
|
if !self.verbose {
|
|
return;
|
|
}
|
|
let Message::Request(request) = message else { return };
|
|
self.timing(format!(
|
|
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
|
|
request.method,
|
|
self.answering_a_rescan,
|
|
self.rescan_wanted,
|
|
self.held.len()
|
|
));
|
|
}
|
|
|
|
/// 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))
|
|
}
|
|
}
|
|
|
|
/// How long ago, in milliseconds — the one unit every timing line is written
|
|
/// in, to two decimals so that a sub-millisecond answer is still a number.
|
|
fn ms(started: std::time::Instant) -> String {
|
|
format!("{:.2} ms", started.elapsed().as_secs_f64() * 1_000.0)
|
|
}
|
|
|
|
/// The `s` a count needs, or nothing. One file is not "1 files".
|
|
fn plural(count: usize) -> &'static str {
|
|
if count == 1 {
|
|
""
|
|
} else {
|
|
"s"
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// watching an index rebuild
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// How many `$/progress` reports one rescan may send.
|
|
///
|
|
/// One per file is right for the workspaces people actually have — the 860-file
|
|
/// corpus is 860 small notifications across two thirds of a second — but a
|
|
/// 40,000-file filelist would be 40,000 of them on every save. Past this many
|
|
/// files the reports thin out to every ⌈total/1000⌉-th, which still moves the
|
|
/// bar by a tenth of a percent at a time: under a pixel.
|
|
const MAX_REPORTS: usize = 1000;
|
|
|
|
/// Whether the file numbered `done` (from 0) of `total` gets a `report`.
|
|
///
|
|
/// The last file always reports, so a rescan's final bar position is always
|
|
/// `total/total` at 100%. Without that, a 10,000-file scan would stop
|
|
/// reporting at 10,000 exactly — but a 10,001-file one would stop at 10,000
|
|
/// and leave the bar a file short of the work it had finished.
|
|
fn reports(done: usize, total: usize) -> bool {
|
|
let step = total.div_ceil(MAX_REPORTS).max(1);
|
|
(done + 1).is_multiple_of(step) || done + 1 == total
|
|
}
|
|
|
|
/// Watches one index rebuild: a `$/progress` report and a log line per file,
|
|
/// and a count of the files the size cap skipped.
|
|
///
|
|
/// Holds the connection rather than the `Server`, because the workspace is
|
|
/// borrowed mutably for the whole of the rebuild being watched. Everything it
|
|
/// sends is a notification, so nothing here can fail in a way a caller could
|
|
/// act on.
|
|
struct IndexWatch<'a> {
|
|
connection: &'a Connection,
|
|
/// The bar to report against — `None` for a client that cannot show one,
|
|
/// which is the same gate `begin_indexing` applied.
|
|
bar: Option<&'a ProgressToken>,
|
|
/// `lucisv.index.logFiles`: whether the per-file lines are sent at all.
|
|
log_files: bool,
|
|
}
|
|
|
|
impl<'a> IndexWatch<'a> {
|
|
fn new(
|
|
connection: &'a Connection,
|
|
bar: Option<&'a ProgressToken>,
|
|
settings: &ClientSettings,
|
|
) -> IndexWatch<'a> {
|
|
IndexWatch { connection, bar, log_files: settings.log_files }
|
|
}
|
|
|
|
/// Report one thing the rebuild just did.
|
|
fn see(&mut self, event: IndexEvent) {
|
|
match event {
|
|
IndexEvent::Parsing { done, total, path } => {
|
|
self.say(format!("indexing: {}", path.display()));
|
|
self.tick(done, total, path);
|
|
}
|
|
// A different word for a file that cost nothing, and the same
|
|
// tick: a cached file is a file of the work list, and the bar
|
|
// flying through them is exactly what the cache bought.
|
|
IndexEvent::Cached { done, total, path } => {
|
|
self.say(format!("cached: {}", path.display()));
|
|
self.tick(done, total, path);
|
|
}
|
|
// A third word, and no count in the end message: an open buffer's
|
|
// own analysis costs nothing either, but one file out of a
|
|
// workspace is not why a scan finished fast, and a bar that grew a
|
|
// clause on every session with a file open would say less, not
|
|
// more. The per-file log still names it, which is where a user
|
|
// asking "did it re-parse my huge buffer?" looks.
|
|
IndexEvent::Analyzed { done, total, path } => {
|
|
self.say(format!("analyzed: {}", path.display()));
|
|
self.tick(done, total, path);
|
|
}
|
|
IndexEvent::Skipped { path, size, cap } => {
|
|
self.say(format!(
|
|
"skipped ({} > {} cap): {}",
|
|
human_size(size),
|
|
human_size(cap),
|
|
path.display()
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Move the bar to `done + 1` of `total`, if this file is one of the ones
|
|
/// that reports.
|
|
///
|
|
/// The message names the file rather than its path: the bar is a strip of
|
|
/// status bar a few dozen characters wide, and the path is in the log for
|
|
/// anyone who wants it. The percentage is `(done + 1) / total`, which
|
|
/// only ever counts up.
|
|
fn tick(&self, done: usize, total: usize, path: &Path) {
|
|
let Some(token) = self.bar else { return };
|
|
if !reports(done, total) {
|
|
return;
|
|
}
|
|
let name = path.file_name().unwrap_or(path.as_os_str()).to_string_lossy();
|
|
let report = WorkDoneProgressReport {
|
|
cancellable: Some(false),
|
|
message: Some(format!("{}/{total} {name}", done + 1)),
|
|
// `total` cannot be 0 here — this is called from inside the loop
|
|
// over the files — but a percentage is not worth a division that
|
|
// has to be argued about.
|
|
percentage: Some(((done + 1) * 100 / total.max(1)) as u32),
|
|
};
|
|
progress_on(self.connection, token, WorkDoneProgress::Report(report));
|
|
}
|
|
|
|
/// One line in the client's output channel, if the user left the file log
|
|
/// on.
|
|
///
|
|
/// `MessageType::LOG`, unprefixed: these are hundreds of lines per rescan
|
|
/// in a channel that is already this server's, and "lucisv: " on every one
|
|
/// of them would be noise plus traffic. The scope warnings, which are
|
|
/// rare and also shown in a popup, keep their prefix.
|
|
fn say(&self, message: String) {
|
|
if !self.log_files {
|
|
return;
|
|
}
|
|
let params = LogMessageParams { typ: MessageType::LOG, message };
|
|
notify_on(self.connection, LogMessage::METHOD, params);
|
|
}
|
|
}
|
|
|
|
/// A byte count in the largest unit that keeps it readable.
|
|
///
|
|
/// The cap is written in bytes and can be set to anything, so a fixed unit is
|
|
/// wrong at one end or the other: "0.0 MiB > 0.0 MiB cap" says nothing about a
|
|
/// 4 KiB file under a 1 KiB cap, and "4194304 B" says nothing quickly about a
|
|
/// netlist.
|
|
fn human_size(bytes: u64) -> String {
|
|
const KIB: f64 = 1024.0;
|
|
const MIB: f64 = KIB * 1024.0;
|
|
// The unit is chosen by what the ROUNDED number reads as, not the raw
|
|
// size: 1 048 575 bytes is "1.0 MiB", never "1024.0 KiB" (QA log,
|
|
// 2026-08-27 — the same class of bug the e2e's "0.0 MiB > 0.0 MiB"
|
|
// caught at the opposite edge).
|
|
let size = bytes as f64;
|
|
if size < KIB {
|
|
format!("{bytes} B")
|
|
} else if (size / KIB).round() < KIB {
|
|
format!("{:.1} KiB", size / KIB)
|
|
} else {
|
|
format!("{:.1} MiB", size / MIB)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod human_size_tests {
|
|
use super::human_size;
|
|
|
|
#[test]
|
|
fn the_unit_is_chosen_by_what_the_rounded_number_reads_as() {
|
|
// QA finding, 2026-08-27: a byte short of a MiB must not print as
|
|
// "1024.0 KiB". The unit flips when the smaller unit's rounded
|
|
// number would read as the next unit.
|
|
assert_eq!(human_size(1_048_575), "1.0 MiB");
|
|
assert_eq!(human_size(1_048_576), "1.0 MiB");
|
|
assert_eq!(human_size(1023), "1023 B");
|
|
assert_eq!(human_size(1024), "1.0 KiB");
|
|
assert_eq!(human_size(4_096), "4.0 KiB");
|
|
assert_eq!(human_size(2_411_724), "2.3 MiB");
|
|
}
|
|
}
|
|
|
|
/// One `$/progress` notification, on a connection rather than through a
|
|
/// `Server` — what the index watcher has while the workspace is borrowed.
|
|
fn progress_on(connection: &Connection, token: &ProgressToken, value: WorkDoneProgress) {
|
|
let params =
|
|
ProgressParams { token: token.clone(), value: ProgressParamsValue::WorkDone(value) };
|
|
notify_on(connection, Progress::METHOD, params);
|
|
}
|
|
|
|
/// One notification, on a connection rather than through a `Server`.
|
|
fn notify_on(connection: &Connection, 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 _ = connection.sender.send(Message::Notification(notification));
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// 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)
|
|
}
|
|
|
|
/// 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
|
|
/// [`burst`] — and of the drain a scan does between two of its files.
|
|
///
|
|
/// 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 — and it never parses, which is why it is the one
|
|
/// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE`
|
|
/// (`docs/features/recursion-limit`).
|
|
fn forward(
|
|
connection: &Connection,
|
|
) -> (std::sync::mpsc::Sender<Message>, std::sync::mpsc::Receiver<Message>) {
|
|
let (sender, receiver) = std::sync::mpsc::channel();
|
|
let source = connection.receiver.clone();
|
|
let ours = sender.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;
|
|
}
|
|
}
|
|
});
|
|
(ours, receiver)
|
|
}
|
|
|
|
/// `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()
|
|
}
|
|
|
|
/// What a `didOpen` did to the index scope, and therefore which of the three
|
|
/// answers it is owed.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
enum Widen {
|
|
/// The scope did not move: the file is in a folder already covered, or the
|
|
/// rung in force is one an open buffer cannot widen (a filelist, or the
|
|
/// whole-workspace walk). Publish and index nothing.
|
|
Nothing,
|
|
/// Folders were added and nothing else changed — the cheap path, indexing
|
|
/// only what the added folders bring in
|
|
/// ([`Server::reindex_widened`]).
|
|
Added(Vec<std::path::PathBuf>),
|
|
/// Anything else. The whole rescan, which is always a correct answer.
|
|
Whole,
|
|
}
|
|
|
|
/// Which of the three [`Widen`] answers a move from `before` to `after` is.
|
|
///
|
|
/// **The chooser, and it is deliberately narrow**: only a scope that grew and
|
|
/// lost nothing takes the incremental path, because that is the only shape
|
|
/// whose result is the whole rescan's by construction — a directory that left
|
|
/// the scope can take files out of the index, and working out *which* files is
|
|
/// the walk the widen exists not to do. Nothing in the server takes a directory
|
|
/// out of the folder scope today (`opened_dirs` only grows, and a `didClose`
|
|
/// costs no rescan at all), so the third arm is a rule kept rather than a case
|
|
/// reached; a future shrink gets a correct answer instead of a subtle one.
|
|
///
|
|
/// **A directory that subsumes one already in scope is an add** (2026-08-29,
|
|
/// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a
|
|
/// user opens routinely raises to a *parent* of the directory the first one
|
|
/// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add
|
|
/// here, because every opened directory is raised on its own and the list keeps
|
|
/// them all: the contained directory is in `after` beside the containing one,
|
|
/// and nothing was lost. The overlap is not re-read either, because
|
|
/// `Workspace::begin_widen`'s work list is diffed **by file against what the
|
|
/// index holds** rather than by folder against the old walk.
|
|
///
|
|
/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so
|
|
/// equality is set equality and `contains` is over a handful of directories.
|
|
fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen {
|
|
if before == after {
|
|
return Widen::Nothing;
|
|
}
|
|
if before.iter().any(|dir| !after.contains(dir)) {
|
|
return Widen::Whole;
|
|
}
|
|
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
|
|
}
|
|
|
|
/// The files a burst opened, in the order the client opened them.
|
|
///
|
|
/// Read off the raw messages rather than off the workspace afterwards,
|
|
/// because the workspace holds its buffers in a `HashMap` and "which file did
|
|
/// the user just open" is a question about order.
|
|
fn opened_in(batch: &[Message]) -> Vec<std::path::PathBuf> {
|
|
batch
|
|
.iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(notification)
|
|
if notification.method == DidOpenTextDocument::METHOD =>
|
|
{
|
|
document_uri(¬ification.params)
|
|
}
|
|
_ => None,
|
|
})
|
|
.filter_map(|uri| crate::uri::uri_to_path(&uri))
|
|
.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),
|
|
/// The server chose not to compute an answer it could have computed, with
|
|
/// a code that tells the client to keep what it has and ask again rather
|
|
/// than to treat this as the answer. The large-file fast path declines
|
|
/// `semanticTokens/full` this way; nothing else uses it.
|
|
Declined(lsp_server::ErrorCode, 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}"))
|
|
}
|
|
Failure::Declined(code, message) => (code as i32, format!("lucisv: {message}")),
|
|
};
|
|
Response::new_err(id, code, message)
|
|
}
|
|
}
|
|
|
|
/// The sentence every large-buffer refusal carries. One string, because a
|
|
/// user who meets it twice should not have to work out whether they are the
|
|
/// same thing.
|
|
const TOO_LARGE: &str =
|
|
"this buffer is over lucisv.largeFile.threshold and is open on the large-file fast path";
|
|
|
|
/// The `textDocument.uri` a request names, read out of the raw params.
|
|
///
|
|
/// Before the typed decode on purpose: the fast-path gate has to know which
|
|
/// buffer a request is about without knowing which of thirty parameter types
|
|
/// it carries, and every document-scoped request in LSP spells it exactly
|
|
/// here. A request with no `textDocument` (the hierarchy resolutions, the
|
|
/// workspace-wide ones, `executeCommand`) is not gated at all, which is
|
|
/// correct: none of them can reach a buffer's text.
|
|
fn document_uri(params: &Value) -> Option<Uri> {
|
|
params.get("textDocument")?.get("uri")?.as_str()?.parse().ok()
|
|
}
|
|
|
|
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()))
|
|
}
|
|
|
|
/// The paths behind a `didChangeWorkspaceFolders` list.
|
|
///
|
|
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
|
|
/// decoded — is dropped rather than guessed at, the same rule `uri.rs` holds
|
|
/// everywhere else: there is nothing on disk to walk for it.
|
|
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
|
|
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
|
|
}
|
|
|
|
/// A notification's params, or `Err` when they do not parse — a malformed
|
|
/// notification is dropped, because there is no id to answer it on.
|
|
fn extract<P: DeserializeOwned>(
|
|
notification: Notification,
|
|
) -> Result<P, ExtractError<Notification>> {
|
|
let method = notification.method.clone();
|
|
notification.extract(&method)
|
|
}
|
|
|
|
/// The buffer a `didClose` names, read without consuming the notification —
|
|
/// the close handler runs after the flush, and dropping a pending change has
|
|
/// to happen before it. `None` for params that do not parse, which the
|
|
/// handler below ignores in exactly the same way.
|
|
fn closing_uri(notification: &Notification) -> Option<Uri> {
|
|
serde_json::from_value::<DidCloseTextDocumentParams>(notification.params.clone())
|
|
.ok()
|
|
.map(|p| p.text_document.uri)
|
|
}
|
|
|
|
#[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 {
|
|
Session::started(roots, abilities, ClientSettings::default())
|
|
}
|
|
|
|
/// A session whose client had already asked for
|
|
/// `lucisv.index.scope: "workspace"` when the startup scan ran — the
|
|
/// scope every session had before 2026-08-27.
|
|
///
|
|
/// Used by every test in this module whose subject is not the scope:
|
|
/// they want their whole fixture tree indexed from the first bar, and
|
|
/// saying so here keeps the folder scope from being a hidden variable
|
|
/// in a test about a progress report or a rename. The folder scope's
|
|
/// own behaviour is tested by the tests named in
|
|
/// `docs/features/index-scope/README.md`.
|
|
fn wide(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
|
Session::wide_with(roots, ClientAbilities { file_watching, ..Default::default() })
|
|
}
|
|
|
|
/// [`Session::wide`] against a client that said exactly `abilities`.
|
|
fn wide_with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
|
let wide = ClientSettings {
|
|
index_scope: crate::settings::IndexScope::Workspace,
|
|
..Default::default()
|
|
};
|
|
Session::started(roots, abilities, wide)
|
|
}
|
|
|
|
fn started(
|
|
roots: Vec<PathBuf>,
|
|
abilities: ClientAbilities,
|
|
settings: ClientSettings,
|
|
) -> Session {
|
|
Session::started_in(roots, abilities, settings, None)
|
|
}
|
|
|
|
/// [`Session::started`] against a client that offered a storage
|
|
/// folder — `initializationOptions.storagePath`, which is where the
|
|
/// persistent index cache goes.
|
|
fn started_in(
|
|
roots: Vec<PathBuf>,
|
|
abilities: ClientAbilities,
|
|
settings: ClientSettings,
|
|
storage: Option<PathBuf>,
|
|
) -> Session {
|
|
let (server_end, client) = Connection::memory();
|
|
// Verbose off, which is how the server ships: every assertion in
|
|
// this module counts the messages a session produces, and the
|
|
// timing lines are tested where they are observable as protocol
|
|
// traffic — `tests/e2e.rs`, against the real binary and its flag.
|
|
let server =
|
|
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
|
|
Session { server, client }
|
|
}
|
|
|
|
/// [`Session::started`] against a client that had **already sent**
|
|
/// `queued` when the server was built.
|
|
///
|
|
/// The opening burst of a real editor: `initialized` is answered by
|
|
/// `initialize_finish`, and everything the client sent behind it is
|
|
/// sitting on the transport before the startup scan takes its first
|
|
/// file. That is the case
|
|
/// `docs/features/scan-interleave/README.md` is about, and the only
|
|
/// way to reach it is to put the messages there first.
|
|
fn started_behind(
|
|
roots: Vec<PathBuf>,
|
|
abilities: ClientAbilities,
|
|
settings: ClientSettings,
|
|
on_the_wire: Vec<Message>,
|
|
queued: Vec<Message>,
|
|
) -> Session {
|
|
let (server_end, client) = Connection::memory();
|
|
// Anything that has to reach the *connection* rather than the
|
|
// queue — an `exit`, which `handle_shutdown` reads for itself —
|
|
// goes here, ahead of the forwarder ever starting.
|
|
for message in on_the_wire {
|
|
client.sender.send(message).expect("the client's wire traffic");
|
|
}
|
|
let server =
|
|
Server::started(server_end, roots, abilities, settings, None, false, queued);
|
|
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()
|
|
}
|
|
|
|
/// Every `$/progress` report since the last drain, as
|
|
/// (message, percentage) — what the bar was told to say and where to
|
|
/// stand.
|
|
fn reported(&self) -> Vec<(Option<String>, Option<u32>)> {
|
|
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::Report(report) => {
|
|
Some((report.message, report.percentage))
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Everything the server logged since the last drain, as
|
|
/// (type, message) — the client's output channel, in order.
|
|
fn logged(&self) -> Vec<(MessageType, String)> {
|
|
self.drain()
|
|
.into_iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
|
let params: LogMessageParams =
|
|
serde_json::from_value(n.params).expect("log message params");
|
|
Some((params.typ, params.message))
|
|
}
|
|
_ => 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(¶ms.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(¶ms.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() }
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// a scan that answers messages while it runs
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A tree of `files` one-package files, plus one that names the last of
|
|
/// them — enough files that a scan over it interleaves.
|
|
fn workspace_of(tag: &str, files: usize) -> Tree {
|
|
let tree = Tree::new(tag);
|
|
for n in 0..files {
|
|
tree.package(&format!("p{n:03}.sv"), &format!("p{n:03}"));
|
|
}
|
|
tree
|
|
}
|
|
|
|
/// A `workspace/symbol` request over the wire, by id.
|
|
fn symbol_request(id: i32, query: &str) -> Message {
|
|
Message::Request(Request::new(
|
|
RequestId::from(id),
|
|
WorkspaceSymbolRequest::METHOD.to_string(),
|
|
serde_json::json!({ "query": query }),
|
|
))
|
|
}
|
|
|
|
/// Where the indexing bar's `end` sits among everything the server said,
|
|
/// and where the response to `id` sits. `None` for either if it never
|
|
/// came.
|
|
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
|
let ended = messages.iter().position(|message| {
|
|
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
|
&& n.params["value"]["kind"] == "end")
|
|
});
|
|
let answered = messages.iter().position(
|
|
|message| matches!(message, Message::Response(r) if r.id == RequestId::from(id)),
|
|
);
|
|
(ended, answered)
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_the_client_had_already_sent_is_answered_during_the_startup_scan() {
|
|
// The round's point, over the real dispatch: a request sitting on the
|
|
// transport when the server is built used to wait for the whole
|
|
// startup scan, because `Server::new` ran that scan before `run()`
|
|
// took its first message. It is now answered *inside* the scan — the
|
|
// response goes out before the bar comes down, which is the only
|
|
// ordering a test can check without a stopwatch.
|
|
let tree = workspace_of("interleaveanswer", INTERLEAVE_ABOVE + 6);
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = session.drain();
|
|
let (ended, answered) = positions(&said, 7);
|
|
let answered = answered.expect("the request is answered at all");
|
|
let ended = ended.expect("the bar comes down");
|
|
assert!(
|
|
answered < ended,
|
|
"the answer must go out before the scan ends, not after it: {said:#?}"
|
|
);
|
|
// And the index really did finish, so nothing was traded for the
|
|
// latency but the completeness of that one answer.
|
|
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
|
|
}
|
|
|
|
#[test]
|
|
fn a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself() {
|
|
// The other side of `INTERLEAVE_ABOVE`. A handful of files is over in
|
|
// milliseconds, so a request that arrived with them is answered from
|
|
// the *finished* index — the complete answer, which is worth more than
|
|
// the few milliseconds an interleaved one would have saved.
|
|
let tree = workspace_of("interleaveshort", 4);
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
// Nothing is answered during construction at all: the burst is still
|
|
// on the queue for `run` to take.
|
|
let said = session.drain();
|
|
assert_eq!(positions(&said, 7).1, None, "{said:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after() {
|
|
// QA attack (`docs/features/scan-interleave/README.md`, settling
|
|
// attacks): the exact edge of `INTERLEAVE_ABOVE`. `scan_once` compares
|
|
// with `>`, not `>=`, so a scan of *exactly* the threshold must still
|
|
// run one-shot and one file more must interleave. Both sides in one
|
|
// test so a future off-by-one in that comparison shows up as a single
|
|
// failing assertion rather than two tests that each only prove half.
|
|
let at_threshold = workspace_of("interleaveboundaryat", INTERLEAVE_ABOVE);
|
|
let one_shot = Session::started_behind(
|
|
vec![at_threshold.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = one_shot.drain();
|
|
assert_eq!(
|
|
positions(&said, 7).1,
|
|
None,
|
|
"exactly INTERLEAVE_ABOVE files must run one-shot: {said:#?}"
|
|
);
|
|
|
|
let above_threshold = workspace_of("interleaveboundaryabove", INTERLEAVE_ABOVE + 1);
|
|
let interleaved = Session::started_behind(
|
|
vec![above_threshold.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![symbol_request(7, "p0")],
|
|
);
|
|
let said = interleaved.drain();
|
|
let (ended, answered) = positions(&said, 7);
|
|
assert!(
|
|
answered.expect("answered mid-scan") < ended.expect("the bar comes down"),
|
|
"one file over INTERLEAVE_ABOVE must interleave: {said:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_queued_behind_a_rescan_waits_for_that_rescan() {
|
|
// The order contract, which interleaving must not cost: a message
|
|
// that asks for a rescan is *applied* — rescan run and all — before
|
|
// anything queued behind it is answered. Here the cap is pushed down
|
|
// to nothing, which empties the index, and the request behind it must
|
|
// see the empty one rather than the half-built one it was sent into.
|
|
let tree = workspace_of("interleaveorder", INTERLEAVE_ABOVE + 6);
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(1),
|
|
)),
|
|
symbol_request(7, "p0"),
|
|
],
|
|
);
|
|
// The configuration was applied mid-scan and the rescan it asked for
|
|
// ran; the request behind it is still waiting, because it is owed that
|
|
// rescan's result.
|
|
assert!(session.server.held.len() == 1, "the request waits: {:?}", session.server.held);
|
|
assert_eq!(session.server.workspace.index().files().len(), 0, "the cap emptied the index");
|
|
let said = session.drain();
|
|
assert_eq!(positions(&said, 7).1, None, "not answered yet: {said:#?}");
|
|
|
|
// `run` answers it before it takes anything newer, and by then the
|
|
// rescan the client asked for has happened.
|
|
let held = std::mem::take(&mut session.server.held);
|
|
assert!(!session.batch(held), "the held burst is handled");
|
|
let answered = session.answers();
|
|
assert_eq!(answered.len(), 1, "{answered:#?}");
|
|
assert_eq!(
|
|
answered[0].response_result.as_ref().ok().and_then(|v| v.as_array()).map(Vec::len),
|
|
Some(0),
|
|
"answered from the index the push asked for, not the one it was sent into"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_held_request_keeps_its_place_and_takes_its_cancel_with_it() {
|
|
// Two corners of holding, in one experiment. The burst carries a
|
|
// cancel for the request it also carries, and the scan the burst's
|
|
// settings push asks for holds a *newer* request of its own along the
|
|
// way. What comes out has to be: the burst's own request first (it
|
|
// arrived first), the newer one behind it, and the cancel still in
|
|
// front of what it cancels — a cancel dropped by the wait would turn
|
|
// into a computed answer the client has stopped listening for.
|
|
let tree = workspace_of("interleaveheldorder", INTERLEAVE_ABOVE + 6);
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(1),
|
|
)),
|
|
Message::Notification(Notification::new(
|
|
Cancel::METHOD.to_string(),
|
|
serde_json::json!({ "id": 7 }),
|
|
)),
|
|
symbol_request(7, "p0"),
|
|
symbol_request(8, "p0"),
|
|
],
|
|
);
|
|
let held: Vec<String> = session
|
|
.server
|
|
.held
|
|
.iter()
|
|
.map(|message| match message {
|
|
Message::Request(request) => format!("req {}", request.id),
|
|
Message::Notification(n) => format!("notif {}", n.method),
|
|
Message::Response(r) => format!("resp {}", r.id),
|
|
})
|
|
.collect();
|
|
assert_eq!(held, ["notif $/cancelRequest", "req 7", "req 8"], "{held:?}");
|
|
|
|
let batch = std::mem::take(&mut session.server.held);
|
|
assert!(!session.batch(batch), "the held burst is handled");
|
|
let answered = session.answers();
|
|
assert_eq!(answered.len(), 2, "{answered:#?}");
|
|
assert_eq!(answered[0].id, RequestId::from(7));
|
|
assert!(
|
|
answered[0]
|
|
.response_result
|
|
.as_ref()
|
|
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
|
|
"the cancel survived the wait: {:#?}",
|
|
answered[0]
|
|
);
|
|
assert_eq!(answered[1].id, RequestId::from(8), "and the newer one is behind it");
|
|
assert!(
|
|
answered[1].response_result.is_ok(),
|
|
"which is answered normally: {:#?}",
|
|
answered[1]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan() {
|
|
// Three settings pushes land inside one startup scan, each of which
|
|
// would rebuild the index on its own. They cost one more scan between
|
|
// them, not three, and no scan runs inside another: two bars, two
|
|
// tokens, in order.
|
|
let tree = workspace_of("interleavecoalesce", INTERLEAVE_ABOVE + 6);
|
|
let cap = |bytes: u64| {
|
|
Message::Notification(Notification::new(
|
|
DidChangeConfiguration::METHOD.to_string(),
|
|
capping(bytes),
|
|
))
|
|
};
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![cap(1), cap(2), cap(3)],
|
|
);
|
|
assert!(!session.server.scanning, "no scan is left running");
|
|
assert!(!session.server.rescan_wanted, "and none is left owed");
|
|
let bars: Vec<(&str, String)> = session
|
|
.drain()
|
|
.into_iter()
|
|
.filter_map(progress_step)
|
|
.filter(|(step, _)| *step != "report")
|
|
.collect();
|
|
assert_eq!(
|
|
bars,
|
|
vec![
|
|
("create", "lucisv-index-0".to_string()),
|
|
("begin", "lucisv-index-0".to_string()),
|
|
("end", "lucisv-index-0".to_string()),
|
|
("create", "lucisv-index-1".to_string()),
|
|
("begin", "lucisv-index-1".to_string()),
|
|
("end", "lucisv-index-1".to_string()),
|
|
],
|
|
"one startup scan and exactly one coalesced rescan behind it"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands() {
|
|
// A scan is interruptible now that it takes messages, and `shutdown`
|
|
// is what interrupts it: the bar never comes down, nothing is
|
|
// published after it, and `run` returns without taking another
|
|
// message. What the scan had already parsed is in the persistent
|
|
// store — it is written through per file — so the next session
|
|
// resumes from it exactly as it does after any other half-done scan.
|
|
let tree = workspace_of("interleaveshutdown", INTERLEAVE_ABOVE + 6);
|
|
let shutdown = || {
|
|
Message::Request(Request::new(
|
|
RequestId::from(9),
|
|
Shutdown::METHOD.to_string(),
|
|
Value::Null,
|
|
))
|
|
};
|
|
let mut session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide_ish(),
|
|
// On the connection as well as on the queue, and in this order:
|
|
// the queued copy is what the scan's first drain is *certain* to
|
|
// see, and the copy the forwarder carries is what stops it reading
|
|
// — so the `exit` behind it is still there for `handle_shutdown`,
|
|
// which reads the connection itself. Whichever of the two the
|
|
// handshake ends up consuming, the scan stops here.
|
|
vec![shutdown(), Message::Notification(Notification::new("exit".into(), Value::Null))],
|
|
vec![shutdown()],
|
|
);
|
|
assert!(session.server.stopped, "the scan saw the shutdown");
|
|
assert_eq!(session.ended(), Vec::<Option<String>>::new(), "the bar never came down");
|
|
assert!(
|
|
session.server.workspace.index().files().len() < INTERLEAVE_ABOVE + 6,
|
|
"the scan stopped where it stood rather than running to the end"
|
|
);
|
|
session.server.run().expect("run returns at once");
|
|
}
|
|
|
|
#[test]
|
|
fn a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once() {
|
|
// QA attack (`docs/features/scan-interleave/README.md`,
|
|
// progress/log-continuity): before this round no buffer could be
|
|
// *open* while `Server::new` was still running, so `Server::started`
|
|
// never had to pay the one-time republish-and-refresh `reindex` has
|
|
// always owed at the end of a rescan. A `didOpen` answered mid-scan
|
|
// now creates exactly that buffer, and the work log says
|
|
// `Server::started` pays the debt at the end of construction.
|
|
//
|
|
// Two publishes for the opened file are both correct, not a
|
|
// duplicate: `didOpen`'s own handler has always published against
|
|
// whatever index exists the moment a file opens (unrelated to this
|
|
// round), which here is the half-built one — so the debt payment
|
|
// after the bar comes down is what gives the client a diagnostics set
|
|
// computed against the *finished* index, and it must come after the
|
|
// `end` event, not folded into the mid-scan one.
|
|
let tree = workspace_of("interleaveopenedpublish", INTERLEAVE_ABOVE + 6);
|
|
let target = tree.path.join("p000.sv");
|
|
let opened = Message::Notification(Notification::new(
|
|
DidOpenTextDocument::METHOD.to_string(),
|
|
serde_json::json!({
|
|
"textDocument": {
|
|
"uri": path_to_uri(&target).expect("uri"),
|
|
"languageId": "systemverilog",
|
|
"version": 1,
|
|
"text": "package p000;\nendpackage\n",
|
|
}
|
|
}),
|
|
));
|
|
let abilities = ClientAbilities {
|
|
work_done_progress: true,
|
|
code_lens_refresh: true,
|
|
..Default::default()
|
|
};
|
|
let session = Session::started_behind(
|
|
vec![tree.path.clone()],
|
|
abilities,
|
|
wide_ish(),
|
|
Vec::new(),
|
|
vec![opened],
|
|
);
|
|
let said = session.drain();
|
|
let target_uri = path_to_uri(&target).expect("uri");
|
|
let ended = said
|
|
.iter()
|
|
.position(|m| {
|
|
matches!(m, Message::Notification(n) if n.method == Progress::METHOD
|
|
&& n.params["value"]["kind"] == "end")
|
|
})
|
|
.expect("the bar comes down");
|
|
let publish_positions: Vec<usize> = said
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(i, m)| match m {
|
|
Message::Notification(n)
|
|
if n.method == PublishDiagnostics::METHOD
|
|
&& serde_json::from_value::<PublishDiagnosticsParams>(n.params.clone())
|
|
.is_ok_and(|p| p.uri == target_uri) =>
|
|
{
|
|
Some(i)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
publish_positions.len(),
|
|
2,
|
|
"one publish from didOpen's own handler, one from the debt Server::started pays: \
|
|
{said:#?}"
|
|
);
|
|
assert!(
|
|
publish_positions[0] < ended,
|
|
"the first publish is didOpen's own, against the half-built index: {said:#?}"
|
|
);
|
|
assert!(
|
|
publish_positions[1] > ended,
|
|
"the second is the debt payment, against the finished index: {said:#?}"
|
|
);
|
|
let refreshes = said
|
|
.iter()
|
|
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
|
.count();
|
|
assert_eq!(refreshes, 1, "exactly one lens refresh, not one per drain: {said:#?}");
|
|
}
|
|
|
|
/// Settings a test uses when its subject is not the scope, spelled once.
|
|
fn wide_ish() -> ClientSettings {
|
|
ClientSettings { index_scope: crate::settings::IndexScope::Workspace, ..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::wide_with(vec![tree.path.clone()], watching_progress());
|
|
// One `report` because the tree holds one file: the counting reports
|
|
// this round added ride the same path the begin/end pair does.
|
|
assert_eq!(
|
|
session.progress(),
|
|
vec![
|
|
("create", "lucisv-index-0".to_string()),
|
|
("begin", "lucisv-index-0".to_string()),
|
|
("report", "lucisv-index-0".to_string()),
|
|
("end", "lucisv-index-0".to_string()),
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_whole_rescan_puts_a_bar_up_and_takes_it_down_again() {
|
|
// Superseded this round (incremental-index, 2026-08-27):
|
|
// `a_save_puts_a_bar_up_and_takes_it_down_again` pinned the bar on a
|
|
// save, and a save of a file the index already holds is now one parse
|
|
// on the incremental path — see
|
|
// `a_one_file_save_costs_no_bar_and_no_log_line` below. The bar's own
|
|
// rule is unchanged and is pinned here on a trigger that really does
|
|
// rescan: two files changing at once.
|
|
let tree = Tree::new("progresssave");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/b.sv", "b");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
|
let _ = session.drain();
|
|
|
|
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
|
// One create, one begin, one report per file, one end — the rescan's
|
|
// own token, not the startup one.
|
|
assert_eq!(
|
|
session.progress(),
|
|
vec![
|
|
("create", "lucisv-index-1".to_string()),
|
|
("begin", "lucisv-index-1".to_string()),
|
|
("report", "lucisv-index-1".to_string()),
|
|
("report", "lucisv-index-1".to_string()),
|
|
("end", "lucisv-index-1".to_string()),
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_fast_path_is_taken_for_one_held_file_and_for_nothing_else() {
|
|
// The trigger table, all four rows in one place. The bar is the tell:
|
|
// a whole rescan puts one up, the incremental path never does.
|
|
let tree = Tree::new("fastpathtable");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/b.sv", "b");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let uri = session
|
|
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
let _ = session.drain();
|
|
|
|
// 1. A save naming one file the index holds — incremental.
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
assert!(session.progress().is_empty(), "one held file on a save is incremental");
|
|
|
|
// 2. One watched file — incremental too, same rule.
|
|
session.watched(&[tree.path.join("rtl/a.sv")]);
|
|
assert!(session.progress().is_empty(), "and one watched file is the same case");
|
|
|
|
// 3. Two files in one watcher event — the whole rescan.
|
|
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
|
assert!(!session.progress().is_empty(), "two files is a rescan");
|
|
|
|
// 4. A settings change that moves which files exist — the whole
|
|
// rescan, whatever it names.
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "exclude": ["rtl/b.sv"], "index": { "scope": "workspace" } } } }),
|
|
);
|
|
assert!(!session.progress().is_empty(), "a settings change is a rescan");
|
|
|
|
// 5. A save naming a file the index does not hold — the whole rescan,
|
|
// which is how a new file gets in at all.
|
|
let fresh = tree.path.join("rtl/c.sv");
|
|
tree.package("rtl/c.sv", "c");
|
|
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
|
);
|
|
assert!(!session.progress().is_empty(), "a file the index does not hold is a rescan");
|
|
assert_eq!(indexed(&session, "c"), 1, "and the new file is in the index after it");
|
|
}
|
|
|
|
/// QA (incremental-index, 2026-08-27): the fast-path discipline under a
|
|
/// burst. `process_batch` handles one message at a time
|
|
/// (`for message in batch`), so two `didSave`s that arrive in the same
|
|
/// burst are not coalesced into one rescan — each is its own notification,
|
|
/// each independently names one held file, and each takes the incremental
|
|
/// path on its own. Not a rebuild, and not a dropped update either.
|
|
#[test]
|
|
fn two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates() {
|
|
let tree = Tree::new("batchtwosaves");
|
|
tree.write("a.sv", "module a;\nendmodule\n");
|
|
tree.write("sub.sv", "module sub;\nendmodule\n");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let uri_a = session.open(&tree.path.join("a.sv"), "module a;\nendmodule\n");
|
|
let uri_sub = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
|
let _ = session.drain();
|
|
let before = session.server.generation;
|
|
|
|
let a_with_sub = "module a;\n sub u1 ();\nendmodule\n";
|
|
let sub_v2 = "module sub;\n logic marker;\nendmodule\n";
|
|
let save = |uri: &Uri, text: &str| {
|
|
Message::Notification(Notification::new(
|
|
DidSaveTextDocument::METHOD.to_string(),
|
|
serde_json::json!({ "textDocument": { "uri": uri }, "text": text }),
|
|
))
|
|
};
|
|
session.batch(vec![save(&uri_a, a_with_sub), save(&uri_sub, sub_v2)]);
|
|
|
|
assert!(session.progress().is_empty(), "neither save alone is a whole rescan");
|
|
// Each save bumps the generation twice — once in `set_document` for
|
|
// the buffer's own new text (every text change does that, save or
|
|
// not), once in `reindex_one` for the fast-path update — so two saves
|
|
// is four, not two and not one shared bump for the whole batch.
|
|
assert_eq!(
|
|
session.server.generation,
|
|
before + 4,
|
|
"two independent fast-path updates, not one bump shared by the batch"
|
|
);
|
|
assert_eq!(
|
|
session.server.workspace.index().instantiations_of("sub").len(),
|
|
1,
|
|
"a.sv's edit reached the index"
|
|
);
|
|
assert_eq!(
|
|
session.server.workspace.candidates().words("marker").len(),
|
|
1,
|
|
"sub.sv's own edit reached the index too, not just a.sv's"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses() {
|
|
// Everything the fast path keeps: a pulling client's cached
|
|
// diagnostics are stale from here, and every lens a client is holding
|
|
// may now read a different count.
|
|
let tree = lens_tree("fastpathafter");
|
|
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("top.sv"),
|
|
"module top;\n sub u_a ();\n sub u_b ();\nendmodule\n",
|
|
);
|
|
let _ = session.drain();
|
|
let before = session.server.generation;
|
|
|
|
let one_site = "module top;\n sub u_a ();\nendmodule\n";
|
|
std::fs::write(tree.path.join("top.sv"), one_site).expect("write");
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri }, "text": one_site }),
|
|
);
|
|
assert!(session.server.generation > before, "the generation moved");
|
|
let refreshes = session
|
|
.sent()
|
|
.iter()
|
|
.filter(|request| request.method == CodeLensRefresh::METHOD)
|
|
.count();
|
|
assert_eq!(refreshes, 1, "one refresh, as a whole rescan sends");
|
|
}
|
|
|
|
#[test]
|
|
fn a_one_file_save_answers_from_the_file_it_saved() {
|
|
// The point of the whole path: one file's edit really does reach the
|
|
// index, and the rest of the workspace really is left alone.
|
|
let tree = lens_tree("fastpathanswer");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let two_sites = "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n";
|
|
let uri = session.open(&tree.path.join("top.sv"), two_sites);
|
|
let _ = session.drain();
|
|
assert_eq!(
|
|
session.server.workspace.index().instantiations_of("sub").len(),
|
|
2,
|
|
"premise: top.sv instantiates `sub` twice"
|
|
);
|
|
|
|
let emptied = "module top;\nendmodule\n";
|
|
std::fs::write(tree.path.join("top.sv"), emptied).expect("write");
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri }, "text": emptied }),
|
|
);
|
|
assert!(
|
|
session.server.workspace.index().instantiations_of("sub").is_empty(),
|
|
"the saved file's edges are gone"
|
|
);
|
|
assert_eq!(
|
|
session.server.workspace.index().units("sub").len(),
|
|
1,
|
|
"and sub.sv, which nothing named, is untouched"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_one_file_save_costs_no_bar_and_no_log_line() {
|
|
// The fast path's whole visible protocol delta: a save that names one
|
|
// file the index already holds does its work inside a frame, so there
|
|
// is no bar to put up and no scan to narrate. What it does still do —
|
|
// the generation bump and the code-lens refresh — is pinned by
|
|
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
|
let tree = Tree::new("progressonefile");
|
|
tree.package("rtl/a.sv", "a");
|
|
let abilities = ClientAbilities { work_done_progress: true, ..Default::default() };
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
|
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 } }),
|
|
);
|
|
assert!(session.progress().is_empty(), "one file is not a scan to report");
|
|
assert!(session.logged().is_empty(), "and not a scan to narrate either");
|
|
}
|
|
|
|
#[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::wide_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::wide_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_counts_the_files_as_it_goes() {
|
|
// The whole of feature 2: how many of how many, which file, and a
|
|
// percentage that was measured rather than guessed.
|
|
let tree = Tree::new("progressreports");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/b.sv", "b");
|
|
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
assert_eq!(
|
|
session.reported(),
|
|
vec![
|
|
(Some("1/2 a.sv".to_string()), Some(50)),
|
|
(Some("2/2 b.sv".to_string()), Some(100)),
|
|
],
|
|
"counts ascending, the file named, the percentage monotonic and ending at 100"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_reports_thin_out_when_the_workspace_is_huge() {
|
|
// A report per file is right for hundreds and wrong for tens of
|
|
// thousands. Past `MAX_REPORTS` files they thin out — but the last
|
|
// file always reports, so the bar always finishes where the work did.
|
|
let tree = Tree::new("progressflood");
|
|
let files = MAX_REPORTS + 100;
|
|
for i in 0..files {
|
|
tree.package(&format!("f{i:05}.sv",), &format!("p{i}"));
|
|
}
|
|
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let reports = session.reported();
|
|
assert!(reports.len() <= MAX_REPORTS, "{} reports for {files} files", reports.len());
|
|
assert!(reports.len() > MAX_REPORTS / 2, "but not silence: {}", reports.len());
|
|
|
|
let percentages: Vec<u32> = reports.iter().filter_map(|(_, p)| *p).collect();
|
|
assert_eq!(percentages.len(), reports.len(), "every report carries one");
|
|
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "monotonic: {percentages:?}");
|
|
assert_eq!(percentages.last(), Some(&100), "and it ends at 100");
|
|
let last = reports.last().expect("a report").0.clone().expect("a message");
|
|
assert!(last.starts_with(&format!("{files}/{files} ")), "the last file reports: {last}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_report_schedule_never_floods_and_never_stops_short() {
|
|
// The rule itself, across both regimes and their boundary — cheaper to
|
|
// check exhaustively here than to build 40,000 files.
|
|
for total in [1, 2, 999, 1000, 1001, 1999, 2000, 12_345, 40_000] {
|
|
let reporting: Vec<usize> = (0..total).filter(|d| reports(*d, total)).collect();
|
|
assert!(!reporting.is_empty(), "{total} files must report something");
|
|
assert!(reporting.len() <= MAX_REPORTS, "{total} files: {} reports", reporting.len());
|
|
assert_eq!(
|
|
reporting.last(),
|
|
Some(&(total - 1)),
|
|
"{total} files: the last file must report"
|
|
);
|
|
assert!(reporting.windows(2).all(|w| w[0] < w[1]), "{total}: strictly ascending");
|
|
// The percentage a client sees only ever counts up, and lands on
|
|
// 100 exactly once, at the end.
|
|
let percentages: Vec<usize> = reporting.iter().map(|d| (d + 1) * 100 / total).collect();
|
|
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "{total}: monotonic");
|
|
assert_eq!(percentages.last(), Some(&100), "{total}: ends at 100");
|
|
}
|
|
}
|
|
|
|
#[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");
|
|
tree.package("rtl/b.sv", "b");
|
|
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
|
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
|
let _ = session.drain();
|
|
|
|
// Two files at once, so this is a whole rescan and there is a bar to
|
|
// order the republish against (incremental-index, 2026-08-27).
|
|
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
|
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", "report", "report", "end", "publish"]);
|
|
}
|
|
|
|
/// A tree with one file the default cap would keep and one it would not.
|
|
/// The big one is padded with a trailing comment, so what makes it big is
|
|
/// not what makes it a package.
|
|
fn oversized_tree(name: &str) -> Tree {
|
|
let tree = Tree::new(name);
|
|
tree.package("rtl/keep.sv", "keep_pkg");
|
|
let head = "package netlist_pkg;\n localparam K = 1;\nendpackage\n// ";
|
|
let mut text = String::from(head);
|
|
while text.len() < 4096 {
|
|
text.push('x');
|
|
}
|
|
text.push('\n');
|
|
tree.write("rtl/netlist.sv", &text);
|
|
tree
|
|
}
|
|
|
|
/// The `didChangeConfiguration` push that sets the index size cap.
|
|
///
|
|
/// It carries `scope: "workspace"` because a push replaces *every*
|
|
/// setting: a cap pushed on its own would take the index back to the
|
|
/// folder scope in the same breath, which is not what a test about the cap
|
|
/// is asking. Same reason `state.rs`'s `wide()` exists.
|
|
fn capping(bytes: u64) -> serde_json::Value {
|
|
serde_json::json!({
|
|
"settings": {
|
|
"lucisv": { "index": { "maxFileSize": bytes, "scope": "workspace" } }
|
|
}
|
|
})
|
|
}
|
|
|
|
/// The `message` of every `$/progress` end in one drained batch, and every
|
|
/// `window/logMessage` line in it. Read off one drain rather than through
|
|
/// `Session::ended`/`logged`, because a test that wants both cannot drain
|
|
/// twice.
|
|
fn ends(messages: &[Message]) -> Vec<Option<String>> {
|
|
messages
|
|
.iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(n) if n.method == Progress::METHOD => {
|
|
let params: ProgressParams =
|
|
serde_json::from_value(n.params.clone()).expect("progress params");
|
|
let ProgressParamsValue::WorkDone(work) = params.value;
|
|
match work {
|
|
WorkDoneProgress::End(end) => Some(end.message),
|
|
_ => None,
|
|
}
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn log_lines(messages: &[Message]) -> Vec<String> {
|
|
messages
|
|
.iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
|
let params: LogMessageParams =
|
|
serde_json::from_value(n.params.clone()).expect("log params");
|
|
Some(params.message)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn a_second_session_over_the_same_storage_folder_resumes_from_the_cache() {
|
|
// The owner's case, end to end through the real dispatch: a session
|
|
// indexes a tree, the editor goes away, and the next session over the
|
|
// same storage folder gets the same index without parsing anything.
|
|
let tree = Tree::new("resume");
|
|
tree.package("rtl/a.sv", "a_pkg");
|
|
tree.package("rtl/b.sv", "b_pkg");
|
|
let storage = Tree::new("resume_storage");
|
|
let wide = ClientSettings {
|
|
index_scope: crate::settings::IndexScope::Workspace,
|
|
..Default::default()
|
|
};
|
|
|
|
let mut first = Session::started_in(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide.clone(),
|
|
Some(storage.path.clone()),
|
|
);
|
|
let cold = first.drain();
|
|
assert_eq!(ends(&cold), vec![Some("2 files indexed".to_string())], "a cold session");
|
|
assert_eq!(
|
|
log_lines(&cold).iter().filter(|line| line.starts_with("indexing: ")).count(),
|
|
2,
|
|
"both files were parsed: {:?}",
|
|
log_lines(&cold)
|
|
);
|
|
let before = first.server.workspace.index().fingerprint();
|
|
let answer =
|
|
first.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"}));
|
|
drop(first);
|
|
|
|
let mut second = Session::started_in(
|
|
vec![tree.path.clone()],
|
|
watching_progress(),
|
|
wide,
|
|
Some(storage.path.clone()),
|
|
);
|
|
let warm = second.drain();
|
|
assert_eq!(
|
|
ends(&warm),
|
|
vec![Some("2 files indexed, 2 from cache".to_string())],
|
|
"the bar says where the files came from"
|
|
);
|
|
let lines = log_lines(&warm);
|
|
assert_eq!(
|
|
lines.iter().filter(|line| line.starts_with("cached: ")).count(),
|
|
2,
|
|
"and so does the log, file by file: {lines:?}"
|
|
);
|
|
assert!(
|
|
!lines.iter().any(|line| line.starts_with("indexing: ")),
|
|
"nothing was parsed: {lines:?}"
|
|
);
|
|
assert_eq!(
|
|
second.server.workspace.index().fingerprint(),
|
|
before,
|
|
"the same index, byte for byte"
|
|
);
|
|
assert_eq!(
|
|
second.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})),
|
|
answer,
|
|
"and the same answers over the wire"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory() {
|
|
// What every client but ours does, and what `smoke.js` does: no
|
|
// `storagePath`, no workspace root to key an OS-directory store on,
|
|
// so nothing is persisted and nothing is read — today's behaviour,
|
|
// unchanged.
|
|
let tree = Tree::new("nostorage");
|
|
tree.package("rtl/a.sv", "a_pkg");
|
|
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let first = session.drain();
|
|
assert_eq!(ends(&first), vec![Some("1 file indexed".to_string())]);
|
|
assert!(
|
|
log_lines(&first).iter().all(|line| !line.starts_with("cached: ")),
|
|
"nothing can come from a cache that was never written: {:?}",
|
|
log_lines(&first)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_end_message_names_what_the_cap_skipped() {
|
|
// The count survives even when the per-file log is off, because it is
|
|
// the only place a user who turned the log off would hear that part of
|
|
// their workspace is not indexed.
|
|
let tree = oversized_tree("capend");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())], "premise: no cap");
|
|
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({
|
|
"settings": {
|
|
"lucisv": {
|
|
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
|
}
|
|
}
|
|
}),
|
|
);
|
|
assert_eq!(
|
|
session.ended(),
|
|
vec![Some("1 file indexed, 1 skipped".to_string())],
|
|
"the cap change rescanned, and the end message counts the skip"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not() {
|
|
let tree = oversized_tree("capserver");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
|
assert_eq!(indexed(&session, "netlist_pkg"), 0, "the big file is not indexed");
|
|
assert_eq!(indexed(&session, "keep_pkg"), 1, "and the small one still is");
|
|
|
|
// Opening it is the user saying they want it: the buffer is indexed
|
|
// whatever the cap says.
|
|
let text = std::fs::read_to_string(tree.path.join("rtl/netlist.sv")).expect("read");
|
|
session.open(&tree.path.join("rtl/netlist.sv"), &text);
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": path_to_uri(&tree.path.join("rtl/netlist.sv")).expect("uri") }
|
|
}),
|
|
);
|
|
assert_eq!(indexed(&session, "netlist_pkg"), 1, "an open buffer is exempt");
|
|
}
|
|
|
|
#[test]
|
|
fn every_indexed_file_is_named_in_the_log_and_so_is_every_skip() {
|
|
let tree = oversized_tree("caplog");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let _ = session.drain();
|
|
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
|
|
|
let logged = session.logged();
|
|
assert!(
|
|
logged.iter().all(|(typ, _)| *typ == MessageType::LOG),
|
|
"the file log is LOG, never a popup-worthy level: {logged:?}"
|
|
);
|
|
let lines: Vec<&String> = logged.iter().map(|(_, line)| line).collect();
|
|
assert_eq!(
|
|
lines.iter().filter(|l| l.starts_with("indexing: ")).count(),
|
|
1,
|
|
"one line per file parsed: {lines:?}"
|
|
);
|
|
assert!(
|
|
lines.iter().any(|l| l.ends_with("rtl/keep.sv") && l.starts_with("indexing: ")),
|
|
"named by full path: {lines:?}"
|
|
);
|
|
let skip = lines
|
|
.iter()
|
|
.find(|l| l.starts_with("skipped ("))
|
|
.unwrap_or_else(|| panic!("a skip line: {lines:?}"));
|
|
assert!(skip.contains("1.0 KiB cap"), "the cap it was measured against: {skip}");
|
|
assert!(skip.contains("4.0 KiB >"), "and the size that broke it: {skip}");
|
|
assert!(skip.ends_with("rtl/netlist.sv"), "and the file it kept out: {skip}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_file_log_goes_quiet_when_the_setting_is_off() {
|
|
let tree = oversized_tree("caplogoff");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let _ = session.drain();
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({
|
|
"settings": {
|
|
"lucisv": {
|
|
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
|
}
|
|
}
|
|
}),
|
|
);
|
|
let logged = session.logged();
|
|
assert!(logged.is_empty(), "not one line, skips included: {logged:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_file_log_does_not_wait_for_a_progress_bar() {
|
|
// The two features are independent: the log is a `window/logMessage`,
|
|
// which every client gets, and the bar is gated on a capability.
|
|
let tree = Tree::new("caplognobar");
|
|
tree.package("rtl/a.sv", "a");
|
|
let session = Session::wide(vec![tree.path.clone()], false);
|
|
// One drain, both questions: `Session::drain` consumes.
|
|
let messages = session.drain();
|
|
assert!(
|
|
messages.iter().cloned().filter_map(progress_step).next().is_none(),
|
|
"premise: no bar for this client"
|
|
);
|
|
let logged: Vec<String> = messages
|
|
.into_iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
|
let params: LogMessageParams =
|
|
serde_json::from_value(n.params).expect("log message params");
|
|
Some(params.message)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(logged.len(), 1, "{logged:?}");
|
|
assert!(logged[0].starts_with("indexing: "), "{logged:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_new_cap_rescans_and_a_new_log_setting_does_not() {
|
|
// `lucisv.index.maxFileSize` changes which files exist, so it costs a
|
|
// rescan exactly as `exclude` does; `logFiles` changes nothing but the
|
|
// narration of the next one.
|
|
let tree = Tree::new("caprescan");
|
|
tree.package("rtl/a.sv", "a");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
let _ = session.drain();
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
|
assert_eq!(session.progress().len(), 4, "create, begin, one report, end");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
|
assert!(session.progress().is_empty(), "the same cap again buys nothing");
|
|
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({
|
|
"settings": {
|
|
"lucisv": {
|
|
"index": { "maxFileSize": 4096, "logFiles": false, "scope": "workspace" }
|
|
}
|
|
}
|
|
}),
|
|
);
|
|
assert!(session.progress().is_empty(), "and neither does turning the log off");
|
|
}
|
|
|
|
#[test]
|
|
fn a_new_index_scope_or_depth_rescans_through_the_real_dispatch() {
|
|
// The other two settings that change which files exist. Driven through
|
|
// `didChangeConfiguration` rather than `set_client_settings`, because
|
|
// the parser, the change test and the rescan are three separate places
|
|
// a scope setting could be dropped.
|
|
let tree = Tree::new("scoperescan");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("include/defs.sv", "defs_pkg");
|
|
let scoped = |scope: &str, depth: u32| {
|
|
serde_json::json!({
|
|
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
|
|
})
|
|
};
|
|
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
|
// The shipped depth is 2 since 2026-08-28, which already reaches the
|
|
// sibling folder — so the narrow premise this test raises the depth
|
|
// *from* is asked for out loud.
|
|
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 0));
|
|
let uri = session.open(
|
|
&tree.path.join("rtl/a.sv"),
|
|
"package a;\n localparam K = 1;\n\
|
|
endpackage\n",
|
|
);
|
|
let _ = (uri, session.drain());
|
|
assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
|
assert_eq!(session.progress().len(), 5, "create, begin, two reports, end");
|
|
assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
|
assert!(session.progress().is_empty(), "the same depth again buys nothing");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, scoped("workspace", 1));
|
|
assert!(!session.progress().is_empty(), "and a new scope does");
|
|
assert_eq!(indexed(&session, "defs_pkg"), 1, "the whole workspace, now");
|
|
}
|
|
|
|
#[test]
|
|
fn the_bar_names_the_open_file_before_the_rest_of_the_scope() {
|
|
// The progress half of the open-first ordering: the file the user is
|
|
// waiting on is `1/N`, not wherever its name happens to sort. The
|
|
// index it produces is identical either way — that is pinned in
|
|
// `state.rs` and in `vlog_semantic`, because it is a property of the
|
|
// builder rather than of the bar.
|
|
let tree = Tree::new("scopeorderbar");
|
|
tree.package("rtl/a_first.sv", "a_first");
|
|
tree.package("rtl/m_open.sv", "m_open");
|
|
tree.package("rtl/z_last.sv", "z_last");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
|
|
let _ = session.drain();
|
|
|
|
// A whole rescan, since that is what has a bar to name files on: a
|
|
// save of one held file takes the incremental path now
|
|
// (incremental-index, 2026-08-27).
|
|
session.watched(&[tree.path.join("rtl/a_first.sv"), tree.path.join("rtl/z_last.sv")]);
|
|
let named: Vec<Option<String>> =
|
|
session.reported().into_iter().map(|(message, _)| message).collect();
|
|
assert_eq!(
|
|
named,
|
|
vec![
|
|
Some("1/3 m_open.sv".to_string()),
|
|
Some("2/3 a_first.sv".to_string()),
|
|
Some("3/3 z_last.sv".to_string()),
|
|
],
|
|
"the open buffer first, then path order"
|
|
);
|
|
}
|
|
|
|
#[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 the *whole* `reindex`: a save of a
|
|
// file the index does not hold, a watcher event naming more than one
|
|
// file, and a changed scope. One begin/end pair each, and no token
|
|
// twice. (Superseded this round: the first two used to be a plain save
|
|
// and a one-file watcher event, both of which take the incremental
|
|
// path now and put no bar up at all.)
|
|
let tree = Tree::new("progresspaths");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/b.sv", "b");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
|
let _ = session.drain();
|
|
|
|
let fresh = tree.path.join("rtl/c.sv");
|
|
tree.package("rtl/c.sv", "c");
|
|
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
|
);
|
|
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.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");
|
|
// Superseded this round: there *are* reports now, and every one of
|
|
// them belongs to a bar that is up. What must never happen is a
|
|
// report on a token whose `end` has already gone out.
|
|
let mut open: Option<&String> = None;
|
|
for (step, token) in &steps {
|
|
match *step {
|
|
"begin" => open = Some(token),
|
|
"report" => {
|
|
assert_eq!(open, Some(token), "a report outside its own bar: {steps:#?}")
|
|
}
|
|
"end" => open = None,
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[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 *whole* rescan while the edit is outstanding, so a progress
|
|
// create sits between the push and its answer. Two files, because one
|
|
// takes the incremental path and puts no bar up
|
|
// (incremental-index, 2026-08-27).
|
|
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.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");
|
|
|
|
// Two files, so the rescan is the whole one that puts a bar up.
|
|
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.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::wide_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", "report", "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::wide(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_hierarchy_view_gets_a_snapshot_and_one_notification_per_completed_index() {
|
|
let tree = Tree::new("hierarchyviewrefresh");
|
|
tree.write("sub.sv", "module sub; endmodule\n");
|
|
tree.write("top.sv", "module top; sub u (); endmodule\n");
|
|
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
|
|
|
let started: Vec<Value> = session
|
|
.drain()
|
|
.into_iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(notification)
|
|
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
|
{
|
|
Some(notification.params)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(started, [serde_json::json!({ "revision": 1 })]);
|
|
|
|
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
|
assert_eq!(snapshot["revision"], 1);
|
|
assert_eq!(snapshot["complete"], true);
|
|
assert_eq!(snapshot["modules"].as_array().expect("modules").len(), 2);
|
|
|
|
tree.write("top.sv", "module top; sub renamed (); endmodule\n");
|
|
session.watched(&[tree.path.join("top.sv")]);
|
|
let changed: Vec<Value> = session
|
|
.drain()
|
|
.into_iter()
|
|
.filter_map(|message| match message {
|
|
Message::Notification(notification)
|
|
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
|
{
|
|
Some(notification.params)
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(changed, [serde_json::json!({ "revision": 2 })]);
|
|
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
|
assert_eq!(snapshot["revision"], 2);
|
|
let top = snapshot["modules"]
|
|
.as_array()
|
|
.expect("modules")
|
|
.iter()
|
|
.find(|module| module["moduleName"] == "top")
|
|
.expect("top");
|
|
assert_eq!(top["instances"][0]["instanceName"], "renamed");
|
|
}
|
|
|
|
/// `complete` says "this is the whole workspace", and the window it has to
|
|
/// be honest about is the one between a finished scan and a rescan already
|
|
/// asked for — where `scanning` alone is false over an index that is about
|
|
/// to be rebuilt. Two answers, both pinned here: the flag itself is false,
|
|
/// and the request does not reach it at all, because `must_wait` sets a
|
|
/// request owed a rescan aside instead of answering it.
|
|
#[test]
|
|
fn a_snapshot_is_never_answered_complete_while_a_rescan_is_owed() {
|
|
let tree = Tree::new("hierarchycomplete");
|
|
tree.write("top.sv", "module top; endmodule\n");
|
|
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
|
session.drain();
|
|
assert!(session.server.index_is_complete(), "settled: nothing is owed");
|
|
assert_eq!(
|
|
session.result(design_hierarchy::METHOD, serde_json::json!({}))["complete"],
|
|
true
|
|
);
|
|
|
|
session.server.rescan_wanted = true;
|
|
assert!(!session.server.scanning, "premise: no scan is running this instant");
|
|
assert!(!session.server.index_is_complete(), "but one is owed, so nothing is complete");
|
|
|
|
let request = Message::Request(Request::new(
|
|
RequestId::from(99),
|
|
design_hierarchy::METHOD.to_string(),
|
|
serde_json::json!({}),
|
|
));
|
|
assert!(!session.batch(vec![request]));
|
|
assert_eq!(session.server.held.len(), 1, "the snapshot waits for the rescan");
|
|
assert!(session.answers().is_empty(), "nothing was answered off the stale index");
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_without_the_hierarchy_view_gets_no_custom_notifications() {
|
|
let tree = Tree::new("nohierarchyviewrefresh");
|
|
tree.write("top.sv", "module top; endmodule\n");
|
|
let session = Session::wide(vec![tree.path.clone()], false);
|
|
assert!(session.drain().into_iter().all(|message| {
|
|
!matches!(message, Message::Notification(notification)
|
|
if notification.method == design_hierarchy::CHANGED_METHOD)
|
|
}));
|
|
}
|
|
|
|
#[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);
|
|
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
|
let _ = session.drain();
|
|
// Two files at once, so this is a whole rescan and there is a bar for
|
|
// the refresh to ride after (incremental-index, 2026-08-27); the
|
|
// one-file path's own refresh is pinned in
|
|
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
|
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
|
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();
|
|
// Two files in `lens_tree`, so two reports between the begin and the
|
|
// end; the refresh is still after all of them.
|
|
assert_eq!(order, ["create", "begin", "report", "report", "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. The flush at the
|
|
/// end is the quiet-period timer firing: a test drives notifications one
|
|
/// at a time, so the burst the loop would have coalesced never forms, and
|
|
/// without this the buffer would sit dirty forever.
|
|
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,
|
|
}),
|
|
);
|
|
session.server.flush_dirty();
|
|
}
|
|
|
|
/// The text the server currently holds for a buffer — the newest applied
|
|
/// text, which while a change sits dirty is the pending one.
|
|
fn buffer(session: &Session, uri: &Uri) -> String {
|
|
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
|
|
return text.clone();
|
|
}
|
|
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 a_burst_of_changes_coalesces_into_one_reparse() {
|
|
// The change debounce's whole payoff: a burst of `didChange`
|
|
// notifications costs one reparse when the next thing that needs the
|
|
// analysis flushes them, not one per keystroke.
|
|
let tree = Tree::new("debounce");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
|
|
|
let before = session.server.generation;
|
|
session.batch(vec![
|
|
changed(&uri, 2, "module m;\n wire a;\nendmodule\n"),
|
|
changed(&uri, 3, "module m;\n wire a;\n wire b;\nendmodule\n"),
|
|
]);
|
|
// Text-current, analysis-stale: nothing has reparsed yet, and the
|
|
// newest text is already what the server holds.
|
|
assert_eq!(session.server.generation, before, "no keystroke reparses on its own");
|
|
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire b;\nendmodule\n");
|
|
|
|
// The first request after the burst is answered from one flush.
|
|
session.result(
|
|
DocumentSymbolRequest::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
assert_eq!(session.server.generation, before + 1, "one reparse for the whole burst");
|
|
assert!(session.server.dirty.is_empty(), "and nothing is left pending");
|
|
}
|
|
|
|
#[test]
|
|
fn closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone() {
|
|
// The debounce's other half: a buffer closed mid-edit is never
|
|
// analyzed. Its pending text is dropped ahead of the flush at the top
|
|
// of `notification`, so the client gets the one clearing publish and
|
|
// nothing else — while every *other* dirty buffer still flushes,
|
|
// because closing one file says nothing about the rest (QA, CD-1).
|
|
let tree = Tree::new("closedirty");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let closing = session.open(&tree.path.join("closing.sv"), "module a;\nendmodule\n");
|
|
let staying = session.open(&tree.path.join("staying.sv"), "module b;\nendmodule\n");
|
|
let _ = session.published();
|
|
|
|
// Both buffers go dirty with text that would diagnose if analyzed.
|
|
let before = session.server.generation;
|
|
for (uri, text) in [
|
|
(&closing, "module a;\n wire ;\nendmodule\n"),
|
|
(&staying, "module b;\n wire ;\nendmodule\n"),
|
|
] {
|
|
session.notify(
|
|
DidChangeTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri, "version": 2 },
|
|
"contentChanges": [{ "text": text }],
|
|
}),
|
|
);
|
|
}
|
|
assert_eq!(session.server.generation, before, "a keystroke reparses nothing on its own");
|
|
|
|
session.notify(
|
|
DidCloseTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": closing } }),
|
|
);
|
|
|
|
assert_eq!(
|
|
session.server.generation,
|
|
before + 1,
|
|
"one reparse — the buffer still open; the closing one's text went with it"
|
|
);
|
|
assert!(session.server.dirty.is_empty(), "nothing left pending");
|
|
|
|
let published = session.published();
|
|
let closed: Vec<_> = published.iter().filter(|p| p.uri == closing).collect();
|
|
assert_eq!(closed.len(), 1, "exactly one publish for the closed buffer: {published:?}");
|
|
assert!(closed[0].diagnostics.is_empty(), "and it is the clearing one: {published:?}");
|
|
let open: Vec<_> = published.iter().filter(|p| p.uri == staying).collect();
|
|
assert_eq!(open.len(), 1, "the other buffer publishes once: {published:?}");
|
|
assert!(
|
|
!open[0].diagnostics.is_empty(),
|
|
"the other buffer's pending edit was flushed as usual: {published:?}"
|
|
);
|
|
}
|
|
|
|
#[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());
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `textDocument/rangesFormatting` (LSP 3.18), through the real dispatch
|
|
// ------------------------------------------------------------------
|
|
|
|
/// One LSP range, as a client writes it.
|
|
fn json_range(sl: u32, sc: u32, el: u32, ec: u32) -> Value {
|
|
serde_json::json!({
|
|
"start": { "line": sl, "character": sc },
|
|
"end": { "line": el, "character": ec },
|
|
})
|
|
}
|
|
|
|
fn ranges_result(session: &mut Session, uri: &Uri, ranges: Vec<Value>) -> Value {
|
|
session.result(
|
|
format::RANGES_FORMATTING,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"ranges": ranges,
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
)
|
|
}
|
|
|
|
fn range_result(session: &mut Session, uri: &Uri, range: Value) -> Value {
|
|
session.result(
|
|
RangeFormatting::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"range": range,
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
)
|
|
}
|
|
|
|
/// Four items on four lines, so two ranges can straddle one they leave.
|
|
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
|
|
|
#[test]
|
|
fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
|
// The dispatch arm, end to end: a real request with a real `ranges`
|
|
// array, decoded by the hand-rolled params and answered by the real
|
|
// handler. Lines 2 and 4, leaving line 3 exactly as written.
|
|
let tree = Tree::new("rangesfmt");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
|
|
|
let edits =
|
|
ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0), json_range(3, 0, 4, 0)]);
|
|
assert_eq!(
|
|
edits[0]["newText"], "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
|
|
"{edits:#?}"
|
|
);
|
|
// Still one whole-document edit, the shape `rangeFormatting` answers.
|
|
assert_eq!(edits.as_array().map(Vec::len), Some(1));
|
|
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 0 }));
|
|
assert!(session.shown().is_empty(), "a clean config says nothing");
|
|
}
|
|
|
|
#[test]
|
|
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
|
// The two requests are the same engine, and a client must never have
|
|
// to choose between them for correctness — only for round trips.
|
|
let tree = Tree::new("rangesone");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
|
|
|
for range in [
|
|
json_range(1, 0, 2, 0),
|
|
json_range(1, 4, 1, 4),
|
|
json_range(0, 0, 99, 0),
|
|
json_range(4, 0, 4, 9),
|
|
] {
|
|
let one = range_result(&mut session, &uri, range.clone());
|
|
let many = ranges_result(&mut session, &uri, vec![range.clone()]);
|
|
assert_eq!(one, many, "{range}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_ranges_array_is_answered_with_no_edit_and_no_word() {
|
|
let tree = Tree::new("rangesempty");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
|
|
|
assert_eq!(ranges_result(&mut session, &uri, vec![]), serde_json::json!([]));
|
|
assert!(session.shown().is_empty(), "an empty ask is not a problem");
|
|
}
|
|
|
|
#[test]
|
|
fn a_ranges_request_for_a_buffer_the_server_does_not_hold_is_null() {
|
|
// What every other formatting handler answers for an unknown document.
|
|
let tree = Tree::new("rangesunknown");
|
|
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!(ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0)]), Value::Null);
|
|
}
|
|
|
|
#[test]
|
|
fn a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods() {
|
|
// No partial output (CLAUDE.md invariant #1), and the multi-range path
|
|
// reaches the *same* `edits()` — so the answer and the message must be
|
|
// equal values, not merely similar shapes.
|
|
let tree = Tree::new("rangesrefuse");
|
|
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");
|
|
let _ = session.drain();
|
|
|
|
let one = range_result(&mut session, &uri, json_range(0, 0, 1, 0));
|
|
let said_once = session.shown();
|
|
let many =
|
|
ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0), json_range(2, 0, 3, 0)]);
|
|
let said_again = session.shown();
|
|
|
|
assert_eq!(one, serde_json::json!([]), "no edit at all");
|
|
assert_eq!(one, many, "byte-identical answers");
|
|
assert_eq!(said_once.len(), 1, "{said_once:?}");
|
|
assert_eq!(said_once, said_again, "and byte-identical ERRORs: {said_again:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_broken_config_warns_once_from_the_multi_range_path_too() {
|
|
// It shares `warn_about_config` with the other explicit formatting
|
|
// requests, dedup included — this is an explicit request the user made,
|
|
// not a keystroke, so it does speak.
|
|
let tree = Tree::new("rangesconfig");
|
|
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"), FOUR_ITEMS);
|
|
let _ = session.drain();
|
|
|
|
let edits = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
|
assert_eq!(
|
|
edits[0]["newText"],
|
|
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"
|
|
);
|
|
let warned = session.shown();
|
|
assert_eq!(warned.len(), 1, "{warned:?}");
|
|
assert_eq!(warned[0].0, MessageType::WARNING);
|
|
assert!(warned[0].1.contains("unknown key `bogus`"), "{warned:?}");
|
|
// And once per buffer state, exactly as the other paths.
|
|
let _ = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
|
assert!(session.shown().is_empty(), "said once, not once per request");
|
|
}
|
|
|
|
#[test]
|
|
fn params_that_do_not_carry_ranges_are_invalid_params_and_not_a_panic() {
|
|
// The params are hand-rolled, so their refusal is ours to get right:
|
|
// a missing `ranges` is a client bug and answers an error, never a
|
|
// guess about what the client meant.
|
|
let tree = Tree::new("rangesjunk");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
|
|
|
let response = session.request(
|
|
format::RANGES_FORMATTING,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
);
|
|
let error = response.response_result.expect_err("missing `ranges` is not answerable");
|
|
assert_eq!(error.code, lsp_server::ErrorCode::InvalidParams as i32, "{error:?}");
|
|
}
|
|
|
|
#[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(¬hing["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, and reads it off
|
|
// the *connection* — so the forwarder has to have stopped first, or it
|
|
// takes the `exit` and the handshake finds nothing. It stops at the
|
|
// first `shutdown` it forwards, so one is sent through it and waited
|
|
// for: once that message is off the queue the forwarder has already
|
|
// broken out of its loop and will never read the connection again.
|
|
// (Before 2026-08-28 the forwarder did not exist until `run`, which
|
|
// this test never calls, so the `exit` simply sat there.)
|
|
session
|
|
.client
|
|
.sender
|
|
.send(Message::Request(Request::new(
|
|
RequestId::from(99),
|
|
Shutdown::METHOD.to_string(),
|
|
Value::Null,
|
|
)))
|
|
.expect("queue a shutdown for the forwarder to stop at");
|
|
session
|
|
.server
|
|
.queue
|
|
.recv_timeout(std::time::Duration::from_secs(5))
|
|
.expect("the forwarder stops at it");
|
|
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(¬ification),
|
|
"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");
|
|
|
|
// The server's own queue — the one the forwarder started at
|
|
// construction is filling — rather than a second one: two forwarders
|
|
// over one connection would each take half the messages.
|
|
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);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// file operations (`docs/features/file-operations/README.md`)
|
|
// ------------------------------------------------------------------
|
|
|
|
/// One `workspace/willRenameFiles` for `from` → `to`, driven through the
|
|
/// real dispatch.
|
|
fn will_rename(session: &mut Session, from: &Path, to: &Path) -> Value {
|
|
session.result(
|
|
WillRenameFiles::METHOD,
|
|
serde_json::json!({ "files": [{
|
|
"oldUri": path_to_uri(from).expect("uri"),
|
|
"newUri": path_to_uri(to).expect("uri"),
|
|
}] }),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn will_rename_answers_the_edit_that_keeps_an_include_resolving() {
|
|
let tree = Tree::new("willrename");
|
|
tree.write("defs.svh", "`define W 8\n");
|
|
tree.write("top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
|
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
|
|
|
let (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh"));
|
|
let answer = will_rename(&mut session, &from, &to);
|
|
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
|
let edits = &answer["changes"][uri.as_str()];
|
|
assert_eq!(edits[0]["newText"], serde_json::json!("widths.svh"), "{answer:#?}");
|
|
// The range is the path token: line 0, inside the quotes.
|
|
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 10 }));
|
|
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 0, "character": 18 }));
|
|
assert!(session.shown().is_empty(), "a rewrite everything could reach says nothing");
|
|
}
|
|
|
|
#[test]
|
|
fn will_rename_works_for_a_file_no_editor_ever_opened() {
|
|
// Includes live in unopened files; the sweep reads them off disk
|
|
// through the same `sources()` the index is built from.
|
|
let tree = Tree::new("willrenameunopened");
|
|
tree.write("defs.svh", "`define W 8\n");
|
|
tree.write("top.sv", "`include \"defs.svh\"\n");
|
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
|
assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open");
|
|
|
|
let answer =
|
|
will_rename(&mut session, &tree.path.join("defs.svh"), &tree.path.join("widths.svh"));
|
|
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
|
assert_eq!(
|
|
answer["changes"][uri.as_str()][0]["newText"],
|
|
serde_json::json!("widths.svh"),
|
|
"{answer:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn will_rename_answers_null_when_there_is_nothing_to_rewrite() {
|
|
let tree = Tree::new("willrenamenull");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.write("notes.md", "prose\n");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
|
|
// A source file nothing includes.
|
|
let answer =
|
|
will_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
|
assert_eq!(answer, Value::Null, "{answer:#?}");
|
|
// And a file this server has no opinion about at all.
|
|
let answer =
|
|
will_rename(&mut session, &tree.path.join("notes.md"), &tree.path.join("NOTES.md"));
|
|
assert_eq!(answer, Value::Null, "{answer:#?}");
|
|
assert!(session.shown().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn an_include_a_rename_strands_is_shown_once_and_logged() {
|
|
// The same "first shown, all logged" rule the scope warnings follow —
|
|
// a rename that strands forty includes must not open forty popups.
|
|
let tree = Tree::new("willrenamewarn");
|
|
std::fs::create_dir_all(tree.path.join("inc")).expect("mkdir");
|
|
tree.write("inc/defs.svh", "`define W 8\n");
|
|
tree.write("a.sv", "`include <defs.svh>\n");
|
|
tree.write("b.sv", "`include <defs.svh>\n");
|
|
tree.write("files.f", "+incdir+inc\na.sv\nb.sv\n");
|
|
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let _ = session.drain();
|
|
|
|
// The angled form resolves against incdirs only, so a move out of the
|
|
// one include path cannot be spelled from either file.
|
|
let answer =
|
|
will_rename(&mut session, &tree.path.join("inc/defs.svh"), &tree.path.join("far.svh"));
|
|
assert_eq!(answer, Value::Null, "nothing invented: {answer:#?}");
|
|
let shown = session.drain();
|
|
let popups: Vec<&Message> = shown
|
|
.iter()
|
|
.filter(|m| matches!(m, Message::Notification(n) if n.method == ShowMessage::METHOD))
|
|
.collect();
|
|
let logs: Vec<&Message> = shown
|
|
.iter()
|
|
.filter(|m| matches!(m, Message::Notification(n) if n.method == LogMessage::METHOD))
|
|
.collect();
|
|
assert_eq!(popups.len(), 1, "one popup for two stranded includes: {popups:#?}");
|
|
assert_eq!(logs.len(), 2, "both are logged: {logs:#?}");
|
|
}
|
|
|
|
/// One `workspace/didRenameFiles` for `from` → `to`.
|
|
fn did_rename(session: &mut Session, from: &Path, to: &Path) {
|
|
session.notify(
|
|
DidRenameFiles::METHOD,
|
|
serde_json::json!({ "files": [{
|
|
"oldUri": path_to_uri(from).expect("uri"),
|
|
"newUri": path_to_uri(to).expect("uri"),
|
|
}] }),
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_rename_notification_rebuilds_the_index() {
|
|
let tree = Tree::new("didrename");
|
|
tree.package("rtl/a.sv", "a");
|
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
|
assert_eq!(indexed(&session, "a"), 1, "premise: indexed under its old name");
|
|
|
|
std::fs::rename(tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")).expect("rename");
|
|
did_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
|
assert_eq!(indexed(&session, "a"), 1, "still one package, found at its new path");
|
|
|
|
// And the same nudge from the watcher for the same move changes
|
|
// nothing: the rebuild is a re-read of the tree, not an increment.
|
|
session.watched(&[tree.path.join("rtl/b.sv")]);
|
|
assert_eq!(indexed(&session, "a"), 1, "reindexing twice is harmless");
|
|
}
|
|
|
|
#[test]
|
|
fn a_delete_notification_rebuilds_the_index() {
|
|
let tree = Tree::new("diddelete");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/gone.sv", "gone_pkg");
|
|
let mut session = Session::wide(vec![tree.path.clone()], false);
|
|
assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed");
|
|
|
|
std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove");
|
|
session.notify(
|
|
DidDeleteFiles::METHOD,
|
|
serde_json::json!({ "files": [
|
|
{ "uri": path_to_uri(&tree.path.join("rtl/gone.sv")).expect("uri") },
|
|
] }),
|
|
);
|
|
assert_eq!(indexed(&session, "gone_pkg"), 0, "gone from the index too");
|
|
assert_eq!(indexed(&session, "a"), 1, "and the rest survives");
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_operation_notification_for_nothing_the_index_reads_costs_no_rebuild() {
|
|
let tree = Tree::new("didrenamestray");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
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");
|
|
|
|
did_rename(&mut session, &tree.path.join("README.md"), &tree.path.join("READ.md"));
|
|
session.notify(
|
|
DidDeleteFiles::METHOD,
|
|
serde_json::json!({ "files": [
|
|
{ "uri": path_to_uri(&tree.path.join("notes.txt")).expect("uri") },
|
|
] }),
|
|
);
|
|
assert_eq!(session.publishes(), 0, "neither is a path the index reads");
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// workspace folders (2026-08-27)
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A `workspace/didChangeWorkspaceFolders` event, as a client sends it.
|
|
fn folder_event(added: &[&Path], removed: &[&Path]) -> Value {
|
|
let folders = |paths: &[&Path]| -> Vec<Value> {
|
|
paths
|
|
.iter()
|
|
.map(|path| {
|
|
serde_json::json!({
|
|
"uri": path_to_uri(path).expect("uri"),
|
|
"name": path.file_name().and_then(|n| n.to_str()).unwrap_or("folder"),
|
|
})
|
|
})
|
|
.collect()
|
|
};
|
|
serde_json::json!({ "event": { "added": folders(added), "removed": folders(removed) } })
|
|
}
|
|
|
|
fn folders_changed(session: &mut Session, added: &[&Path], removed: &[&Path]) {
|
|
session.notify(DidChangeWorkspaceFolders::METHOD, folder_event(added, removed));
|
|
}
|
|
|
|
#[test]
|
|
fn a_didopen_rebuilds_exactly_when_it_widens_the_scope() {
|
|
// Superseded this round (index-scope, 2026-08-27): the test that stood
|
|
// here — `a_rootless_session_gaining_its_first_folder_flips_didopen_
|
|
// from_reindex_to_publish` — pinned `didOpen`'s *root*-conditional,
|
|
// rootless reindexing and rooted publishing. Rung 3 is now the default
|
|
// rung with a root as well, so the root set is not the question any
|
|
// more; the question is whether the file just opened brought a folder
|
|
// the index does not cover, and this is the same case list under the
|
|
// rule that replaced it. The pinned property is strictly stronger: it
|
|
// holds in a rootless session and in a rooted one, and it is the same
|
|
// one line of code for both.
|
|
let outside = Tree::new("didopenscopeoutside");
|
|
outside.package("a.sv", "a");
|
|
let folder = Tree::new("didopenscopefolder");
|
|
folder.package("rtl/b.sv", "b");
|
|
folder.package("rtl/beside.sv", "beside");
|
|
|
|
let mut session = Session::new(Vec::new(), false);
|
|
assert!(!session.server.workspace.has_roots(), "premise: rootless");
|
|
|
|
// `generation` counts a buffer's text *and* the index, so an open that
|
|
// widens is `set_document`'s bump plus `reindex`'s own — two.
|
|
let before = session.server.generation;
|
|
let _ = session
|
|
.open(&outside.path.join("a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
assert_eq!(session.server.generation, before + 2, "a new folder widens by reindexing");
|
|
|
|
folders_changed(&mut session, &[&folder.path], &[]);
|
|
assert!(session.server.workspace.has_roots(), "the workspace now has a root");
|
|
|
|
// A root does not make the scope wide: this file's folder has still
|
|
// never been opened from, so it widens and rebuilds exactly as the
|
|
// rootless one did.
|
|
let after_folder = session.server.generation;
|
|
let uri = session
|
|
.open(&folder.path.join("rtl/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
|
assert_eq!(
|
|
session.server.generation,
|
|
after_folder + 2,
|
|
"a folder outside the scope widens it, root or no root"
|
|
);
|
|
assert_eq!(indexed(&session, "b"), 1, "and the widened scope really was scanned");
|
|
assert!(session.published().iter().any(|p| p.uri == uri), "and it is published too");
|
|
|
|
// The second file in a folder already in scope costs only
|
|
// `set_document`'s bump: nothing about which files exist moved.
|
|
let quiet = session.server.generation;
|
|
let uri = session.open(
|
|
&folder.path.join("rtl/beside.sv"),
|
|
"package beside;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
assert_eq!(
|
|
session.server.generation,
|
|
quiet + 1,
|
|
"a file the scope already covers must not cost a rescan"
|
|
);
|
|
assert!(
|
|
session.published().iter().any(|p| p.uri == uri),
|
|
"it is still published, just not rescanned"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
|
|
// The chooser, as a table. Everything but "grew and lost nothing"
|
|
// falls back to the whole rescan, which is always a correct answer.
|
|
let a = PathBuf::from("/w/a");
|
|
let b = PathBuf::from("/w/b");
|
|
let c = PathBuf::from("/w/c");
|
|
let all = [a.clone(), b.clone(), c.clone()];
|
|
|
|
assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved");
|
|
assert_eq!(
|
|
widen_of(&all, &all),
|
|
Widen::Nothing,
|
|
"and one an open buffer could not widen — a filelist or the wide rung, both empty"
|
|
);
|
|
assert_eq!(
|
|
widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]),
|
|
Widen::Added(vec![b.clone()]),
|
|
"one folder added: only that folder is indexed"
|
|
);
|
|
assert_eq!(
|
|
widen_of(&[], &all),
|
|
Widen::Added(all.to_vec()),
|
|
"the first open of a session adds every directory it has"
|
|
);
|
|
assert_eq!(
|
|
widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]),
|
|
Widen::Added(vec![a.clone(), c.clone()]),
|
|
"two added around one held: both, and never the held one"
|
|
);
|
|
// The `scopeDepth: 2` shape `performance_take2.md` §5b measured: the
|
|
// newly opened file raises to a directory that *contains* one already
|
|
// in scope. The contained directory is still in `after` — every opened
|
|
// directory is raised on its own and none of them is ever dropped — so
|
|
// this is an add like any other, and the widen's own file diff is what
|
|
// stops the overlap being read twice
|
|
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
|
let ip = PathBuf::from("/w");
|
|
assert_eq!(
|
|
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
|
|
Widen::Added(vec![ip]),
|
|
"a folder that subsumes the old scope is an add, not a removal"
|
|
);
|
|
assert_eq!(
|
|
widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)),
|
|
Widen::Whole,
|
|
"a directory that left is not an add: the whole rescan settles what went with it"
|
|
);
|
|
assert_eq!(
|
|
widen_of(&[a.clone(), b.clone()], &[a, c]),
|
|
Widen::Whole,
|
|
"and a swap is a removal too, however many arrived beside it"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() {
|
|
// The round's claim, through the real dispatch: two jumps into two new
|
|
// folders, each answered by indexing only that folder, and the tables
|
|
// that come out are the ones a whole rescan produces — asked by
|
|
// running that rescan afterwards and comparing.
|
|
let tree = Tree::new("didopenwidenequal");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/a2.sv", "a2");
|
|
tree.package("lib/b.sv", "b");
|
|
tree.package("lib/b2.sv", "b2");
|
|
tree.package("tb/c.sv", "c");
|
|
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let _ = session
|
|
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
let _ = session
|
|
.open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
|
let _ = session
|
|
.open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n");
|
|
assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders");
|
|
assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened");
|
|
|
|
let widened = session.server.workspace.index().fingerprint();
|
|
let words = session.server.workspace.candidates().words("").to_vec();
|
|
let includes = session.server.workspace.includes().fingerprint();
|
|
session.server.workspace.rebuild_index();
|
|
assert_eq!(widened, session.server.workspace.index().fingerprint(), "index");
|
|
assert_eq!(words, session.server.workspace.candidates().words(""), "completion words");
|
|
assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph");
|
|
}
|
|
|
|
#[test]
|
|
fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() {
|
|
// A widen answered while a scan runs cannot fold itself in: that scan
|
|
// holds a work list taken from the *old* scope, so folding a widen
|
|
// into it would make "which files exist" mean two things inside one
|
|
// scan. It sets the same `rescan_wanted` flag every other mid-scan
|
|
// trigger sets — one more whole scan after this one, coalesced with
|
|
// whatever else asked (`docs/features/scan-interleave/README.md`).
|
|
//
|
|
// Driven directly rather than over the wire, because the wire cannot
|
|
// reach it in one step: a widen itself never drains the queue, and the
|
|
// startup scan under the folder scope indexes nothing and so never
|
|
// interleaves. The reachable route is a `didOpen` answered inside a
|
|
// long *whole* rescan, which is this flag and this call.
|
|
let tree = Tree::new("widenmidscan");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("lib/late.sv", "late");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
// The shipped depth is 2 since 2026-08-28, which would have `lib/` in
|
|
// scope before the widen this test is about — so the premise names the
|
|
// narrow depth rather than assuming it.
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }),
|
|
);
|
|
let _ = session
|
|
.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope");
|
|
|
|
session.server.scanning = true;
|
|
session.server.reindex_widened(vec![tree.path.join("lib")]);
|
|
assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan");
|
|
assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan");
|
|
|
|
// What the running scan's own loop then does with the flag.
|
|
session.server.scanning = false;
|
|
let warnings = session.server.scan_until_settled(true);
|
|
assert!(warnings.is_empty(), "{warnings:?}");
|
|
assert!(!session.server.rescan_wanted, "one more scan is all it was owed");
|
|
// Not indexed, and correctly so: the deferred rescan is a *whole* one
|
|
// over the scope as it now stands, and `lib/` entered that scope only
|
|
// because a buffer was opened from it — which this test never did.
|
|
assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move");
|
|
}
|
|
|
|
#[test]
|
|
fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() {
|
|
// The whole point: "Add Folder to Workspace" used to change nothing
|
|
// until the editor was restarted.
|
|
let first = Tree::new("folderadd");
|
|
first.package("rtl/a.sv", "a");
|
|
let second = Tree::new("folderaddsecond");
|
|
second.package("rtl/b.sv", "b");
|
|
|
|
let mut session = Session::wide(vec![first.path.clone()], false);
|
|
assert_eq!(indexed(&session, "b"), 0, "premise: the second folder is not open yet");
|
|
|
|
folders_changed(&mut session, &[&second.path], &[]);
|
|
assert_eq!(indexed(&session, "b"), 1, "the added folder is scanned");
|
|
assert_eq!(indexed(&session, "a"), 1, "and the one already open survives");
|
|
|
|
// And it is reachable through a real request, not only in the index.
|
|
let hits = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query":"b"}));
|
|
let found = hits.as_array().expect("a symbol list");
|
|
assert!(
|
|
found.iter().any(|hit| hit["location"]["uri"]
|
|
.as_str()
|
|
.is_some_and(|uri| uri.contains("folderaddsecond"))),
|
|
"{found:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed() {
|
|
// The client owns buffer lifecycle: closing a folder does not close
|
|
// the editors that were open in it. Such a buffer keeps the deal
|
|
// every rootless buffer has always had — it is still analyzed, still
|
|
// published, and still overrides disk in the index.
|
|
let first = Tree::new("folderremove");
|
|
first.package("rtl/a.sv", "a");
|
|
let second = Tree::new("folderremovesecond");
|
|
second.package("rtl/open.sv", "open_pkg");
|
|
second.package("rtl/other.sv", "other_pkg");
|
|
|
|
let mut session = Session::wide(vec![first.path.clone(), second.path.clone()], false);
|
|
let uri = session.open(
|
|
&second.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
assert_eq!(indexed(&session, "other_pkg"), 1, "premise: the whole folder is indexed");
|
|
|
|
folders_changed(&mut session, &[], &[&second.path]);
|
|
assert_eq!(indexed(&session, "other_pkg"), 0, "the folder's files left the index");
|
|
assert_eq!(indexed(&session, "a"), 1, "the folder that stayed is untouched");
|
|
assert_eq!(
|
|
indexed(&session, "open_pkg"),
|
|
1,
|
|
"the open buffer contributes itself, as every out-of-scope buffer does"
|
|
);
|
|
|
|
// The rebuild republished it, and an edit to it is still diagnosed.
|
|
let published = session.published();
|
|
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
|
|
);
|
|
let published = session.published();
|
|
assert_eq!(published.len(), 1, "{published:#?}");
|
|
assert_eq!(published[0].uri, uri);
|
|
assert!(!published[0].diagnostics.is_empty(), "a broken buffer still reports");
|
|
|
|
// And closing it clears cleanly — the removed folder is not a special
|
|
// case for `didClose`, which already sends an empty publish for
|
|
// whatever buffer is named regardless of where it lived.
|
|
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
|
session.notify(
|
|
DidCloseTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
let published = session.published();
|
|
assert_eq!(published.len(), 1, "{published:#?}");
|
|
assert_eq!(published[0].uri, uri);
|
|
assert!(published[0].diagnostics.is_empty(), "the close cleared it");
|
|
}
|
|
|
|
#[test]
|
|
fn one_folder_notification_is_one_rescan_with_one_bar_and_one_generation() {
|
|
// Everything a rescan owes rides inside `reindex()`; an event carries
|
|
// both lists, so it must cost exactly one of each.
|
|
let first = Tree::new("folderonce");
|
|
first.package("rtl/a.sv", "a");
|
|
let second = Tree::new("folderoncesecond");
|
|
second.package("rtl/b.sv", "b");
|
|
let third = Tree::new("folderoncethird");
|
|
third.package("rtl/c.sv", "c");
|
|
|
|
let abilities = ClientAbilities {
|
|
work_done_progress: true,
|
|
code_lens_refresh: true,
|
|
..Default::default()
|
|
};
|
|
let mut session =
|
|
Session::wide_with(vec![first.path.clone(), second.path.clone()], abilities);
|
|
session.open(&first.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
let before = session.server.generation;
|
|
let _ = session.drain();
|
|
|
|
// One notification that both adds and removes: two changes, one scan.
|
|
folders_changed(&mut session, &[&third.path], &[&second.path]);
|
|
assert_eq!(indexed(&session, "c"), 1, "the addition took");
|
|
assert_eq!(indexed(&session, "b"), 0, "and so did the removal");
|
|
assert_eq!(session.server.generation, before + 1, "one generation bump");
|
|
|
|
let messages = session.drain();
|
|
let steps: Vec<&'static str> =
|
|
messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect();
|
|
// One bar, up and down — with a report for each of the two files the
|
|
// new root set holds (`a.sv` and `c.sv`).
|
|
assert_eq!(steps, vec!["create", "begin", "report", "report", "end"], "one bar");
|
|
let publishes = messages
|
|
.iter()
|
|
.filter(
|
|
|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD),
|
|
)
|
|
.count();
|
|
assert_eq!(publishes, 1, "the one open buffer is republished once");
|
|
let refreshes = messages
|
|
.iter()
|
|
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
|
.count();
|
|
assert_eq!(refreshes, 1, "the counts on screen were invalidated once");
|
|
}
|
|
|
|
#[test]
|
|
fn a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added() {
|
|
// Three separate notifications, each of which genuinely moves the
|
|
// root set (unlike the no-op shapes above), must cost three separate
|
|
// rescans — `change_roots` has no batching across notifications, only
|
|
// within one — and the state after must be consistent with the net
|
|
// effect: two adds and one remove is "present".
|
|
// QA (2026-08-27): "own shapes" case from the review checklist.
|
|
let root = Tree::new("rapidflaproot");
|
|
root.package("rtl/a.sv", "a");
|
|
let flapping = Tree::new("rapidflapfolder");
|
|
flapping.package("rtl/b.sv", "b");
|
|
|
|
let mut session = Session::wide(vec![root.path.clone()], false);
|
|
let before = session.server.generation;
|
|
|
|
folders_changed(&mut session, &[&flapping.path], &[]);
|
|
assert_eq!(indexed(&session, "b"), 1, "added");
|
|
folders_changed(&mut session, &[], &[&flapping.path]);
|
|
assert_eq!(indexed(&session, "b"), 0, "removed");
|
|
folders_changed(&mut session, &[&flapping.path], &[]);
|
|
assert_eq!(indexed(&session, "b"), 1, "added again");
|
|
|
|
assert_eq!(
|
|
session.server.generation,
|
|
before + 3,
|
|
"one rescan per notification, three total"
|
|
);
|
|
assert_eq!(
|
|
indexed(&session, "a"),
|
|
1,
|
|
"the folder that never moved is untouched throughout"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_folder_event_that_moves_nothing_costs_nothing() {
|
|
// Total and no-op-safe: every shape a client can send that leaves the
|
|
// root set where it was must cost no rescan at all.
|
|
let tree = Tree::new("foldernoop");
|
|
tree.package("rtl/a.sv", "a");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
|
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
let before = session.server.generation;
|
|
let _ = session.drain();
|
|
|
|
folders_changed(&mut session, &[], &[]);
|
|
folders_changed(&mut session, &[&tree.path], &[]);
|
|
folders_changed(&mut session, &[], &[&tree.path.join("never-added")]);
|
|
folders_changed(&mut session, &[&tree.path], &[&tree.path]);
|
|
// Params that do not parse at all, and a folder that is not a path.
|
|
session.notify(DidChangeWorkspaceFolders::METHOD, serde_json::json!({ "nonsense": 1 }));
|
|
session.notify(
|
|
DidChangeWorkspaceFolders::METHOD,
|
|
serde_json::json!({ "event": {
|
|
"added": [{ "uri": "untitled:Untitled-1", "name": "scratch" }], "removed": [],
|
|
} }),
|
|
);
|
|
|
|
assert!(session.progress().is_empty(), "no rescan for any of them");
|
|
assert_eq!(session.publishes(), 0, "and nothing was republished");
|
|
assert_eq!(session.server.generation, before, "and no generation moved");
|
|
assert_eq!(indexed(&session, "a"), 1, "the root itself survived every one");
|
|
}
|
|
|
|
#[test]
|
|
fn a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves() {
|
|
// The source glob is workspace-wide — the client matches it against
|
|
// whatever folders it holds, so a folder change needs no new
|
|
// registration for it. The *filelist* watcher is an absolute path
|
|
// anchored at the first root, so a folder change can move it without
|
|
// anyone touching the setting.
|
|
let first = Tree::new("folderwatch");
|
|
first.package("rtl/a.sv", "a");
|
|
first.write("files.f", "rtl/a.sv\n");
|
|
let second = Tree::new("folderwatchsecond");
|
|
second.package("rtl/b.sv", "b");
|
|
second.write("files.f", "rtl/b.sv\n");
|
|
|
|
let mut session = Session::new(vec![first.path.clone()], true);
|
|
let _ = session.drain();
|
|
|
|
// No filelist setting: nothing about the registration depends on the
|
|
// roots, so adding a folder re-registers nothing.
|
|
folders_changed(&mut session, &[&second.path], &[]);
|
|
assert!(session.requests().is_empty(), "the source glob is workspace-wide");
|
|
|
|
// With a *relative* filelist the watched path is `<first root>/files.f`...
|
|
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
|
let _ = session.drain();
|
|
// ...so dropping that root moves it to the second folder's copy.
|
|
folders_changed(&mut session, &[], &[&first.path]);
|
|
let requests = session.requests();
|
|
assert_eq!(requests.len(), 2, "{requests:#?}");
|
|
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
|
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
|
assert_eq!(
|
|
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
|
second.path.join("files.f").to_str().expect("utf-8").to_string(),
|
|
"{requests:#?}"
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// pulled settings (2026-08-27)
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A client that answers `workspace/configuration`.
|
|
fn pulling_settings() -> ClientAbilities {
|
|
ClientAbilities { configuration: true, ..Default::default() }
|
|
}
|
|
|
|
/// The id of the one outstanding `workspace/configuration`, and the params
|
|
/// it went out with.
|
|
fn configuration_request(session: &Session) -> (RequestId, Value) {
|
|
let sent = session.sent();
|
|
let asked: Vec<&Request> =
|
|
sent.iter().filter(|r| r.method == WorkspaceConfiguration::METHOD).collect();
|
|
assert_eq!(asked.len(), 1, "exactly one pull is outstanding: {sent:#?}");
|
|
(asked[0].id.clone(), asked[0].params.clone())
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
|
|
let tree = Tree::new("pullstartup");
|
|
tree.package("rtl/a.sv", "a");
|
|
let session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (_id, params) = configuration_request(&session);
|
|
assert_eq!(
|
|
params,
|
|
serde_json::json!({ "items": [{ "section": "lucisv" }] }),
|
|
"one item, our section, no scope"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
|
// `Server::new` calls `register_watchers` and then
|
|
// `request_configuration`, in that order — this pins it on the actual
|
|
// wire rather than trusting the call order in the source. Every
|
|
// outgoing request's id is `lucisv-{n}` off one monotonically
|
|
// increasing counter, so the numeric suffix *is* the send order.
|
|
// QA (2026-08-27): pinned per the dev's own review checklist item
|
|
// ("verify on the wire").
|
|
let tree = Tree::new("pulloraftwatch");
|
|
let abilities =
|
|
ClientAbilities { file_watching: true, configuration: true, ..pulling_settings() };
|
|
let session = Session::with(vec![tree.path.clone()], abilities);
|
|
let sent = session.sent();
|
|
let index_of = |method: &str| -> usize {
|
|
sent.iter()
|
|
.position(|r| r.method == method)
|
|
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
|
};
|
|
let watchers = index_of(RegisterCapability::METHOD);
|
|
let pull = index_of(WorkspaceConfiguration::METHOD);
|
|
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
|
|
|
|
let numeric_suffix = |request: &Request| -> u32 {
|
|
request
|
|
.id
|
|
.to_string()
|
|
.trim_matches('"')
|
|
.trim_start_matches("lucisv-")
|
|
.parse()
|
|
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
|
|
};
|
|
assert!(
|
|
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
|
|
"the pull's id must be issued after the watcher registration's: {sent:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_cannot_be_asked_is_never_asked() {
|
|
// Every client that predates this — `smoke.js` included — sends
|
|
// `capabilities: {}` and must see nothing new at all.
|
|
let tree = Tree::new("pullnone");
|
|
let session = Session::new(vec![tree.path.clone()], false);
|
|
assert!(session.requests().is_empty(), "{:#?}", session.requests());
|
|
}
|
|
|
|
#[test]
|
|
fn a_pulled_answer_reaches_the_formatter_through_the_same_parser_a_push_uses() {
|
|
let tree = Tree::new("pullapply");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
|
let (id, _) = configuration_request(&session);
|
|
|
|
// The editor's tab size, until the client answers.
|
|
assert_eq!(
|
|
formatting_result(&mut session, &uri)[0]["newText"],
|
|
serde_json::json!("module m;\n wire a;\nendmodule\n")
|
|
);
|
|
|
|
// The answer is an array with one entry per requested item, and the
|
|
// entry is the *section*, not the `{lucisv: ...}` wrapper a push has.
|
|
session.answer(id, serde_json::json!([{ "indent": 4, "lineLength": 120 }]));
|
|
assert_eq!(
|
|
formatting_result(&mut session, &uri)[0]["newText"],
|
|
serde_json::json!("module m;\n wire a;\nendmodule\n"),
|
|
"the pulled indent is in force"
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().line_length, Some(120));
|
|
}
|
|
|
|
#[test]
|
|
fn a_pulled_answer_that_changes_the_scope_rebuilds_the_index() {
|
|
// The pull applies through the same path a push does, so an `exclude`
|
|
// that arrives this way must cost the same rescan.
|
|
let tree = Tree::new("pullexclude");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("scratch/wip.sv", "scratch_pkg");
|
|
let mut session = Session::wide_with(vec![tree.path.clone()], pulling_settings());
|
|
assert_eq!(indexed(&session, "scratch_pkg"), 1, "premise: indexed at first");
|
|
|
|
let (id, _) = configuration_request(&session);
|
|
// The pulled section carries the scope for the same reason a pushed
|
|
// one does: an answer is the *whole* section, so leaving it out would
|
|
// narrow the index in the same breath as the exclude.
|
|
session.answer(
|
|
id,
|
|
serde_json::json!([{ "exclude": ["scratch"], "index": { "scope": "workspace" } }]),
|
|
);
|
|
assert_eq!(indexed(&session, "scratch_pkg"), 0, "the pulled exclude took effect");
|
|
assert_eq!(indexed(&session, "a"), 1, "and nothing else moved");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses() {
|
|
// `apply_settings` is the one function both doors go through, but
|
|
// nothing pinned it for the *pull* path specifically before this: the
|
|
// answer changing `lucisv.filelist` must move `filelist_path()` and
|
|
// cost a watcher re-registration exactly as a pushed one does.
|
|
// QA (2026-08-27): pinned per the dev's own review checklist item
|
|
// ("the full chain: pull answer -> apply_settings -> filelist moved
|
|
// -> re-register").
|
|
let tree = Tree::new("pullfilelistwatch");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
let abilities =
|
|
ClientAbilities { configuration: true, file_watching: true, ..Default::default() };
|
|
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
|
// Drains the startup watcher registration and the startup pull's own
|
|
// request together; `configuration_request` needs only the latter.
|
|
let (id, _) = configuration_request(&session);
|
|
|
|
session.answer(id, serde_json::json!([{ "filelist": "files.f" }]));
|
|
let requests = session.requests();
|
|
assert_eq!(requests.len(), 2, "{requests:#?}");
|
|
assert_eq!(requests[0].0, UnregisterCapability::METHOD, "the old registration first");
|
|
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
|
assert_eq!(
|
|
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
|
tree.path.join("files.f").to_str().expect("utf-8").to_string(),
|
|
"{requests:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn an_unusable_pull_answer_leaves_the_defaults_and_says_nothing() {
|
|
// Nothing here is the user's fault and nothing here is actionable, so
|
|
// every one of these must be as quiet as a client that answered
|
|
// `null` — which is what the spec asks a client without the section
|
|
// to do.
|
|
let tree = Tree::new("pulljunk");
|
|
for answer in [
|
|
serde_json::json!(null),
|
|
serde_json::json!([]),
|
|
serde_json::json!([null]),
|
|
serde_json::json!("lucisv"),
|
|
serde_json::json!({ "indent": 4 }),
|
|
serde_json::json!([{ "indent": "four", "exclude": 7 }]),
|
|
serde_json::json!([{ "lucisv": { "indent": 4 } }]),
|
|
] {
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id, answer.clone());
|
|
assert_eq!(
|
|
session.server.workspace.client_settings(),
|
|
&settings::ClientSettings::default(),
|
|
"the answer {answer} must leave the defaults"
|
|
);
|
|
assert!(session.shown().is_empty(), "and must not open a popup");
|
|
}
|
|
|
|
// An error response is the same news, said differently.
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
session.server.response(Response::new_err(
|
|
id,
|
|
lsp_server::ErrorCode::MethodNotFound as i32,
|
|
"no configuration here".to_string(),
|
|
));
|
|
assert_eq!(
|
|
session.server.workspace.client_settings(),
|
|
&settings::ClientSettings::default()
|
|
);
|
|
assert!(session.shown().is_empty(), "a refused pull is not worth a popup");
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_push_pulls_instead_of_resetting_everything_to_default() {
|
|
// The modern client's "something changed, ask me for what you need".
|
|
// Applying it as a payload would silently clear the settings it just
|
|
// told us to come and fetch.
|
|
let tree = Tree::new("pushempty");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
|
|
|
for empty in
|
|
[serde_json::json!({ "settings": {} }), serde_json::json!({ "settings": null })]
|
|
{
|
|
let _ = session.drain();
|
|
session.notify(DidChangeConfiguration::METHOD, empty.clone());
|
|
assert_eq!(
|
|
session.server.workspace.client_settings().indent,
|
|
Some(4),
|
|
"{empty} must not clear what was pulled"
|
|
);
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "{empty}");
|
|
// Put it back for the next round.
|
|
session.server.workspace.set_client_settings(settings::ClientSettings {
|
|
indent: Some(4),
|
|
..Default::default()
|
|
});
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_push_to_a_client_that_cannot_be_asked_still_means_no_opinion() {
|
|
// The legacy path, unchanged: with nobody to ask, an empty payload is
|
|
// what it has always been — no opinion about anything.
|
|
let tree = Tree::new("pushemptylegacy");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "indent": 4 } } }),
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
|
assert_eq!(session.server.workspace.client_settings().indent, None, "cleared, as before");
|
|
assert!(session.requests().is_empty(), "and nothing was asked of it");
|
|
}
|
|
|
|
#[test]
|
|
fn a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked() {
|
|
// The legacy `synchronize.configurationSection` path survives the
|
|
// pull model: a client that sends both must not have its own push
|
|
// ignored in favour of a round trip.
|
|
let tree = Tree::new("pushpayload");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id, serde_json::json!([null]));
|
|
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(8));
|
|
let sent = session.sent();
|
|
assert!(
|
|
!sent.iter().any(|r| r.method == WorkspaceConfiguration::METHOD),
|
|
"a payload is not a request to go and fetch one: {sent:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding() {
|
|
// The other half of the precedence question: a client that both
|
|
// pushes (the legacy `synchronize.configurationSection`) and can be
|
|
// pulled may have its own push arrive *before* the startup pull's
|
|
// answer does — both mechanisms firing off the same connection at
|
|
// once. The loop is single-threaded and processes messages strictly
|
|
// in receive order, with no notion of "the push is newer" beyond
|
|
// that: `apply_settings` always replaces the whole struct, so
|
|
// whichever of the two is processed *last* is simply what is in
|
|
// force afterward. QA (2026-08-27): pinned per the dev's own review
|
|
// checklist item ("push-with-payload arriving while a pull is
|
|
// outstanding — which wins").
|
|
let tree = Tree::new("latepullwins");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
|
|
// The push lands first, while the startup pull is still outstanding.
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the push landed");
|
|
|
|
// The pull's answer arrives after — and, being processed last,
|
|
// overwrites it.
|
|
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
|
assert_eq!(
|
|
session.server.workspace.client_settings().indent,
|
|
Some(4),
|
|
"processed last, so in force last — the pull's answer, not the push"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn three_outstanding_requests_are_answered_by_id_in_any_order() {
|
|
// `applyEdit`, a progress `create` and a `workspace/configuration`
|
|
// all in flight at once. Only two of them are in `pending`, and the
|
|
// arrival order is not the send order — the id is the whole lookup,
|
|
// and neither answer may be delivered to the other's handler.
|
|
let abilities = ClientAbilities {
|
|
apply_edit: true,
|
|
work_done_progress: true,
|
|
configuration: true,
|
|
..Default::default()
|
|
};
|
|
let (tree, mut session, params) = propagating("threeway", abilities);
|
|
let _ = session.drain();
|
|
// `propagating` answered nothing, so the startup pull is already
|
|
// spent; an empty push asks again, and that one is left outstanding
|
|
// alongside the other two.
|
|
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
|
|
|
let result = session.result(ExecuteCommand::METHOD, params);
|
|
assert!(result.is_null(), "the edit was pushed, not returned");
|
|
// Two files, so the rescan is the whole one that puts a bar up.
|
|
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
|
|
|
let sent = session.sent();
|
|
let of = |method: &str| -> RequestId {
|
|
sent.iter()
|
|
.find(|request| request.method == method)
|
|
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
|
.id
|
|
.clone()
|
|
};
|
|
let (edit, create, pull) = (
|
|
of(ApplyWorkspaceEdit::METHOD),
|
|
of(WorkDoneProgressCreate::METHOD),
|
|
of(WorkspaceConfiguration::METHOD),
|
|
);
|
|
|
|
// Backwards: the pull first, then the ignorable create, then the edit.
|
|
session.answer(pull, serde_json::json!([{ "indent": 4 }]));
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "the pull landed");
|
|
assert!(session.shown().is_empty(), "and said nothing to the user");
|
|
|
|
session.answer(create, serde_json::json!(null));
|
|
assert!(session.shown().is_empty(), "a create answer says nothing either");
|
|
|
|
session.answer(edit, serde_json::json!({ "applied": false }));
|
|
let shown = session.shown();
|
|
assert_eq!(shown.len(), 1, "{shown:#?}");
|
|
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn two_outstanding_configuration_pulls_are_each_answered_by_their_own_id() {
|
|
// A second pull can go out before the first is answered — an empty
|
|
// `didChangeConfiguration` racing the client's answer to the startup
|
|
// pull, say. Both ids sit in `pending` at once; each answer is
|
|
// applied through its own id, and whichever is processed last is
|
|
// simply what ends up in force — there is no notion of the newer
|
|
// pull's answer winning over the older one, only processing order.
|
|
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
|
let tree = Tree::new("twopulls");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let sent = session.sent();
|
|
let first = sent
|
|
.iter()
|
|
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
|
.expect("the startup pull")
|
|
.id
|
|
.clone();
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
|
let sent = session.sent();
|
|
let second = sent
|
|
.iter()
|
|
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
|
.expect("the re-pull")
|
|
.id
|
|
.clone();
|
|
assert_ne!(first, second, "two distinct outstanding requests, not one reused");
|
|
|
|
// Answered out of order: the second (newer) pull first, then the
|
|
// first (older, startup) one.
|
|
session.answer(second, serde_json::json!([{ "indent": 8 }]));
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the newer landed");
|
|
session.answer(first, serde_json::json!([{ "indent": 4 }]));
|
|
assert_eq!(
|
|
session.server.workspace.client_settings().indent,
|
|
Some(4),
|
|
"whichever answer is processed last is what is in force — no id-based precedence"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
|
|
// An id the server never sent, or a duplicate answer to one already
|
|
// consumed, names nothing in `pending`: `response` must not panic and
|
|
// must leave whatever settings are in force untouched.
|
|
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
|
let tree = Tree::new("forgottenid");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id.clone(), serde_json::json!([{ "indent": 4 }]));
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
|
|
|
// The same id, answered a second time — already removed from `pending`.
|
|
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
|
assert_eq!(
|
|
session.server.workspace.client_settings().indent,
|
|
Some(4),
|
|
"a stale re-answer is a no-op"
|
|
);
|
|
|
|
// An id that was never sent by this server at all.
|
|
session.answer(
|
|
RequestId::from("never-sent".to_string()),
|
|
serde_json::json!([{ "indent": 2 }]),
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the large-file fast path (`docs/features/large-file-mode/README.md`)
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A session whose fast path starts at 100 bytes, so a test buffer can be
|
|
/// three lines long instead of four megabytes.
|
|
fn fast_path_settings() -> ClientSettings {
|
|
ClientSettings { large_file_threshold: 100, ..Default::default() }
|
|
}
|
|
|
|
/// A source file that is real Verilog and over the test threshold.
|
|
fn big_source() -> String {
|
|
let mut text = String::from("module top;\n wire sig_a;\n");
|
|
for i in 0..20 {
|
|
text.push_str(&format!(" assign sig_a = w{i};\n"));
|
|
}
|
|
text.push_str("endmodule\n");
|
|
assert!(text.len() > 100, "the premise: over the test threshold");
|
|
text
|
|
}
|
|
|
|
/// A session with one large buffer open, and its URI.
|
|
///
|
|
/// Every call gets its own tree: this is the one `Tree::new` name shared
|
|
/// by roughly a dozen tests (every large-file-mode test that does not
|
|
/// need bespoke source text), which — unlike the rest of this module's
|
|
/// trees, each named for the one test that uses it — would otherwise
|
|
/// collide on the same `/tmp` directory under `cargo test`'s default
|
|
/// parallelism and race each other's `remove_dir_all`/`create_dir_all`.
|
|
/// The counter is what makes the shared literal safe to share.
|
|
fn fast_path_session(abilities: ClientAbilities) -> (Tree, Session, Uri) {
|
|
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
let tree = Tree::new(&format!("largefile{n}"));
|
|
let path = tree.path.join("net.v");
|
|
tree.write("net.v", &big_source());
|
|
let mut session =
|
|
Session::started(vec![tree.path.clone()], abilities, fast_path_settings());
|
|
let uri = session.open(&path, &big_source());
|
|
let _ = session.drain();
|
|
(tree, session, uri)
|
|
}
|
|
|
|
/// The params a document-scoped request carries, at a position on the
|
|
/// `sig_a` declaration.
|
|
fn at_sig_a(uri: &Uri) -> Value {
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"position": { "line": 1, "character": 9 },
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn a_buffer_over_the_threshold_opens_on_the_fast_path_and_says_so_once() {
|
|
let (_tree, mut session, uri) = {
|
|
let tree = Tree::new("largeannounce");
|
|
let path = tree.path.join("net.v");
|
|
tree.write("net.v", &big_source());
|
|
let mut session = Session::started(
|
|
vec![tree.path.clone()],
|
|
ClientAbilities::default(),
|
|
fast_path_settings(),
|
|
);
|
|
let uri = session.open(&path, &big_source());
|
|
(tree, session, uri)
|
|
};
|
|
let lines: Vec<String> = session
|
|
.logged()
|
|
.into_iter()
|
|
.map(|(_, message)| message)
|
|
.filter(|message| message.contains("large-file fast path"))
|
|
.collect();
|
|
assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}");
|
|
assert!(lines[0].contains("net.v"), "{}", lines[0]);
|
|
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
|
|
|
// A keystroke in it does not say it again.
|
|
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
|
assert!(
|
|
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
|
|
"the line is per entry, not per notification"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_large_buffer_is_diagnosed_as_empty_and_clears_what_it_left_behind() {
|
|
let tree = Tree::new("largesquiggles");
|
|
let path = tree.path.join("grow.v");
|
|
let mut session = Session::started(
|
|
vec![tree.path.clone()],
|
|
ClientAbilities::default(),
|
|
fast_path_settings(),
|
|
);
|
|
// Small and broken: a real diagnostic is drawn.
|
|
let uri = session.open(&path, "module m;\n wire ;\nendmodule\n");
|
|
let drawn = session.published();
|
|
assert_eq!(drawn.len(), 1);
|
|
assert!(!drawn[0].diagnostics.is_empty(), "premise: squiggles were drawn");
|
|
|
|
// The same buffer, edited past the threshold: one publish, empty, so
|
|
// the squiggles go away rather than being left frozen on screen.
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
|
|
);
|
|
let cleared = session.published();
|
|
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
|
|
assert!(cleared[0].diagnostics.is_empty(), "and it is empty: {cleared:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn semantic_tokens_range_paints_a_large_buffer() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
let data = session.result(
|
|
SemanticTokensRangeRequest::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"range": {
|
|
"start": { "line": 1, "character": 0 },
|
|
"end": { "line": 3, "character": 0 },
|
|
},
|
|
}),
|
|
);
|
|
let tokens = data["data"].as_array().expect("a token array").clone();
|
|
assert!(!tokens.is_empty(), "the window was lexed: {data}");
|
|
assert!(data["resultId"].is_null(), "a range answer is not delta material");
|
|
// First token: `wire` on line 1, five numbers per token.
|
|
assert_eq!(tokens.len() % 5, 0);
|
|
assert_eq!(tokens[0], 1, "delta_line — the first line of the window");
|
|
}
|
|
|
|
#[test]
|
|
fn semantic_tokens_full_is_declined_rather_than_answered_empty() {
|
|
// The whole reason: VS Code marks a model whose document provider
|
|
// answered *anything* as complete and never asks its range provider
|
|
// again. An error leaves it incomplete, so the viewport keeps
|
|
// painting. `serverCancelSupport` decides which code says so.
|
|
let cancels = ClientAbilities { token_server_cancel: true, ..Default::default() };
|
|
let (_tree, mut session, uri) = fast_path_session(cancels);
|
|
let params = serde_json::json!({ "textDocument": { "uri": uri } });
|
|
for method in [SemanticTokensFullRequest::METHOD, SemanticTokensFullDeltaRequest::METHOD] {
|
|
let mut params = params.clone();
|
|
params["previousResultId"] = serde_json::json!("1");
|
|
let error = session.request(method, params).response_result.expect_err("declined");
|
|
assert_eq!(error.code, lsp_server::ErrorCode::ServerCancelled as i32, "{method}");
|
|
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
|
}
|
|
|
|
// A client that never advertised it gets the code every 3.16 client
|
|
// already understands.
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
let error = session
|
|
.request(
|
|
SemanticTokensFullRequest::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
)
|
|
.response_result
|
|
.expect_err("declined");
|
|
assert_eq!(error.code, lsp_server::ErrorCode::ContentModified as i32);
|
|
}
|
|
|
|
#[test]
|
|
fn formatting_a_large_buffer_refuses_out_loud_and_edits_nothing() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
let edits = session.result(
|
|
Formatting::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
);
|
|
assert_eq!(edits, serde_json::json!([]), "no edit, ever");
|
|
let shown = session.shown();
|
|
assert_eq!(shown.len(), 1, "the user pressed a key and is owed a reason: {shown:?}");
|
|
assert_eq!(shown[0].0, MessageType::ERROR);
|
|
assert!(shown[0].1.contains("largeFile.threshold"), "{}", shown[0].1);
|
|
}
|
|
|
|
#[test]
|
|
fn the_two_formatting_requests_the_user_did_not_press_stay_silent() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
let edits = session.result(
|
|
OnTypeFormatting::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"position": { "line": 1, "character": 9 },
|
|
"ch": ";",
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
);
|
|
assert_eq!(edits, serde_json::json!([]));
|
|
let saved = session.result(
|
|
WillSaveWaitUntil::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri }, "reason": 1 }),
|
|
);
|
|
assert_eq!(saved, Value::Null);
|
|
assert!(session.shown().is_empty(), "neither fires on a key the user pressed");
|
|
}
|
|
|
|
#[test]
|
|
fn a_rename_is_refused_rather_than_applied_to_every_file_but_this_one() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
assert_eq!(
|
|
session.result(PrepareRenameRequest::METHOD, at_sig_a(&uri)),
|
|
Value::Null,
|
|
"the box never opens"
|
|
);
|
|
let mut params = at_sig_a(&uri);
|
|
params["newName"] = serde_json::json!("sig_b");
|
|
let error = session.request(Rename::METHOD, params).response_result.expect_err("refused");
|
|
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
|
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
|
}
|
|
|
|
#[test]
|
|
fn definition_and_references_answer_from_one_scan_of_the_buffer() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
// The cursor is on the `sig_a` of `wire sig_a;`, and every `sig_a` in
|
|
// the file is one answer.
|
|
let found = session.result(GotoDefinition::METHOD, at_sig_a(&uri));
|
|
let locations = found.as_array().expect("an array");
|
|
assert_eq!(locations.len(), 1, "{found}");
|
|
assert_eq!(locations[0]["range"]["start"]["line"], 1);
|
|
assert_eq!(locations[0]["uri"].as_str(), Some(uri.as_str()));
|
|
|
|
let mut params = at_sig_a(&uri);
|
|
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
|
let all = session.result(References::METHOD, params.clone());
|
|
assert_eq!(all.as_array().expect("an array").len(), 21, "the wire and its 20 uses");
|
|
params["context"] = serde_json::json!({ "includeDeclaration": false });
|
|
let uses = session.result(References::METHOD, params);
|
|
assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration");
|
|
}
|
|
|
|
/// **The dispatch table.** Every document-scoped request, and what a
|
|
/// buffer on the fast path answers it. The point is that the list is
|
|
/// complete and pinned: a handler added later that reads a large buffer's
|
|
/// *text* will fail here rather than in a user's editor.
|
|
#[test]
|
|
fn every_other_request_a_large_buffer_gets_answers_nothing_at_all() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
let document = serde_json::json!({ "textDocument": { "uri": uri } });
|
|
let position = at_sig_a(&uri);
|
|
let range = serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"range": {
|
|
"start": { "line": 0, "character": 0 },
|
|
"end": { "line": 3, "character": 0 },
|
|
},
|
|
});
|
|
let empty = serde_json::json!([]);
|
|
// (method, params, expected answer)
|
|
let table: Vec<(&str, Value, Value)> = vec![
|
|
(HoverRequest::METHOD, position.clone(), Value::Null),
|
|
(GotoTypeDefinition::METHOD, position.clone(), empty.clone()),
|
|
(LinkedEditingRange::METHOD, position.clone(), Value::Null),
|
|
(DocumentLinkRequest::METHOD, document.clone(), empty.clone()),
|
|
(DocumentHighlightRequest::METHOD, position.clone(), Value::Null),
|
|
(FoldingRangeRequest::METHOD, document.clone(), empty.clone()),
|
|
(DocumentSymbolRequest::METHOD, document.clone(), empty.clone()),
|
|
(CodeLensRequest::METHOD, document.clone(), empty.clone()),
|
|
(InlayHintRequest::METHOD, range.clone(), empty.clone()),
|
|
(
|
|
CodeActionRequest::METHOD,
|
|
{
|
|
let mut params = range.clone();
|
|
params["context"] = serde_json::json!({ "diagnostics": [] });
|
|
params
|
|
},
|
|
empty.clone(),
|
|
),
|
|
(Completion::METHOD, position.clone(), Value::Null),
|
|
(SignatureHelpRequest::METHOD, position.clone(), Value::Null),
|
|
(
|
|
InlineCompletionRequest::METHOD,
|
|
{
|
|
let mut params = position.clone();
|
|
params["context"] =
|
|
serde_json::json!({ "triggerKind": 2, "selectedCompletionInfo": null });
|
|
params
|
|
},
|
|
Value::Null,
|
|
),
|
|
(CallHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
|
(TypeHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
|
// The one custom method: an object with both lists empty, which is
|
|
// what "this buffer has no scopes" already looks like.
|
|
(
|
|
pairs::SCOPE_PAIRS_METHOD,
|
|
document.clone(),
|
|
serde_json::json!({ "pairs": [], "unmatched": [] }),
|
|
),
|
|
];
|
|
for (method, params, expected) in table {
|
|
assert_eq!(session.result(method, params), expected, "{method}");
|
|
}
|
|
// `selectionRange` is the one request that answers something: the
|
|
// whole document is a legal expand-selection step even with nothing
|
|
// parsed, and it costs one span.
|
|
let mut selection = document.clone();
|
|
selection["positions"] = serde_json::json!([{ "line": 1, "character": 9 }]);
|
|
let chain = session.result(SelectionRangeRequest::METHOD, selection);
|
|
assert_eq!(chain.as_array().expect("one chain per position").len(), 1);
|
|
assert!(chain[0]["parent"].is_null(), "one step, the file: {chain}");
|
|
// Nothing above said a word to the user.
|
|
assert!(session.shown().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer() {
|
|
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
|
let (_tree, mut session, uri) = fast_path_session(pulling);
|
|
let report = session.result(
|
|
DocumentDiagnosticRequest::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
assert_eq!(report["items"], serde_json::json!([]), "{report}");
|
|
}
|
|
|
|
/// `workspace/diagnostic` walks every open buffer (`workspace_report`
|
|
/// above), a large one included — it is not skipped, it is present with
|
|
/// an empty **full** report, the same answer `diagnostics::all` gives
|
|
/// `textDocument/diagnostic`. Pinned because the workspace-scoped sweep is
|
|
/// a different code path from the per-document one already covered by
|
|
/// `a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer`.
|
|
#[test]
|
|
fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report() {
|
|
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
|
let (_tree, mut session, uri) = fast_path_session(pulling);
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
|
);
|
|
let items = report["items"].as_array().expect("items");
|
|
assert_eq!(items.len(), 1, "{report:#?}");
|
|
assert_eq!(items[0]["uri"].as_str(), Some(uri.as_str()));
|
|
assert_eq!(items[0]["kind"], "full", "present, not skipped: {report:#?}");
|
|
assert_eq!(items[0]["items"], serde_json::json!([]), "{report:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() {
|
|
let tree = Tree::new("largethreshold");
|
|
let path = tree.path.join("net.v");
|
|
tree.write("net.v", &big_source());
|
|
// Default settings: the buffer is nowhere near 4 MiB, so it is
|
|
// analyzed in full.
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&path, &big_source());
|
|
assert!(!session.server.workspace.document(&uri).expect("open").large);
|
|
|
|
// Pushed. The buffer already open does not change mode on the spot —
|
|
// the decision is taken where a document is built.
|
|
session.notify(
|
|
DidChangeConfiguration::METHOD,
|
|
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }),
|
|
);
|
|
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
|
assert!(
|
|
!session.server.workspace.document(&uri).expect("open").large,
|
|
"the open buffer keeps the mode it was built in"
|
|
);
|
|
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
|
assert!(
|
|
session.server.workspace.document(&uri).expect("open").large,
|
|
"and takes the fast path at its next change"
|
|
);
|
|
|
|
// Pulled: the same value through the other door.
|
|
let mut session = Session::with(
|
|
vec![tree.path.clone()],
|
|
ClientAbilities { configuration: true, ..Default::default() },
|
|
);
|
|
let (id, _) = configuration_request(&session);
|
|
session.answer(id, serde_json::json!([{ "largeFile": { "threshold": 100 } }]));
|
|
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
|
let uri = session.open(&path, &big_source());
|
|
assert!(session.server.workspace.document(&uri).expect("open").large);
|
|
}
|
|
|
|
#[test]
|
|
fn an_edit_to_a_large_buffer_moves_its_lines_and_the_next_window_agrees() {
|
|
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
|
// Insert a line at the top. `sig_a`'s declaration moves from line 1
|
|
// to line 2, which is only true if the line index was rebuilt.
|
|
session.notify(
|
|
DidChangeTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri, "version": 2 },
|
|
"contentChanges": [{
|
|
"range": {
|
|
"start": { "line": 0, "character": 0 },
|
|
"end": { "line": 0, "character": 0 },
|
|
},
|
|
"text": "// a new first line\n",
|
|
}],
|
|
}),
|
|
);
|
|
let data = session.result(
|
|
SemanticTokensRangeRequest::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"range": {
|
|
"start": { "line": 2, "character": 0 },
|
|
"end": { "line": 3, "character": 0 },
|
|
},
|
|
}),
|
|
);
|
|
let tokens = data["data"].as_array().expect("tokens");
|
|
assert_eq!(tokens[0], 2, "the window's own line, after the insertion");
|
|
let found = session.result(
|
|
GotoDefinition::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"position": { "line": 2, "character": 9 },
|
|
}),
|
|
);
|
|
assert_eq!(found[0]["range"]["start"]["line"], 2, "{found}");
|
|
}
|
|
}
|