Parser (tolerant mode only, parser/recover_list.rs): a lone '.', a
'.name(' left open at its line end and a trailing ',' in a named list are
recovered inside their entry — always a diagnostic, never silent; strict
mode and valid code are unchanged (1 026 inputs old vs new: identical
strict results and trees, byte-identical CLI output; corpus 814/6).
Server (state/port_grace.rs): diagnostics that start inside the entry the
last edit touched, in a named-connection list of an instance, are withheld
for 1.5 s and released by the loop's timeout, an edit elsewhere or a save;
a pulling client that supports it gets workspace/diagnostic/refresh.
A trailing ',' in a named list is now reported in tolerant mode too.
Dev + QA (Opus 5.5); QA failed one gate (lucisv_mcp qa_f1), one fix
round, re-check passed: parser 521, server 1954, mcp 383, formatter 352.
Not yet seen in a running VS Code. docs/features/port-entry-grace; topo
rows for §68.1 and §68.2.
Co-Authored-By: Claude Mythos 5.2 <[email protected]>
1420 lines
66 KiB
Rust
1420 lines
66 KiB
Rust
//! `lucisv-server` — the lucisv language server, speaking LSP over stdio.
|
|
//!
|
|
//! One binary for every editor: VS Code through a thin extension, Vim/Neovim
|
|
//! through built-in LSP config. No editor-specific logic lives below the
|
|
//! protocol layer, and no language logic lives in it — every answer comes from
|
|
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
|
|
//! `docs/features/lucisv-server/README.md`.
|
|
|
|
mod candidates;
|
|
mod code_action;
|
|
mod completion;
|
|
mod convert;
|
|
mod design_hierarchy;
|
|
mod diagnostics;
|
|
mod expand;
|
|
mod extract;
|
|
mod fences;
|
|
mod file_ops;
|
|
mod folding;
|
|
mod format;
|
|
mod hierarchy;
|
|
mod hover;
|
|
mod imports;
|
|
mod includes;
|
|
mod index_cache;
|
|
mod inlay;
|
|
mod inline;
|
|
mod inline_module;
|
|
mod instantiate;
|
|
mod large;
|
|
mod lens;
|
|
mod linked;
|
|
mod lint;
|
|
mod lint_snapshot;
|
|
mod lint_trace;
|
|
mod locate;
|
|
mod module_select;
|
|
mod nav;
|
|
mod on_type;
|
|
mod pairs;
|
|
#[cfg(test)]
|
|
mod perf;
|
|
mod ports;
|
|
mod rename;
|
|
mod rename_trace;
|
|
mod scan_order;
|
|
mod scan_trace;
|
|
mod selection;
|
|
mod server;
|
|
mod settings;
|
|
mod signature;
|
|
mod state;
|
|
mod symbols;
|
|
mod sync;
|
|
mod templates;
|
|
mod tokens;
|
|
mod type_def;
|
|
mod type_hierarchy;
|
|
mod uri;
|
|
mod watch;
|
|
|
|
use std::error::Error;
|
|
use std::path::PathBuf;
|
|
|
|
use lsp_server::Connection;
|
|
use lsp_types::{
|
|
CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability,
|
|
CodeLensOptions, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities,
|
|
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
|
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
|
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
|
RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability,
|
|
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
|
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
|
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
|
|
TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions,
|
|
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
|
};
|
|
|
|
use vlog_parser::PARSE_STACK_SIZE;
|
|
|
|
use crate::server::{ClientAbilities, Server};
|
|
use crate::uri::uri_to_path;
|
|
|
|
/// The one flag this binary takes: per-operation timing lines in the client's
|
|
/// log channel. One spelling, no `-v` — see
|
|
/// `docs/features/verbose-timing/README.md`.
|
|
const VERBOSE: &str = "--verbose";
|
|
/// `vscode-languageclient` (and other LSP clients) append `--stdio` to the
|
|
/// spawn when the transport is stdio — the only transport this server has.
|
|
/// Accepted as the statement of fact it is; rejecting it turned out to crash
|
|
/// every real VS Code session the moment strict argument parsing shipped
|
|
/// (lead hotfix, 2026-08-29 — the smoke and restart harnesses spawn the
|
|
/// binary directly, so nothing in the loop exercised the library's spawn).
|
|
const STDIO: &str = "--stdio";
|
|
|
|
/// What someone who spelled an argument wrong is told, on stderr. One line:
|
|
/// this binary is spawned by an editor, not typed at a prompt.
|
|
const USAGE: &str = "usage: lucisv-server [--verbose] [--stdio]";
|
|
|
|
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
|
// Before the transport: an argument we do not understand means the client
|
|
// asked for something we are not doing, and answering LSP anyway would
|
|
// hide that for the whole session.
|
|
let verbose = match verbose_flag(std::env::args().skip(1)) {
|
|
Ok(verbose) => verbose,
|
|
Err(unknown) => {
|
|
eprintln!("error: unknown option: {unknown}");
|
|
eprintln!("{USAGE}");
|
|
std::process::exit(2);
|
|
}
|
|
};
|
|
let (connection, io_threads) = Connection::stdio();
|
|
|
|
let (id, params) = connection.initialize_start()?;
|
|
// Read before the typed decode, because `lsp-types` 0.97's client
|
|
// capabilities have no field for it and drop it on the floor — see
|
|
// `ranges_formatting_support`.
|
|
let ranges_formatting = ranges_formatting_support(¶ms);
|
|
let diagnostic_refresh = diagnostic_refresh_support(¶ms);
|
|
// Read from the raw params for the same reason, and because it is not a
|
|
// capability at all: `initializationOptions` is whatever the client's
|
|
// extension put there.
|
|
let storage = storage_path(¶ms);
|
|
let hierarchy_view = hierarchy_view_support(¶ms);
|
|
// A client that sends params we cannot read still gets a server; every
|
|
// field we want is optional anyway.
|
|
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
|
|
let roots = workspace_roots(¶ms);
|
|
let abilities = ClientAbilities {
|
|
snippets: snippet_support(¶ms),
|
|
file_watching: watch::dynamic_registration(¶ms),
|
|
apply_edit: apply_edit_support(¶ms),
|
|
pull_diagnostics: pull_diagnostics_support(¶ms),
|
|
work_done_progress: work_done_progress_support(¶ms),
|
|
code_lens_refresh: code_lens_refresh_support(¶ms),
|
|
diagnostic_refresh,
|
|
show_document: show_document_support(¶ms),
|
|
configuration: configuration_support(¶ms),
|
|
token_server_cancel: token_server_cancel_support(¶ms),
|
|
hierarchy_view,
|
|
code_action_resolve: code_action_resolve_support(¶ms),
|
|
create_files: create_files_support(¶ms),
|
|
};
|
|
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
|
|
|
// The message loop parses every buffer it is handed, so it does not run
|
|
// on the main thread: that stack is whatever the OS and `ulimit -s` left
|
|
// it, and the parser's nesting limit only turns over-deep input into a
|
|
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
|
|
// whole server, taking the editor session with it). Nothing else here
|
|
// parses — `lsp-server`'s reader and writer threads move JSON, and the
|
|
// forwarder in `Server::queue` moves messages.
|
|
std::thread::Builder::new()
|
|
.name("lucisv-main".to_string())
|
|
.stack_size(PARSE_STACK_SIZE)
|
|
.spawn(move || Server::new(connection, roots, abilities, storage, verbose).run())?
|
|
.join()
|
|
.map_err(|_| "the server thread panicked")??;
|
|
io_threads.join()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Whether the arguments ask for verbose timing, or the first argument this
|
|
/// binary does not take.
|
|
///
|
|
/// Refused rather than ignored: a client that spawns `lucisv-server --verbos`
|
|
/// would otherwise get a whole session of silence and no way to tell it from a
|
|
/// flag that does not work. Repeating the flag is not an error — it says the
|
|
/// same thing twice — and no argument at all is the spawn every editor has
|
|
/// always used.
|
|
fn verbose_flag(args: impl Iterator<Item = String>) -> Result<bool, String> {
|
|
let mut verbose = false;
|
|
for arg in args {
|
|
if arg == STDIO {
|
|
continue;
|
|
}
|
|
if arg != VERBOSE {
|
|
return Err(arg);
|
|
}
|
|
verbose = true;
|
|
}
|
|
Ok(verbose)
|
|
}
|
|
|
|
/// What the server tells the client it can do. Nothing is advertised that is
|
|
/// not implemented: a capability an editor discovers to be a lie is worse than
|
|
/// one it never had.
|
|
fn capabilities() -> ServerCapabilities {
|
|
ServerCapabilities {
|
|
// The protocol default, and what the conversion in `convert.rs`
|
|
// implements. Stated rather than left implicit.
|
|
position_encoding: Some(PositionEncodingKind::UTF16),
|
|
// Incremental sync: a keystroke costs one range, not the whole file.
|
|
// Spelled out as options rather than a bare kind because a bare kind
|
|
// says nothing about open/close or save, and clients fill that in
|
|
// themselves — this states the same defaults a bare kind resolved to,
|
|
// so nothing but `change` moves. `includeText: false` keeps a save
|
|
// from re-sending a buffer the server already tracks edit by edit;
|
|
// the `didSave` handler still honours text if a client sends it.
|
|
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
|
|
open_close: Some(true),
|
|
change: Some(TextDocumentSyncKind::INCREMENTAL),
|
|
// The plain `willSave` notification carries nothing this server
|
|
// can act on, so it is left unadvertised; `willSaveWaitUntil` is
|
|
// the format-on-save hook, for the editors that have no
|
|
// format-on-save of their own. It answers `null` unless
|
|
// `lucisv.formatOnSave` is on — see
|
|
// `docs/features/will-save-wait-until/README.md`.
|
|
will_save: None,
|
|
will_save_wait_until: Some(true),
|
|
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
|
|
include_text: Some(false),
|
|
})),
|
|
})),
|
|
document_formatting_provider: Some(OneOf::Left(true)),
|
|
document_range_formatting_provider: Some(OneOf::Left(true)),
|
|
// Two trigger characters, and only two. A newline re-indents the line
|
|
// it opened; a `;` lays out the statement it ended, through the range
|
|
// engine. Not `}` — SV closes its blocks with the *word* `end`, and
|
|
// re-triggering on letters would run this on half of every identifier.
|
|
// Advertised unconditionally: on-type formatting only fires where the
|
|
// client's own `editor.formatOnType` is on, which is off by default,
|
|
// so the user has already opted in by the time a request arrives. See
|
|
// `docs/features/on-type-formatting/README.md`.
|
|
document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
|
|
first_trigger_character: on_type::NEWLINE.to_string(),
|
|
more_trigger_character: Some(vec![on_type::SEMICOLON.to_string()]),
|
|
}),
|
|
definition_provider: Some(OneOf::Left(true)),
|
|
// The same jump one token to the left: from a name to where its type
|
|
// is declared. `Simple(true)` rather than a registration — there is
|
|
// nothing to scope it to that `definitionProvider` is not already
|
|
// scoped to. See `docs/features/type-definition/README.md`.
|
|
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
|
|
// SV's closing labels, edited as one name: `module m` and
|
|
// `endmodule : m` change together. `Simple(true)` rather than a
|
|
// registration — there is nothing to scope it to, and the handler
|
|
// declines every position that is not one of the two names. See
|
|
// `docs/features/linked-editing/README.md`.
|
|
linked_editing_range_provider: Some(LinkedEditingRangeServerCapabilities::Simple(true)),
|
|
references_provider: Some(OneOf::Left(true)),
|
|
// `` `include`` lines, underlined and ctrl-clickable. Every link is
|
|
// returned with its target already resolved, so there is nothing for
|
|
// `documentLink/resolve` to do — and go-to-definition answers the same
|
|
// lines, for the editors that have no ctrl-click.
|
|
document_link_provider: Some(DocumentLinkOptions {
|
|
resolve_provider: Some(false),
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
}),
|
|
// The cursor on a `begin` highlights its own `end`, matched over the
|
|
// token stream; anywhere else, the symbol under it highlights its own
|
|
// other occurrences in this file. The handler declines a position
|
|
// that is neither, which leaves the editor's word highlighting in
|
|
// charge there.
|
|
document_highlight_provider: Some(OneOf::Left(true)),
|
|
// One range per matched scope pair and per multi-line block comment,
|
|
// off the same matcher the rainbow reads.
|
|
folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
|
|
hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
|
|
document_symbol_provider: Some(OneOf::Left(true)),
|
|
workspace_symbol_provider: Some(OneOf::Left(true)),
|
|
// `prepareProvider` is what stops an editor from offering a rename the
|
|
// engine would refuse: the client asks first, and a refusal there costs
|
|
// the user nothing.
|
|
rename_provider: Some(OneOf::Right(RenameOptions {
|
|
prepare_provider: Some(true),
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
})),
|
|
// The kinds are listed rather than `Simple(true)` so a client can ask
|
|
// for one of them alone — which is how fix-on-save is configured.
|
|
code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
|
|
code_action_kinds: Some(vec![
|
|
CodeActionKind::QUICKFIX,
|
|
CodeActionKind::new(code_action::FIX_ALL),
|
|
CodeActionKind::new(ports::REFACTOR_PORTS),
|
|
imports::kind(),
|
|
extract::kind(),
|
|
inline_module::kind(),
|
|
]),
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
// The quick fixes are complete when they are offered; the port
|
|
// refactorings are not, for a client that can ask
|
|
// (`docs/features/lazy-code-action/README.md`). Advertised
|
|
// unconditionally because the server can always answer a resolve
|
|
// — including for an action that already carries its edit, which
|
|
// it hands straight back.
|
|
resolve_provider: Some(true),
|
|
})),
|
|
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
|
// the user, which no code action can carry, and a Vim user has no
|
|
// lightbulb at all — so all three are commands as well. The code
|
|
// lens's own jump joins them: a lens carries a `Command`, and this is
|
|
// where a command has to be declared to be runnable.
|
|
execute_command_provider: Some(ExecuteCommandOptions {
|
|
commands: commands(),
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
}),
|
|
// "N instantiations" over every module and interface declaration in
|
|
// the buffer, counted across the workspace. Every lens is returned
|
|
// complete — title, command and arguments — so there is nothing for
|
|
// `codeLens/resolve` to do, which is said out loud rather than left
|
|
// unset. See `docs/features/code-lens/README.md`.
|
|
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }),
|
|
// Names, templates and — since 2026-09-02 — members. An identifier
|
|
// being typed asks for the first two on its own, with no trigger
|
|
// needed; a **member** list has no identifier to be asked by, because
|
|
// the user has typed a separator and nothing after it yet. So `.` and
|
|
// `:` are advertised, and nothing else: they are the two bytes that
|
|
// can turn the cursor into a member position.
|
|
//
|
|
// The trigger is a *prompt*, never an instruction. The handler reads
|
|
// the buffer and decides — `server.rs` discards the request's
|
|
// `context` — so a `.` in a connection list, a lone `:` of a case
|
|
// item and a `::` after nothing readable all answer exactly what they
|
|
// would have answered had the user pressed the key themselves. See
|
|
// `docs/features/member-completion/README.md`.
|
|
completion_provider: Some(CompletionOptions {
|
|
// Every item is returned complete — skeleton, documentation and
|
|
// all — so there is nothing for `completionItem/resolve` to do.
|
|
resolve_provider: None,
|
|
trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
|
|
all_commit_characters: None,
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
completion_item: None,
|
|
}),
|
|
// `(` opens a connection or parameter list and `,` moves to the next
|
|
// entry; between them they cover every place the ports are worth
|
|
// showing.
|
|
signature_help_provider: Some(SignatureHelpOptions {
|
|
trigger_characters: Some(
|
|
signature::TRIGGERS.iter().map(|t| (*t).to_string()).collect(),
|
|
),
|
|
retrigger_characters: None,
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
}),
|
|
// Port and parameter names on ordered connection lists. Every hint is
|
|
// returned complete — a label, a position and nothing to fetch later —
|
|
// so there is no `inlayHint/resolve`.
|
|
inlay_hint_provider: Some(OneOf::Right(InlayHintServerCapabilities::Options(
|
|
InlayHintOptions {
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
resolve_provider: None,
|
|
},
|
|
))),
|
|
// The module hierarchy, both directions: modules are the nodes and an
|
|
// instantiation is the call. Every item is complete when it is
|
|
// returned, and the client drives the expansion one hop at a time.
|
|
call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
|
|
// Ghost text for `if (` and `begin`, LSP 3.18. `true` rather than
|
|
// options: there is nothing to configure on the server side, and the
|
|
// one thing a user can say — `lucisv.inlineTemplates` — is a setting the
|
|
// handler reads, not a registration option. The VS Code client only
|
|
// sends the request after opting into `ProposedFeatures`, so an
|
|
// extension older than this server simply never asks.
|
|
inline_completion_provider: Some(OneOf::Left(true)),
|
|
// Expand-selection. Nothing to configure: the chain is computed from
|
|
// the buffer alone, and every position is answered.
|
|
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
|
|
// Pull diagnostics (3.17), served from the same parse+lint pass the
|
|
// push model publishes. `inter_file_dependencies` because a save
|
|
// rebuilds the workspace index and *that* changes what other files
|
|
// report; `workspace_diagnostics` because `workspace/diagnostic` is
|
|
// answered — over the open buffers, which is the only scope this
|
|
// server has ever diagnosed.
|
|
diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
|
|
identifier: Some(diagnostics::SOURCE.to_string()),
|
|
inter_file_dependencies: true,
|
|
workspace_diagnostics: true,
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
})),
|
|
// File operations (3.16): renaming a header rewrites the
|
|
// `` `include``s that resolve to it, and a rename or a delete nudges
|
|
// the index without waiting for the watcher round-trip. Advertised
|
|
// unconditionally — unlike the watchers, nothing here is
|
|
// server-initiated, so a client that cannot send these requests simply
|
|
// never sends them and the capability costs it nothing. See
|
|
// `docs/features/file-operations/README.md`.
|
|
workspace: Some(WorkspaceServerCapabilities {
|
|
// Workspace folders, added and removed mid-session. Both halves
|
|
// are needed and neither implies the other: `supported` says the
|
|
// server understands a multi-folder workspace at all, and
|
|
// `changeNotifications` is what makes the client *send*
|
|
// `didChangeWorkspaceFolders`. `Left(true)` rather than an id —
|
|
// the string form exists so the registration can later be undone
|
|
// by name, and this server never unregisters it. See
|
|
// `docs/features/folders-and-config/README.md`.
|
|
workspace_folders: Some(WorkspaceFoldersServerCapabilities {
|
|
supported: Some(true),
|
|
change_notifications: Some(OneOf::Left(true)),
|
|
}),
|
|
file_operations: Some(file_ops::file_operations()),
|
|
}),
|
|
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
|
|
SemanticTokensOptions {
|
|
work_done_progress_options: WorkDoneProgressOptions::default(),
|
|
legend: SemanticTokensLegend {
|
|
token_types: tokens::token_types(),
|
|
token_modifiers: tokens::token_modifiers(),
|
|
},
|
|
// The visible lines, for the first paint of a large file:
|
|
// the same tokenizer, filtered, and re-encoded from the
|
|
// start of the document so the answer stands on its own.
|
|
range: Some(true),
|
|
// `delta: true` rather than a bare `full: true`, so a client
|
|
// that has an answer already asks what changed instead of
|
|
// re-fetching the file's whole token set on every keystroke.
|
|
// `full` itself stays served — the enum's `Delta` variant is
|
|
// the full capability plus deltas, not a replacement.
|
|
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
|
|
},
|
|
)),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Every command this server executes: the port refactorings, organize
|
|
/// imports, the instantiation skeleton, and the jump the code lens hangs off.
|
|
fn commands() -> Vec<String> {
|
|
let mut commands = ports::commands();
|
|
commands.extend(imports::commands());
|
|
commands.extend(extract::commands());
|
|
commands.extend(inline_module::commands());
|
|
commands.extend(instantiate::commands());
|
|
commands.extend(lens::commands());
|
|
commands
|
|
}
|
|
|
|
/// The `initialize` result exactly as it goes on the wire.
|
|
///
|
|
/// Two capabilities are written in here rather than in [`capabilities`],
|
|
/// because `lsp-types` 0.97 cannot spell either:
|
|
///
|
|
/// * **`typeHierarchyProvider`** — the crate models type hierarchy on the
|
|
/// *client* side only, so `ServerCapabilities` has no field for it, and
|
|
/// `experimental` is a different key that no client reads for this.
|
|
/// * **`documentRangeFormattingProvider`** widened to
|
|
/// `{ "rangesSupport": true }` when `ranges_formatting` — the crate's
|
|
/// `DocumentRangeFormattingOptions` carries only `workDoneProgress`. This is
|
|
/// the spec's own `boolean | DocumentRangeFormattingOptions` union, so the
|
|
/// object form is legal for any client; it is sent only to a client that
|
|
/// asked because the bare `true` is the shape no client can misread, and a
|
|
/// client that did not ask will never send the request anyway. See
|
|
/// `docs/features/lsp-318-extras/README.md`.
|
|
///
|
|
/// Both are the same JSON a field would have produced.
|
|
fn initialize_value(ranges_formatting: bool) -> Result<serde_json::Value, serde_json::Error> {
|
|
let mut value = serde_json::to_value(initialize_result())?;
|
|
if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) {
|
|
caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true));
|
|
if ranges_formatting {
|
|
caps.insert(
|
|
"documentRangeFormattingProvider".to_string(),
|
|
serde_json::json!({ "rangesSupport": true }),
|
|
);
|
|
}
|
|
}
|
|
Ok(value)
|
|
}
|
|
|
|
fn initialize_result() -> lsp_types::InitializeResult {
|
|
lsp_types::InitializeResult {
|
|
capabilities: capabilities(),
|
|
server_info: Some(lsp_types::ServerInfo {
|
|
name: "lucisv-server".to_string(),
|
|
version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
|
}),
|
|
// `lsp-types`' `proposed` feature adds an `offsetEncoding` field here
|
|
// (clangd's unofficial extension). It is not ours to send.
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Whether the client can send `textDocument/rangesFormatting` (LSP 3.18),
|
|
/// read from the **raw** `initialize` params.
|
|
///
|
|
/// It has to be the raw JSON: `lsp-types` 0.97 aliases
|
|
/// `DocumentRangeFormattingClientCapabilities` to the plain dynamic-registration
|
|
/// struct, which has no `rangesSupport` field and no place to keep an unknown
|
|
/// one, so by the time the params are an `InitializeParams` the flag is gone.
|
|
/// Anything that is not literally `true` at
|
|
/// `capabilities.textDocument.rangeFormatting.rangesSupport` — absent, `false`,
|
|
/// a string, a client whose params do not parse at all — means no, which is
|
|
/// exactly the answer that leaves that client's capability where it was.
|
|
fn ranges_formatting_support(params: &serde_json::Value) -> bool {
|
|
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
|
|
}
|
|
|
|
/// The folder the client set aside for this workspace's server state —
|
|
/// `initializationOptions.storagePath`, which the VS Code extension fills in
|
|
/// with `context.storageUri`.
|
|
///
|
|
/// The persistent index cache goes here when there is one: it is
|
|
/// per-workspace, the editor cleans it up when the workspace is forgotten,
|
|
/// and it needs no guess about where this platform keeps caches. A client
|
|
/// that sends nothing — every client but ours, and ours before this — leaves
|
|
/// the OS cache directory to decide
|
|
/// (`docs/features/index-persistence/README.md`). A blank value counts as
|
|
/// unset, the same reading `lucisv.serverPath` gives a blank setting.
|
|
fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
|
|
let path = params["initializationOptions"]["storagePath"].as_str()?;
|
|
(!path.trim().is_empty()).then(|| PathBuf::from(path))
|
|
}
|
|
|
|
/// Whether this client hosts lucisv's custom hierarchy view and therefore
|
|
/// wants invalidation notifications for it. The snapshot request itself is
|
|
/// always served; this gate prevents unsolicited traffic to other LSP clients.
|
|
fn hierarchy_view_support(params: &serde_json::Value) -> bool {
|
|
params["initializationOptions"]["hierarchyView"] == true
|
|
}
|
|
|
|
/// Whether the client can expand `${1:x}` tabstops in a completion item.
|
|
///
|
|
/// A client that did not say so gets the skeleton as plain text: a literal
|
|
/// `${1:clk}` written into a buffer is worse than no tabstops at all, and the
|
|
/// protocol gives no way to find out after the fact.
|
|
fn snippet_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.text_document
|
|
.as_ref()
|
|
.and_then(|text_document| text_document.completion.as_ref())
|
|
.and_then(|completion| completion.completion_item.as_ref())
|
|
.and_then(|item| item.snippet_support)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Whether the client can fetch a code action's `edit` after the fact —
|
|
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
|
|
///
|
|
/// The property list is the capability: a client that can resolve `title`
|
|
/// alone cannot be offered an action without its edit, so nothing short of
|
|
/// `"edit"` counts. A client that says nothing gets every action complete, as
|
|
/// every client did before this was read
|
|
/// (`docs/features/lazy-code-action/README.md`).
|
|
fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.text_document
|
|
.as_ref()
|
|
.and_then(|text_document| text_document.code_action.as_ref())
|
|
.and_then(|code_action| code_action.resolve_support.as_ref())
|
|
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
|
}
|
|
|
|
/// Whether the client can apply a `WorkspaceEdit` that **creates a file** —
|
|
/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations`
|
|
/// list containing `create`.
|
|
///
|
|
/// Both halves, because a creation is a resource operation and a resource
|
|
/// operation can only be sent inside `documentChanges`: a client with one and
|
|
/// not the other cannot apply the edit at all. A client that says nothing gets
|
|
/// the extracted module written below the one it came from, in the file it
|
|
/// came from, which needs no capability of any kind
|
|
/// (`docs/features/extract-inline-module/README.md`).
|
|
fn create_files_support(params: &InitializeParams) -> bool {
|
|
let Some(edits) = params
|
|
.capabilities
|
|
.workspace
|
|
.as_ref()
|
|
.and_then(|workspace| workspace.workspace_edit.as_ref())
|
|
else {
|
|
return false;
|
|
};
|
|
let creates = edits
|
|
.resource_operations
|
|
.as_ref()
|
|
.is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create));
|
|
edits.document_changes.unwrap_or(false) && creates
|
|
}
|
|
|
|
/// Whether the client applies a `workspace/applyEdit` request.
|
|
///
|
|
/// A client that did not say so gets a command's edit back as the request
|
|
/// result — which is what every client got before this was read, and is the
|
|
/// only thing left to try for one that cannot be pushed an edit.
|
|
fn apply_edit_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.workspace
|
|
.as_ref()
|
|
.and_then(|workspace| workspace.apply_edit)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Whether the client lets the *server* cancel a semantic-tokens request —
|
|
/// `textDocument.semanticTokens.serverCancelSupport`.
|
|
///
|
|
/// The large-file fast path declines `semanticTokens/full`, and this decides
|
|
/// with which error code: `ServerCancelled` for a client that says it
|
|
/// understands one (the spec restricts that code to requests "that explicitly
|
|
/// support being server cancellable", and this capability is how a client
|
|
/// says so), `ContentModified` for one that does not. Both leave
|
|
/// `vscode-languageclient` throwing a `CancellationError`, which is what keeps
|
|
/// the range provider alive — see
|
|
/// `docs/features/large-file-mode/README.md`.
|
|
fn token_server_cancel_support(params: &InitializeParams) -> bool {
|
|
params.capabilities.text_document.as_ref().is_some_and(|text_document| {
|
|
text_document
|
|
.semantic_tokens
|
|
.as_ref()
|
|
.is_some_and(|tokens| tokens.server_cancel_support == Some(true))
|
|
})
|
|
}
|
|
|
|
/// Whether the client pulls diagnostics (LSP 3.17).
|
|
///
|
|
/// Sending the capability at all is what says so; its two fields are about
|
|
/// dynamic registration and related documents, neither of which this server
|
|
/// uses. A client that says nothing keeps the push model unchanged.
|
|
fn pull_diagnostics_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.text_document
|
|
.as_ref()
|
|
.is_some_and(|text_document| text_document.diagnostic.is_some())
|
|
}
|
|
|
|
/// Whether the client renders server-initiated work-done progress.
|
|
///
|
|
/// The spec forbids a server from creating progress at all without this, so a
|
|
/// client that said nothing is sent no `window/workDoneProgress/create` and no
|
|
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
|
|
/// before this was read.
|
|
fn work_done_progress_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.window
|
|
.as_ref()
|
|
.and_then(|window| window.work_done_progress)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Whether the client can be asked to re-request its code lenses.
|
|
///
|
|
/// `workspace/codeLens/refresh` is server-initiated, so the spec makes this
|
|
/// capability the gate. A client that said nothing keeps whatever counts it
|
|
/// last asked for until something else makes it ask again — which is what
|
|
/// every client got before code lenses existed at all.
|
|
fn code_lens_refresh_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.workspace
|
|
.as_ref()
|
|
.and_then(|workspace| workspace.code_lens.as_ref())
|
|
.and_then(|code_lens| code_lens.refresh_support)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Whether the client can be asked to pull its diagnostics again
|
|
/// (`workspace/diagnostic/refresh`), read from the **raw** `initialize`
|
|
/// params.
|
|
///
|
|
/// Server-initiated, so the spec makes this capability the gate, exactly as
|
|
/// for the code-lens refresh. It has to be the raw JSON: the protocol's key is
|
|
/// `workspace.diagnostics`, and `lsp-types` 0.97 spells its field
|
|
/// `diagnostic` with no rename, so the typed decode never sees what VS Code
|
|
/// sends. Anything but a literal `true` means no. Sent when a connection entry
|
|
/// held back while it was typed is released
|
|
/// (`docs/features/port-entry-grace/README.md`).
|
|
fn diagnostic_refresh_support(params: &serde_json::Value) -> bool {
|
|
params["capabilities"]["workspace"]["diagnostics"]["refreshSupport"] == true
|
|
}
|
|
|
|
/// Whether the client opens a document the server asks it to.
|
|
///
|
|
/// This is what makes the instantiation lens actually navigate: an
|
|
/// `executeCommand` result cannot move a cursor, so the jump is a pushed
|
|
/// `window/showDocument`. A client that did not advertise it still gets the
|
|
/// sites back as the command's result.
|
|
fn show_document_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.window
|
|
.as_ref()
|
|
.and_then(|window| window.show_document.as_ref())
|
|
.is_some_and(|show_document| show_document.support)
|
|
}
|
|
|
|
/// Whether the client answers `workspace/configuration`.
|
|
///
|
|
/// The pull half of the settings model: a client that says so is asked for
|
|
/// the `lucisv` section at startup and again whenever it sends an empty
|
|
/// `didChangeConfiguration`. A client that said nothing is only ever pushed
|
|
/// settings, exactly as before.
|
|
fn configuration_support(params: &InitializeParams) -> bool {
|
|
params
|
|
.capabilities
|
|
.workspace
|
|
.as_ref()
|
|
.and_then(|workspace| workspace.configuration)
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// The directories to index: the client's workspace folders, or the
|
|
/// deprecated single root when that is all it sent.
|
|
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
|
if let Some(folders) = ¶ms.workspace_folders {
|
|
let roots: Vec<PathBuf> = folders.iter().filter_map(|f| uri_to_path(&f.uri)).collect();
|
|
if !roots.is_empty() {
|
|
return roots;
|
|
}
|
|
}
|
|
#[allow(deprecated)] // `root_uri` is how older clients name the workspace.
|
|
params.root_uri.as_ref().and_then(uri_to_path).into_iter().collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// [`verbose_flag`] over what a spawn would really hand it.
|
|
fn args(args: &[&str]) -> Result<bool, String> {
|
|
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
|
|
}
|
|
|
|
#[test]
|
|
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
|
|
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
|
|
}
|
|
|
|
#[test]
|
|
fn the_one_flag_is_the_one_spelling() {
|
|
assert_eq!(args(&["--verbose"]), Ok(true));
|
|
// Twice says the same thing twice.
|
|
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
|
|
// Every near miss is refused, `-v` included: one spelling, so a client
|
|
// that guessed is told rather than silently given nothing.
|
|
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
|
|
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn stdio_is_accepted_as_the_statement_of_fact_it_is() {
|
|
// `vscode-languageclient` appends `--stdio` for TransportKind.stdio —
|
|
// the spawn every real VS Code session actually makes. Rejecting it
|
|
// crashed the extension five times and gave up (lead hotfix,
|
|
// 2026-08-29); it must parse in every combination and change nothing.
|
|
assert_eq!(args(&["--stdio"]), Ok(false));
|
|
assert_eq!(args(&["--stdio", "--verbose"]), Ok(true));
|
|
assert_eq!(args(&["--verbose", "--stdio"]), Ok(true));
|
|
assert_eq!(args(&["--stdio", "--stdio"]), Ok(false));
|
|
// And a near miss of IT is still refused.
|
|
assert_eq!(args(&["--Stdio"]), Err("--Stdio".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
fn the_first_argument_we_do_not_take_is_the_one_reported() {
|
|
// Named, so the message can say which word was wrong — the whole
|
|
// reason this refuses instead of ignoring.
|
|
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
|
|
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
|
|
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
|
|
// The two halves of the contract live in different languages: the
|
|
// manifest's default decides whether `extension.js` puts `--verbose`
|
|
// in the spawn arguments, and `verbose_flag` decides what the server
|
|
// does with the arguments it gets. They must agree that the shipped
|
|
// state is off.
|
|
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
|
.join("../../editors/vscode/package.json");
|
|
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
|
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
|
|
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
|
|
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
|
|
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
|
|
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
|
|
}
|
|
|
|
#[test]
|
|
fn every_advertised_capability_is_implemented() {
|
|
let caps = capabilities();
|
|
assert!(caps.document_formatting_provider.is_some());
|
|
assert!(caps.document_range_formatting_provider.is_some());
|
|
assert!(caps.definition_provider.is_some());
|
|
assert!(caps.type_definition_provider.is_some());
|
|
assert!(caps.linked_editing_range_provider.is_some());
|
|
assert!(caps.references_provider.is_some());
|
|
assert!(caps.document_link_provider.is_some());
|
|
assert!(caps.document_highlight_provider.is_some());
|
|
assert!(caps.folding_range_provider.is_some());
|
|
assert!(caps.hover_provider.is_some());
|
|
assert!(caps.document_symbol_provider.is_some());
|
|
assert!(caps.workspace_symbol_provider.is_some());
|
|
assert!(caps.semantic_tokens_provider.is_some());
|
|
assert!(caps.code_action_provider.is_some());
|
|
assert!(caps.rename_provider.is_some());
|
|
assert!(caps.execute_command_provider.is_some());
|
|
assert!(caps.completion_provider.is_some());
|
|
assert!(caps.signature_help_provider.is_some());
|
|
assert!(caps.inlay_hint_provider.is_some());
|
|
assert!(caps.call_hierarchy_provider.is_some());
|
|
assert!(caps.inline_completion_provider.is_some());
|
|
assert!(caps.selection_range_provider.is_some());
|
|
assert!(caps.diagnostic_provider.is_some());
|
|
assert!(caps.code_lens_provider.is_some());
|
|
assert!(caps.document_on_type_formatting_provider.is_some());
|
|
assert!(caps.workspace.is_some(), "the file operations live here");
|
|
}
|
|
|
|
#[test]
|
|
fn the_file_operations_reach_the_wire_under_workspace() {
|
|
// A client sends `willRenameFiles` only where the *server's* filters
|
|
// say so, and it looks for them at this exact key — a capability
|
|
// nested one level wrong is a capability that is never exercised.
|
|
let value = initialize_value(false).expect("the initialize result serializes");
|
|
let operations = &value["capabilities"]["workspace"]["fileOperations"];
|
|
assert_eq!(
|
|
operations["willRename"]["filters"][0]["pattern"]["glob"],
|
|
serde_json::json!(watch::SOURCE_GLOB),
|
|
"{value:#?}"
|
|
);
|
|
assert_eq!(
|
|
operations["willRename"]["filters"][1]["pattern"]["matches"],
|
|
serde_json::json!("folder"),
|
|
"a folder rename moves every include that reached into it"
|
|
);
|
|
assert_eq!(operations["didRename"]["filters"].as_array().map(Vec::len), Some(1));
|
|
assert_eq!(operations["didDelete"]["filters"].as_array().map(Vec::len), Some(1));
|
|
// The three this server does not answer are absent, not empty: a
|
|
// filter list a server cannot serve is a request it will be sent.
|
|
for absent in ["willCreate", "didCreate", "willDelete"] {
|
|
assert_eq!(operations[absent], serde_json::Value::Null, "{absent} is not answered");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn workspace_folders_are_supported_and_their_changes_are_asked_for() {
|
|
// Two separate statements, and a client reads them separately:
|
|
// without `supported` it may not treat this as a multi-folder server
|
|
// at all, and without `changeNotifications` it never sends
|
|
// `didChangeWorkspaceFolders` however well that is handled.
|
|
let folders = capabilities()
|
|
.workspace
|
|
.expect("the workspace section")
|
|
.workspace_folders
|
|
.expect("workspace folders");
|
|
assert_eq!(folders.supported, Some(true));
|
|
assert_eq!(folders.change_notifications, Some(OneOf::Left(true)));
|
|
}
|
|
|
|
#[test]
|
|
fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() {
|
|
// Nested one level wrong, or serialized as the string form of
|
|
// `changeNotifications`, and the notification simply never arrives.
|
|
let value = initialize_value(false).expect("the initialize result serializes");
|
|
assert_eq!(
|
|
value["capabilities"]["workspace"]["workspaceFolders"],
|
|
serde_json::json!({ "supported": true, "changeNotifications": true }),
|
|
"{value:#?}"
|
|
);
|
|
// And the neighbour under the same key is untouched.
|
|
assert!(value["capabilities"]["workspace"]["fileOperations"].is_object(), "{value:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn configuration_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
|
assert!(!configuration_support(&InitializeParams::default()), "silence means push-only");
|
|
|
|
let saying = |configuration: Option<bool>| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
workspace: Some(WorkspaceClientCapabilities {
|
|
configuration,
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(configuration_support(&saying(Some(true))));
|
|
assert!(!configuration_support(&saying(Some(false))));
|
|
assert!(!configuration_support(&saying(None)));
|
|
}
|
|
|
|
#[test]
|
|
fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() {
|
|
// `ServerCapabilities` has no `type_hierarchy_provider` field in
|
|
// lsp-types 0.97 — the crate models type hierarchy on the client side
|
|
// only — so the capability is written into the serialized object. A
|
|
// client keys entirely off this key: without it the three requests are
|
|
// never sent, however well they are implemented.
|
|
let value = initialize_value(false).expect("the initialize result serializes");
|
|
assert_eq!(
|
|
value["capabilities"]["typeHierarchyProvider"],
|
|
serde_json::json!(true),
|
|
"{value:#?}"
|
|
);
|
|
// And the rest of the object is untouched by the insertion.
|
|
assert_eq!(value["capabilities"]["callHierarchyProvider"], serde_json::json!(true));
|
|
assert_eq!(value["serverInfo"]["name"], serde_json::json!("lucisv-server"));
|
|
}
|
|
|
|
// QA (2026-08-26): the spot checks above name two fields; this pins the
|
|
// whole object instead. `initialize_result()` and `capabilities()` are
|
|
// untouched by this round (confirmed against `24e8eab`), so the only way
|
|
// the insertion could disturb anything is the one `caps.insert` call
|
|
// itself — this proves that byte-for-byte rather than by inspection: pull
|
|
// the one inserted key back out and what remains must equal the plain,
|
|
// uninserted serialization exactly. A future round that lets the
|
|
// insertion clobber an existing key, or that adds a field to
|
|
// `ServerCapabilities` under the same JSON name, fails this immediately.
|
|
#[test]
|
|
fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() {
|
|
let mut with_insertion = initialize_value(false).expect("the initialize result serializes");
|
|
let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too");
|
|
let caps =
|
|
with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
|
assert_eq!(
|
|
caps.remove("typeHierarchyProvider"),
|
|
Some(serde_json::json!(true)),
|
|
"the one key the insertion is supposed to add"
|
|
);
|
|
assert_eq!(
|
|
with_insertion, plain,
|
|
"removing the inserted key must restore exactly what capabilities() \
|
|
and initialize_result() produce on their own, key for key, value for value"
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `rangesFormatting` (LSP 3.18) — the capability, on both wire shapes
|
|
// ------------------------------------------------------------------
|
|
|
|
/// `initialize` params carrying whatever a client said about
|
|
/// `rangesSupport`, as raw JSON — which is the only place it survives.
|
|
fn client_saying(ranges_support: serde_json::Value) -> serde_json::Value {
|
|
serde_json::json!({
|
|
"processId": null,
|
|
"capabilities": {
|
|
"textDocument": { "rangeFormatting": { "rangesSupport": ranges_support } }
|
|
}
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn ranges_formatting_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
|
assert!(ranges_formatting_support(&client_saying(serde_json::json!(true))));
|
|
assert!(!ranges_formatting_support(&client_saying(serde_json::json!(false))));
|
|
// Junk in that slot is not a yes. A client that means it sends `true`.
|
|
assert!(!ranges_formatting_support(&client_saying(serde_json::json!("yes"))));
|
|
assert!(!ranges_formatting_support(&client_saying(serde_json::Value::Null)));
|
|
// The 3.17 client: the key is not there at all.
|
|
assert!(!ranges_formatting_support(&serde_json::json!({ "capabilities": {} })));
|
|
// And params that are not even an object — `Value::index` answers
|
|
// `Null` rather than panicking, which is the whole reason this is a
|
|
// JSON read and not a typed one.
|
|
assert!(!ranges_formatting_support(&serde_json::json!("nonsense")));
|
|
assert!(!ranges_formatting_support(&serde_json::Value::Null));
|
|
}
|
|
|
|
#[test]
|
|
fn hierarchy_notifications_are_an_explicit_initialization_option() {
|
|
let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } });
|
|
assert!(hierarchy_view_support(&saying));
|
|
for silent in [
|
|
serde_json::json!({}),
|
|
serde_json::json!({ "initializationOptions": { "hierarchyView": false } }),
|
|
serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }),
|
|
serde_json::Value::Null,
|
|
] {
|
|
assert!(!hierarchy_view_support(&silent), "{silent:#?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
|
|
// The gate's whole point: every client that shipped before this round
|
|
// must see the same byte on the wire. A bare `true` is the shape no
|
|
// client can misread, and one that never advertised `rangesSupport`
|
|
// will never send the request however it is advertised.
|
|
let value = initialize_value(false).expect("the initialize result serializes");
|
|
assert_eq!(
|
|
value["capabilities"]["documentRangeFormattingProvider"],
|
|
serde_json::json!(true),
|
|
"{value:#?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_asked_sees_the_options_object_with_ranges_support() {
|
|
// `documentRangeFormattingProvider` is `boolean |
|
|
// DocumentRangeFormattingOptions` in the spec, and `rangesSupport` is
|
|
// a field on the options arm — so widening the bool to the object is
|
|
// how the spec says to answer, and it is the only way
|
|
// `vscode-languageclient` will register its multi-range provider.
|
|
let value = initialize_value(true).expect("the initialize result serializes");
|
|
assert_eq!(
|
|
value["capabilities"]["documentRangeFormattingProvider"],
|
|
serde_json::json!({ "rangesSupport": true }),
|
|
"{value:#?}"
|
|
);
|
|
// Single-range formatting is still advertised by that same key — the
|
|
// object is not an *extra* capability, it is the same one saying more.
|
|
assert!(
|
|
value["capabilities"]["documentRangeFormattingProvider"].is_object(),
|
|
"and never a second key: {value:#?}"
|
|
);
|
|
assert_eq!(value["capabilities"]["documentRangeFormattingProvider"]["rangesSupport"], true);
|
|
}
|
|
|
|
#[test]
|
|
fn widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result() {
|
|
// The same proof `the_json_insertion_disturbs_nothing_else...` gives
|
|
// for `typeHierarchyProvider`, for the second inserted key: the two
|
|
// results must differ at exactly one key and be equal everywhere else.
|
|
let mut gated = initialize_value(true).expect("serializes");
|
|
let plain = initialize_value(false).expect("serializes");
|
|
let caps = gated["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
|
assert_eq!(
|
|
caps.insert("documentRangeFormattingProvider".to_string(), serde_json::json!(true)),
|
|
Some(serde_json::json!({ "rangesSupport": true })),
|
|
"the one key the widening is supposed to replace"
|
|
);
|
|
assert_eq!(
|
|
gated, plain,
|
|
"putting the bare `true` back must restore the ungated result exactly"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() {
|
|
// The trigger set is the feature: a client sends this request on every
|
|
// one of these characters and on no other, so what is listed here is
|
|
// exactly what `on_type::on_type_formatting` knows how to answer. `}`
|
|
// is deliberately absent — SV closes its blocks with the word `end`.
|
|
let options = capabilities().document_on_type_formatting_provider.expect("advertised");
|
|
assert_eq!(options.first_trigger_character, "\n");
|
|
assert_eq!(options.more_trigger_character, Some(vec![";".to_string()]));
|
|
}
|
|
|
|
#[test]
|
|
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
|
|
// A client keys entirely off this: it sends `full/delta` only where
|
|
// `full.delta` is `true`, and `range` only where `range` is.
|
|
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
|
|
capabilities().semantic_tokens_provider
|
|
else {
|
|
panic!("the options form, not a registration");
|
|
};
|
|
assert_eq!(options.range, Some(true));
|
|
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
|
|
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
|
|
}
|
|
|
|
#[test]
|
|
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
|
|
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
|
|
else {
|
|
panic!("the options form, not a bare kind");
|
|
};
|
|
assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL));
|
|
assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered");
|
|
assert_eq!(options.will_save, None, "the plain notification has nothing for us");
|
|
}
|
|
|
|
#[test]
|
|
fn the_diagnostic_options_say_what_this_server_actually_does() {
|
|
let Some(DiagnosticServerCapabilities::Options(options)) =
|
|
capabilities().diagnostic_provider
|
|
else {
|
|
panic!("plain options, not a dynamic registration");
|
|
};
|
|
assert_eq!(options.identifier.as_deref(), Some(diagnostics::SOURCE), "same tag as a push");
|
|
assert!(options.inter_file_dependencies, "a save changes other files' diagnostics");
|
|
assert!(options.workspace_diagnostics, "`workspace/diagnostic` is answered");
|
|
}
|
|
|
|
#[test]
|
|
fn apply_edit_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
|
assert!(!apply_edit_support(&InitializeParams::default()), "silence means no");
|
|
|
|
let saying = |apply_edit: Option<bool>| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
workspace: Some(WorkspaceClientCapabilities { apply_edit, ..Default::default() }),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(apply_edit_support(&saying(Some(true))));
|
|
assert!(!apply_edit_support(&saying(Some(false))));
|
|
assert!(!apply_edit_support(&saying(None)));
|
|
}
|
|
|
|
#[test]
|
|
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
|
|
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
|
|
|
|
let saying = |work_done_progress: Option<bool>| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(work_done_progress_support(&saying(Some(true))));
|
|
assert!(!work_done_progress_support(&saying(Some(false))));
|
|
assert!(!work_done_progress_support(&saying(None)));
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
|
|
use lsp_types::{
|
|
ClientCapabilities, DiagnosticClientCapabilities, TextDocumentClientCapabilities,
|
|
};
|
|
assert!(!pull_diagnostics_support(&InitializeParams::default()), "silence means push");
|
|
|
|
let pulling = InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
text_document: Some(TextDocumentClientCapabilities {
|
|
// Both fields left unset: sending the capability is the
|
|
// whole of the statement, and neither field is about
|
|
// whether the client pulls.
|
|
diagnostic: Some(DiagnosticClientCapabilities::default()),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(pull_diagnostics_support(&pulling));
|
|
}
|
|
|
|
#[test]
|
|
fn the_call_hierarchy_is_advertised_as_a_plain_capability() {
|
|
// Nothing about it is optional or resolvable: the three requests are
|
|
// either all served or none are.
|
|
assert_eq!(
|
|
capabilities().call_hierarchy_provider,
|
|
Some(CallHierarchyServerCapability::Simple(true))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn document_links_resolve_nothing_because_every_target_is_already_known() {
|
|
let options = capabilities().document_link_provider.expect("document links");
|
|
assert_eq!(options.resolve_provider, Some(false));
|
|
}
|
|
|
|
#[test]
|
|
fn inlay_hints_resolve_nothing_because_every_hint_is_complete() {
|
|
let Some(OneOf::Right(InlayHintServerCapabilities::Options(options))) =
|
|
capabilities().inlay_hint_provider
|
|
else {
|
|
panic!("inlay hints must carry options, not a bare `true`");
|
|
};
|
|
assert_eq!(options.resolve_provider, None);
|
|
}
|
|
|
|
#[test]
|
|
fn signature_help_advertises_the_characters_the_handler_answers_on() {
|
|
let options = capabilities().signature_help_provider.expect("signature help");
|
|
assert_eq!(options.trigger_characters, Some(vec!["(".to_string(), ",".to_string()]));
|
|
}
|
|
|
|
#[test]
|
|
fn completion_resolves_nothing_because_every_item_is_complete() {
|
|
let options = capabilities().completion_provider.expect("completion");
|
|
assert_eq!(options.resolve_provider, None);
|
|
}
|
|
|
|
#[test]
|
|
fn completion_triggers_on_the_two_separators_that_start_a_member_list() {
|
|
let options = capabilities().completion_provider.expect("completion");
|
|
assert_eq!(
|
|
options.trigger_characters,
|
|
Some(vec![".".to_string(), ":".to_string()]),
|
|
"a member list has no identifier to ask for it, so the separator must",
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn snippet_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{
|
|
ClientCapabilities, CompletionClientCapabilities, CompletionItemCapability,
|
|
TextDocumentClientCapabilities,
|
|
};
|
|
assert!(!snippet_support(&InitializeParams::default()), "silence means no");
|
|
|
|
let saying = |snippet_support: Option<bool>| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
text_document: Some(TextDocumentClientCapabilities {
|
|
completion: Some(CompletionClientCapabilities {
|
|
completion_item: Some(CompletionItemCapability {
|
|
snippet_support,
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(super::snippet_support(&saying(Some(true))));
|
|
assert!(!super::snippet_support(&saying(Some(false))));
|
|
assert!(!super::snippet_support(&saying(None)));
|
|
}
|
|
|
|
#[test]
|
|
fn rename_advertises_prepare_so_the_editor_asks_before_offering() {
|
|
let Some(OneOf::Right(options)) = capabilities().rename_provider else {
|
|
panic!("rename must carry options, not a bare `true`");
|
|
};
|
|
assert_eq!(options.prepare_provider, Some(true));
|
|
}
|
|
|
|
#[test]
|
|
fn the_legend_and_the_encoder_agree_on_length() {
|
|
// The wire format carries indices into these arrays, so a mismatch
|
|
// between the legend and the encoder is a silent mis-colouring.
|
|
assert_eq!(tokens::token_types().len(), 14);
|
|
assert_eq!(tokens::token_modifiers().len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn the_code_action_kinds_are_named_in_the_capability() {
|
|
// A client filtering by kind (fix-on-save does) sees nothing unless the
|
|
// kinds it may ask for are advertised.
|
|
let Some(CodeActionProviderCapability::Options(options)) =
|
|
capabilities().code_action_provider
|
|
else {
|
|
panic!("the kinds must be listed, not just `true`");
|
|
};
|
|
let kinds = options.code_action_kinds.expect("kinds");
|
|
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
|
|
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
|
|
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
|
|
assert_eq!(
|
|
options.resolve_provider,
|
|
Some(true),
|
|
"the port refactorings are offered without their edits to a client that can ask"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn create_files_support_needs_both_halves_of_the_capability() {
|
|
use lsp_types::{
|
|
ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities,
|
|
WorkspaceEditClientCapabilities,
|
|
};
|
|
assert!(
|
|
!create_files_support(&InitializeParams::default()),
|
|
"silence means the module goes below the one it came from"
|
|
);
|
|
|
|
let saying = |document_changes: Option<bool>, ops: Option<&[ResourceOperationKind]>| {
|
|
InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
workspace: Some(WorkspaceClientCapabilities {
|
|
workspace_edit: Some(WorkspaceEditClientCapabilities {
|
|
document_changes,
|
|
resource_operations: ops.map(<[_]>::to_vec),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
}
|
|
};
|
|
let create = [ResourceOperationKind::Create];
|
|
let rename = [ResourceOperationKind::Rename];
|
|
assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends");
|
|
assert!(
|
|
!create_files_support(&saying(Some(true), Some(&rename))),
|
|
"a client that can rename but not create cannot apply the creation"
|
|
);
|
|
assert!(
|
|
!create_files_support(&saying(Some(true), None)),
|
|
"no resource operations at all is no creation"
|
|
);
|
|
assert!(
|
|
!create_files_support(&saying(None, Some(&create))),
|
|
"a resource operation can only be sent inside `documentChanges`"
|
|
);
|
|
assert!(!create_files_support(&saying(Some(false), Some(&create))));
|
|
}
|
|
|
|
#[test]
|
|
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{
|
|
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
|
|
TextDocumentClientCapabilities,
|
|
};
|
|
assert!(
|
|
!code_action_resolve_support(&InitializeParams::default()),
|
|
"silence means the whole edit up front"
|
|
);
|
|
|
|
let saying = |properties: &[&str]| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
text_document: Some(TextDocumentClientCapabilities {
|
|
code_action: Some(CodeActionClientCapabilities {
|
|
resolve_support: Some(CodeActionCapabilityResolveSupport {
|
|
properties: properties.iter().map(|p| p.to_string()).collect(),
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(code_action_resolve_support(&saying(&["edit"])));
|
|
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
|
|
assert!(
|
|
!code_action_resolve_support(&saying(&["documentation"])),
|
|
"resolving anything but the edit is no use to us"
|
|
);
|
|
assert!(!code_action_resolve_support(&saying(&[])));
|
|
}
|
|
|
|
#[test]
|
|
fn every_advertised_command_is_one_the_server_runs() {
|
|
let options = capabilities().execute_command_provider.expect("commands");
|
|
assert_eq!(options.commands, commands());
|
|
// Every half of the list, so none can go missing quietly: a lens
|
|
// whose command is not advertised is a lens no client will run, and
|
|
// an unadvertised `lucisv.instantiate` is the whole of §2.9-19 gone.
|
|
for command in ports::commands()
|
|
.iter()
|
|
.chain(instantiate::commands().iter())
|
|
.chain(lens::commands().iter())
|
|
{
|
|
assert!(options.commands.contains(command), "{command} is not advertised");
|
|
}
|
|
assert!(
|
|
options.commands.iter().all(|c| c.starts_with("lucisv.")),
|
|
"{:?}",
|
|
options.commands
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn code_lenses_resolve_nothing_because_every_lens_is_complete() {
|
|
let options = capabilities().code_lens_provider.expect("code lenses");
|
|
assert_eq!(options.resolve_provider, Some(false));
|
|
}
|
|
|
|
#[test]
|
|
fn code_lens_refresh_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{
|
|
ClientCapabilities, CodeLensWorkspaceClientCapabilities, WorkspaceClientCapabilities,
|
|
};
|
|
assert!(!code_lens_refresh_support(&InitializeParams::default()), "silence means no");
|
|
|
|
let saying = |refresh_support: Option<bool>| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
workspace: Some(WorkspaceClientCapabilities {
|
|
code_lens: Some(CodeLensWorkspaceClientCapabilities { refresh_support }),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(code_lens_refresh_support(&saying(Some(true))));
|
|
assert!(!code_lens_refresh_support(&saying(Some(false))));
|
|
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
|
|
}
|
|
|
|
#[test]
|
|
fn diagnostic_refresh_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
|
let saying = |refresh: serde_json::Value| {
|
|
serde_json::json!({
|
|
"processId": null,
|
|
"capabilities": { "workspace": { "diagnostics": { "refreshSupport": refresh } } }
|
|
})
|
|
};
|
|
assert!(diagnostic_refresh_support(&saying(serde_json::json!(true))));
|
|
assert!(!diagnostic_refresh_support(&saying(serde_json::json!(false))));
|
|
assert!(!diagnostic_refresh_support(&saying(serde_json::json!("yes"))));
|
|
assert!(!diagnostic_refresh_support(&saying(serde_json::Value::Null)));
|
|
assert!(!diagnostic_refresh_support(&serde_json::json!({ "capabilities": {} })));
|
|
assert!(!diagnostic_refresh_support(&serde_json::Value::Null));
|
|
// The protocol's key is plural; `lsp-types`' singular field name is
|
|
// not what any client sends, and is not read.
|
|
let singular = serde_json::json!({
|
|
"capabilities": { "workspace": { "diagnostic": { "refreshSupport": true } } }
|
|
});
|
|
assert!(!diagnostic_refresh_support(&singular));
|
|
}
|
|
|
|
#[test]
|
|
fn show_document_support_is_read_from_the_clients_own_capabilities() {
|
|
use lsp_types::{
|
|
ClientCapabilities, ShowDocumentClientCapabilities, WindowClientCapabilities,
|
|
};
|
|
assert!(!show_document_support(&InitializeParams::default()), "silence means no");
|
|
|
|
let saying = |support: bool| InitializeParams {
|
|
capabilities: ClientCapabilities {
|
|
window: Some(WindowClientCapabilities {
|
|
show_document: Some(ShowDocumentClientCapabilities { support }),
|
|
..Default::default()
|
|
}),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert!(show_document_support(&saying(true)));
|
|
assert!(!show_document_support(&saying(false)));
|
|
}
|
|
|
|
#[test]
|
|
fn utf16_is_advertised_because_that_is_what_convert_implements() {
|
|
assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16));
|
|
}
|
|
}
|