Files
lucisv/crates/lucisv_server/src/server/tests/mod.rs
T
lucioandClaude Fable 5 b96827c51d Decomposition, lane C: lucisv_server's server.rs and completion.rs become modules, a pure move
TODO section 28, lane C (the file-size rule in CLAUDE.md).
server.rs (2 559 production + 6 293 test lines) becomes server/{mod,
dispatch, client, index, notification, progress, diagnostics, batch,
formatting, large_file, semantic_tokens}.rs with the tests in
server/tests/ (16 files, one per former banner section, 15 shared
helpers hoisted into the harness); completion.rs (1 716 + 2 463)
becomes completion/{mod, member, module, tiers, word, site,
harness}.rs with each provider's tests beside it. answer_request (393)
and handle_notification (197) stay whole as the dispatch tables they
are; perf.rs stays whole because its one sentence has no and. Every
import elsewhere in the crate resolves through pub(crate) re-exports,
so main.rs, inline.rs, instantiate.rs, hover.rs, nav.rs and state.rs
are byte-identical. Proof: per-binary counts identical (1 435 / 85 / 3;
workspace 3 215 / 48), e2e and the vsix smoke green, a live LSP session
against opentitan answering byte-identically from this build and the
base, and a line-multiset + signature census (360/360, 188/188) done
by the dev and redone from scratch by QA.

docs/features/decomposition-server/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:33:48 -07:00

556 lines
21 KiB
Rust

//! The `Server` tests: one file per feature, every one driven through the
//! real `process_batch` against a scratch workspace on disk.
//!
//! This file is the harness — `Tree`, a workspace root removed on drop, and
//! `Session`, a server on an in-memory connection whose every outgoing
//! message can be read back — followed by the helpers more than one file
//! uses. The sibling files are the sections the one big test module used to
//! have, under the names they had; a helper used by one section only stayed
//! with it.
use std::path::{Path, PathBuf};
use std::str::FromStr;
use lsp_server::{Notification, Request, Response};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
ShowMessageParams, WorkDoneProgress, WorkDoneProgressCreateParams,
};
use serde_json::Value;
use super::batch::{is_shutdown, widen_of, Widen};
use super::progress::{reports, MAX_REPORTS};
use super::*;
use crate::uri::path_to_uri;
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
mod apply_edit;
mod cancel;
mod file_ops;
mod folders;
mod formatting;
mod index;
mod large_file;
mod progress;
mod pull_diagnostics;
mod requests;
mod scan;
mod settings;
mod sync;
mod tokens;
mod watchers;
/// 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(&params.token)))
}
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams = serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
let step = match work {
WorkDoneProgress::Begin(_) => "begin",
WorkDoneProgress::Report(_) => "report",
WorkDoneProgress::End(_) => "end",
};
Some((step, token_text(&params.token)))
}
_ => None,
}
}
fn token_text(token: &ProgressToken) -> String {
match token {
ProgressToken::String(text) => text.clone(),
ProgressToken::Number(number) => number.to_string(),
}
}
/// A client that shows a progress bar and nothing else.
fn watching_progress() -> ClientAbilities {
ClientAbilities { work_done_progress: true, ..Default::default() }
}
// ----------------------------------------------------------------------
// helpers more than one file uses
// ----------------------------------------------------------------------
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";
/// 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()
}
/// 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 `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" } }
}
})
}
/// A client that pulls diagnostics rather than being pushed them.
fn pulling() -> ClientAbilities {
ClientAbilities { pull_diagnostics: true, ..Default::default() }
}
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,
}),
)
}
/// 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()
}
/// A `lucisv.filelist` push, in the shape a client sends it.
fn filelist_push(path: &str) -> Value {
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
}
/// 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() }
}
/// 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
}
/// 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)
}
/// 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 },
}),
)
}
/// 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())
}