TODO §71.7. Three server bugs, all older than this series. - A caret just past an identifier's last letter resolved the NEXT character (spans are end-exclusive): references, definition, hover and highlight came back empty where VS Code considers the caret on the word — the owner's 'not found, then works after clicking back'. lucisv_server/src/caret.rs; nine position-to-symbol requests use it through Server::symbol_offset; the References view opens a row with the caret at the name's start. - process_batch held requests during a scan but applied notifications at once, so a didChange could overtake an older one still queued; with incremental sync that corrupted the server's copy of the buffer until the file was reopened. Rule now: no notification overtakes an older unapplied notification (Server::must_hold, the 'behind' count for the burst a scan is nested in). Cancels wait whenever anything is held; responses never. - answer_what_is_waiting acted on a didOpen it had queued but not applied, re-holding the same batch at every file of the startup scan (~300-400 s on OpenTitan). Scan state now changes only where a message is applied; a held batch is handed back at most once per applied didOpen. An attempt to also drop excluded buffers from the index on close cost 190 ms per open of an outside file and was reverted after QA measured it. Dev (two rounds), QA (two rounds, own ordering driver: 9 118 bursts, no wrong text) and lead review: docs/features/scan-ordering/README.md. TODO.md files what stays open. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.8) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree including cross; lucisv_server 2030/0. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
649 lines
34 KiB
Rust
649 lines
34 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`.
|
|
//!
|
|
//! The server is one directory of modules, each the answer to one question;
|
|
//! this file holds the `Server` itself — what the client can do, what the
|
|
//! server owns, and the loop (`run`, `process_batch`, the order contract in
|
|
//! `must_wait`). The rest, in the order a message meets them:
|
|
//!
|
|
//! * `batch` — reading a burst before any of it is served: the forwarder
|
|
//! thread, the drain, the cancels a burst carries, the `didOpen`s that widen
|
|
//! the scope;
|
|
//! * `dispatch` — `answer_request`, the table over request methods, with the
|
|
//! decoding it needs and the `Failure` it answers in;
|
|
//! * `large_file` — what a buffer over the large-file threshold answers
|
|
//! instead of the dispatch;
|
|
//! * `formatting` — the five formatting entries and how a refusal is said;
|
|
//! * `semantic_tokens` — the remembered answer a token delta is computed
|
|
//! against;
|
|
//! * `diagnostics` — when a buffer is analyzed (the change debounce) and how
|
|
//! what it says reaches the client, pushed or pulled;
|
|
//! * `notification` — `handle_notification`, the table over notification
|
|
//! methods, and the settings applier both settings doors share;
|
|
//! * `index` — the rescans: whole, one file, widened, and the scan that
|
|
//! answers messages while it runs;
|
|
//! * `progress` — the indexing bar and the per-file log a rescan runs under;
|
|
//! * `client` — what goes to the client other than a response: the requests
|
|
//! made of it and the answers read back, the messages, the timing lines.
|
|
//!
|
|
//! Methods a sibling file calls are `pub(super)`; everything else is private
|
|
//! to its file. The tests are in `tests/`, one file per feature.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::error::Error;
|
|
|
|
use lsp_server::{Connection, Message, RequestId};
|
|
use lsp_types::notification::{Cancel, Notification as _};
|
|
use lsp_types::{SemanticToken, Uri};
|
|
|
|
use crate::state::Workspace;
|
|
|
|
use batch::{burst, cancelled_id, cancelled_in, cancelled_response, changes_state};
|
|
use dispatch::names_nowhere;
|
|
|
|
mod batch;
|
|
mod client;
|
|
mod diagnostics;
|
|
mod dispatch;
|
|
mod formatting;
|
|
mod index;
|
|
mod large_file;
|
|
mod notification;
|
|
#[cfg(test)]
|
|
mod probe;
|
|
mod progress;
|
|
mod semantic_tokens;
|
|
mod startup;
|
|
#[cfg(test)]
|
|
mod tests;
|
|
|
|
/// 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 accepts a `workspace/diagnostic/refresh` — what
|
|
/// makes a pulling client pull again when a connection entry held back
|
|
/// while it was typed is released
|
|
/// (`docs/features/port-entry-grace/README.md`). A client that said
|
|
/// nothing sees the release at its own next pull.
|
|
pub diagnostic_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,
|
|
/// Whether the client can fetch a code action's `edit` through
|
|
/// `codeAction/resolve` — `textDocument.codeAction.resolveSupport`
|
|
/// listing `"edit"`. Only then are the port refactorings *offered* without
|
|
/// their edits; a client that said nothing gets the whole edit up front,
|
|
/// which is what every client got before this was read
|
|
/// (`docs/features/lazy-code-action/README.md`).
|
|
pub code_action_resolve: bool,
|
|
/// Whether the client can apply a `WorkspaceEdit` that creates a file —
|
|
/// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations`
|
|
/// list containing `create`. Only then does an extracted module get a
|
|
/// file of its own; a client that said nothing gets it written below the
|
|
/// module it came from
|
|
/// (`docs/features/extract-inline-module/README.md`).
|
|
pub create_files: 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>,
|
|
/// The preset `style = "auto"` last settled on for each recently
|
|
/// formatted document, so range, selection and on-type requests neither
|
|
/// search every preset again nor lose the file's preset while the buffer
|
|
/// does not parse (`auto_style.rs`).
|
|
auto_styles: crate::auto_style::AutoStyles,
|
|
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
|
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
|
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
|
/// open buffers — and the memo is the one thing a pass has to write.
|
|
/// Nothing is called while it is borrowed.
|
|
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
|
|
/// The unknown-rule-name lines already logged for the **editor's**
|
|
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
|
|
/// value produced them. A client that re-pushes the same section — VS Code
|
|
/// does, whenever anything in it changes — says nothing again; a list the
|
|
/// user edited re-arms every name that is new to it. The project file's
|
|
/// twin memo is `lint_config_problems` above.
|
|
said_lint_names: Vec<String>,
|
|
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,
|
|
/// Whether the startup scan is still *owed* — the window between the
|
|
/// `workspace/configuration` request that opens a session and the answer
|
|
/// that decides the scope its one scan runs at
|
|
/// (`server/startup.rs`). Nothing has been indexed yet, so a rescan
|
|
/// trigger in this window is folded into the scan that is about to run
|
|
/// rather than run as a scan of its own, and every request waits for it —
|
|
/// there is nothing to answer one from. Never true again after
|
|
/// construction.
|
|
staging: bool,
|
|
/// Whether the scan now running still owes the user's own neighbourhood —
|
|
/// their open buffers and the folders those raise to, which
|
|
/// [`crate::scan_order`] puts at the head of its work list. Until it has
|
|
/// been indexed there is nothing worth answering a request off: the prefix
|
|
/// holds the alphabet rather than what the user is looking at, and §P4b2
|
|
/// measured what that answers, which is `[]`
|
|
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
|
|
/// running, and false during a scan with no neighbourhood to wait for.
|
|
head_owed: bool,
|
|
/// Whether a `didOpen` was **applied** while the scan now running had
|
|
/// messages to answer — set where the `didOpen` is applied, and read by
|
|
/// that scan's drain once the batch carrying it has been handled. Never
|
|
/// read off a batch, which may hold the `didOpen` unapplied behind a
|
|
/// request (`docs/features/scan-ordering/README.md`, C).
|
|
opened_mid_scan: 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>,
|
|
/// How many notifications older than the message being handled are still
|
|
/// unapplied in the bursts it is nested inside — the tail of a burst
|
|
/// whose message started a scan, while that scan answers newer ones. One
|
|
/// of the two places an older notification can wait; `held` is the other
|
|
/// ([`Server::must_hold`]). Cancels are not counted: they change nothing.
|
|
behind: usize,
|
|
/// Navigation requests a scan answered **empty** while it was still
|
|
/// growing the index, to be asked again at its next publish.
|
|
///
|
|
/// **Not a second `held`, and deliberately not part of
|
|
/// [`Server::must_wait`].** A held request is one the order contract says
|
|
/// nothing newer may overtake; this is one whose answer was computed,
|
|
/// found to name nowhere, and set aside because the reason it named
|
|
/// nowhere may be that the file it wants has not been scanned yet
|
|
/// (`docs/features/perf5r-publication/README.md`). Nothing else is owed
|
|
/// anything by it — a hover, a completion or a code action behind one is
|
|
/// answered exactly as before — and it is asked again at most once per
|
|
/// publish, so the re-computation is bounded by the cadence and not by the
|
|
/// scan's file count. A scan ending runs whatever is left through the
|
|
/// dispatch one last time, with itself already over — so nothing is
|
|
/// deferred that time round and an empty answer, which is now the honest
|
|
/// one, goes out ([`Server::answer_what_was_deferred`]).
|
|
deferred: 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,
|
|
/// When this server was built — the moment after `initialize`/`initialized`
|
|
/// that `main` hands control over. Every startup number is measured from
|
|
/// here, so a scan's line can say how much of the wait came before it
|
|
/// (`docs/features/perf5-p4/README.md`).
|
|
born: std::time::Instant,
|
|
}
|
|
|
|
/// 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;
|
|
|
|
/// 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, and when
|
|
/// it was asked — the config round trip is part of what a startup costs.
|
|
Configuration(std::time::Instant),
|
|
}
|
|
|
|
/// 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 {
|
|
/// 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. The
|
|
/// same wake-up releases a connection entry whose diagnostics were held
|
|
/// back while it was typed, once its grace has run out.
|
|
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;
|
|
}
|
|
// A connection entry whose grace ran out while messages kept
|
|
// arriving is released here, not only when the wait below times
|
|
// out (`docs/features/port-entry-grace/README.md`).
|
|
self.release_port_entries();
|
|
let message = match self.quiet_wait() {
|
|
None => match self.queue.recv() {
|
|
Ok(message) => message,
|
|
Err(_) => return Ok(()),
|
|
},
|
|
Some(wait) => match self.queue.recv_timeout(wait) {
|
|
Ok(message) => message,
|
|
Err(RecvTimeoutError::Timeout) => {
|
|
self.flush_dirty();
|
|
self.release_port_entries();
|
|
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();
|
|
// The bursts this one is nested inside, and the notifications of them
|
|
// still unapplied; restored on the way out (an `Err` is a client that
|
|
// has gone, and nothing reads this after it).
|
|
let outer = self.behind;
|
|
let mut unapplied = batch.iter().filter(|m| changes_state(m)).count();
|
|
let mut messages = batch.into_iter();
|
|
while let Some(message) = messages.next() {
|
|
// What is unapplied *older* than this message is only ever in the
|
|
// bursts around this one — the rest of this burst is newer.
|
|
self.behind = outer;
|
|
// A message 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_hold(&message) {
|
|
self.cancel_deferred(&message)?;
|
|
self.say_held(&message);
|
|
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
|
|
rest.push(message);
|
|
rest.extend(messages);
|
|
self.hold(rest, already_waiting);
|
|
return Ok(false);
|
|
}
|
|
unapplied -= usize::from(changes_state(&message));
|
|
// Whatever this message starts — a scan, whose drain answers the
|
|
// client's newer messages — runs with the rest of this burst's
|
|
// notifications still unapplied, and newer ones must not overtake
|
|
// them.
|
|
self.behind = outer + unapplied;
|
|
match message {
|
|
Message::Request(request) => {
|
|
if self.connection.handle_shutdown(&request)? {
|
|
self.behind = outer;
|
|
return Ok(true);
|
|
}
|
|
self.answer_from_batch(request, &mut cancelled)?;
|
|
}
|
|
// 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 => {
|
|
let cancel = Message::Notification(notification);
|
|
// A request the empty-answer rule set aside is not in this
|
|
// burst, so `cancelled_in` cannot see it — but it is still
|
|
// a request the client is waiting on, and a cancel for it
|
|
// is honoured where it lands: answered `RequestCancelled`
|
|
// now, and never asked again (QA, perf5r-publication).
|
|
self.cancel_deferred(&cancel)?;
|
|
consumed_cancels.push(cancel);
|
|
}
|
|
Message::Notification(notification) => self.notification(notification),
|
|
Message::Response(response) => self.response(response),
|
|
}
|
|
}
|
|
self.behind = outer;
|
|
Ok(false)
|
|
}
|
|
|
|
/// Answer one request a burst carried: `RequestCancelled` when the burst
|
|
/// also carried its cancel, set aside for the next publish when it is a
|
|
/// navigation request the scan has not reached the answer to yet, and
|
|
/// computed otherwise.
|
|
fn answer_from_batch(
|
|
&mut self,
|
|
request: lsp_server::Request,
|
|
cancelled: &mut HashSet<RequestId>,
|
|
) -> Result<(), Box<dyn Error + Sync + Send>> {
|
|
// 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 {
|
|
// A navigation request whose answer would be `[]` only because
|
|
// the scan has not reached its target yet is asked again at the
|
|
// next publish rather than answered with nowhere
|
|
// ([`Server::deferred`]).
|
|
let again = self.ask_again_if_empty(&request);
|
|
let response = self.request(request);
|
|
if let Some(request) = again.filter(|_| names_nowhere(&response)) {
|
|
self.say_deferred(&request);
|
|
self.deferred.push(Message::Request(request));
|
|
return Ok(());
|
|
}
|
|
response
|
|
};
|
|
self.connection.sender.send(Message::Response(response))?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Put `rest` — the cancels the burst already carried, the message that
|
|
/// must wait, and the rest of its burst, in that order — into `held`: in
|
|
/// front of whatever a scan this burst started has held since
|
|
/// `already_waiting`, behind everything older. The cancels go back in
|
|
/// front of what they cancel because `cancelled_in` runs again over the
|
|
/// held batch; one naming nothing in it is dropped there, as it would
|
|
/// have been here.
|
|
fn hold(&mut self, mut rest: Vec<Message>, already_waiting: usize) {
|
|
rest.extend(self.held.split_off(already_waiting));
|
|
self.held.extend(rest);
|
|
}
|
|
|
|
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
|
|
/// take it out and answer it cancelled. A cancel naming anything else is
|
|
/// left to the batch's own rule.
|
|
fn cancel_deferred(&mut self, cancel: &Message) -> Result<(), Box<dyn Error + Sync + Send>> {
|
|
let Some(id) = cancelled_id(cancel) else { return Ok(()) };
|
|
let found = self
|
|
.deferred
|
|
.iter()
|
|
.position(|message| matches!(message, Message::Request(request) if request.id == id));
|
|
if let Some(at) = found {
|
|
self.deferred.remove(at);
|
|
self.connection.sender.send(Message::Response(cancelled_response(id)))?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// 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. Four 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;
|
|
/// * `staging` — the startup scan has not begun, because the settings
|
|
/// that decide its scope are still in flight. There is no index at all
|
|
/// to answer from, so a request waits for that scan — and is answered
|
|
/// *inside* it, mid-way, exactly as one arriving while it runs is
|
|
/// ([`Server::waiting_for_this_scan`]);
|
|
/// * `head_owed` — the scan running has not yet reached the end of the
|
|
/// user's own folder. There *is* an index, but the part of it a request
|
|
/// is asking about is the part not built yet, and answering off the
|
|
/// alphabet's prefix returns `[]` rather than an answer. A request
|
|
/// behind a `didOpen` is owed that `didOpen`'s effect on the scan
|
|
/// order, which is the same rule the other four state
|
|
/// ([`Server::head_owed`]).
|
|
///
|
|
/// 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()
|
|
|| self.staging
|
|
|| self.head_owed
|
|
}
|
|
|
|
/// Whether `message`, reaching `process_batch` right now, must be held
|
|
/// instead of handled.
|
|
///
|
|
/// **No notification overtakes an older notification.** Only a
|
|
/// notification changes what the server holds — a buffer's text, which
|
|
/// buffers are open, the settings, the folders, what is on disk — so the
|
|
/// order those are applied in is the order they were sent in, and nothing
|
|
/// a request is later answered against can be a state the client never
|
|
/// had. A notification waits while an older one is unapplied: in `held`,
|
|
/// or in the tail of a burst whose message started the scan now draining
|
|
/// ([`Server::behind`]). Before 2026-11-19 a `didChange` drained mid-scan
|
|
/// was applied ahead of an older `didChange` still waiting, and an
|
|
/// incremental edit landed on the wrong text
|
|
/// (`docs/features/scan-ordering/README.md`, B).
|
|
///
|
|
/// **Not "no notification overtakes a request".** A request held by the
|
|
/// contract above is answered against whatever was applied by the time
|
|
/// it is replayed — as every request answered late always was — and a
|
|
/// notification behind it with nothing older unapplied is applied at
|
|
/// once. Holding it too would cost the startup its first `didOpen`
|
|
/// (QA-3) and buy no state the client could see.
|
|
///
|
|
/// A **cancel** changes nothing the server holds, so it never makes a
|
|
/// notification wait; it waits itself whenever anything is held, so that
|
|
/// one naming a held request is replayed beside it and honoured. A
|
|
/// **response** is never held: it answers a request the server made, and
|
|
/// no ordering promise ties it to the editor's stream
|
|
/// (`take_the_answer_out_of_held` in `startup.rs` makes the same
|
|
/// argument).
|
|
fn must_hold(&self, message: &Message) -> bool {
|
|
match message {
|
|
Message::Request(_) => self.must_wait(),
|
|
Message::Notification(_) if !changes_state(message) => !self.held.is_empty(),
|
|
Message::Notification(_) => self.behind > 0 || self.held.iter().any(changes_state),
|
|
Message::Response(_) => false,
|
|
}
|
|
}
|
|
|
|
/// Whether a scan is running or already owed — the two states in which a
|
|
/// rescan trigger records that one more scan is wanted instead of running
|
|
/// one itself.
|
|
///
|
|
/// The second is the startup's configuration wait (`server/startup.rs`):
|
|
/// the scan it is waiting for has not begun, and when it does it will
|
|
/// resolve the scope afresh and read every file in it, so anything asked
|
|
/// for now is satisfied by it.
|
|
fn scan_owed(&self) -> bool {
|
|
self.scanning || self.staging
|
|
}
|
|
|
|
/// 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()
|
|
}
|
|
}
|