textDocument/didChange now applies ranged content changes instead of requiring the whole buffer per keystroke. New pure sync::apply_changes applies each change against the document as the previous ones left it (fresh line table per change), clamping inherited from convert.rs and a backwards range read as a pure insertion — the one rule that cannot lose text. One notification stays one reparse / one generation bump / one publish. Full-sync clients (rangeless changes) keep byte-identical behavior; save advertises includeText: false and didSave still honours text when sent. 35 tests added (28 unit incl. a 400-sequence randomized cross-check against an independent reference model and QA's surrogate/CRLF/final- newline attacks, 6 server-level, 1 e2e pinning the wire capability shape). QA's one finding — CRLF split across two same-position inserts in one batch lands \n\r — is pre-existing convert.rs behavior, pinned by test, unreachable by real clients; see the feature README. docs/features/incremental-sync/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
1971 lines
90 KiB
Rust
1971 lines
90 KiB
Rust
//! The request loop: one message in, one response out, 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 and un-cancellable
|
|
//! — Verilog files are small, every handler is milliseconds, and a worker pool
|
|
//! would buy nothing yet. See `docs/features/lucisv-server/README.md`.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::error::Error;
|
|
|
|
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
|
|
use lsp_types::notification::{
|
|
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument,
|
|
DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics,
|
|
ShowMessage,
|
|
};
|
|
use lsp_types::request::{
|
|
ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls,
|
|
CallHierarchyPrepare, CodeActionRequest, Completion, DocumentDiagnosticRequest,
|
|
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
|
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
|
|
InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability,
|
|
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullRequest, SignatureHelpRequest,
|
|
UnregisterCapability, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
|
};
|
|
use lsp_types::{
|
|
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
|
|
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CodeActionKind, CodeActionParams,
|
|
CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
|
|
DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
|
|
DidSaveTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport,
|
|
DocumentDiagnosticReportResult, DocumentFormattingParams, DocumentHighlightParams,
|
|
DocumentLinkParams, DocumentRangeFormattingParams, DocumentSymbolParams,
|
|
DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport,
|
|
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
|
InlineCompletionParams, LogMessageParams, MessageType, Position, PreviousResultId,
|
|
PublishDiagnosticsParams, ReferenceParams, RegistrationParams,
|
|
RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams,
|
|
SelectionRangeParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
|
|
SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport,
|
|
UnregistrationParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport,
|
|
WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, WorkspaceEdit,
|
|
WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse,
|
|
WorkspaceUnchangedDocumentDiagnosticReport,
|
|
};
|
|
use serde::de::DeserializeOwned;
|
|
use serde_json::Value;
|
|
|
|
use crate::state::Workspace;
|
|
use crate::{
|
|
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay,
|
|
inline, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, tokens,
|
|
watch,
|
|
};
|
|
|
|
/// What the client said it can do, read once at `initialize` because that is
|
|
/// the only time those capabilities are sent.
|
|
#[derive(Default)]
|
|
pub struct ClientAbilities {
|
|
/// Whether the client can expand a completion item's tabstops.
|
|
pub snippets: bool,
|
|
/// Whether the client accepts a `workspace/didChangeWatchedFiles`
|
|
/// registration. There is no static form of that capability, so a client
|
|
/// that says nothing keeps the save-only staleness model.
|
|
pub file_watching: bool,
|
|
/// Whether the client applies a `workspace/applyEdit` request. A client
|
|
/// that cannot gets a command's edit back as the request result instead,
|
|
/// which is what every client got before this was read.
|
|
pub apply_edit: bool,
|
|
/// Whether the client *pulls* diagnostics (LSP 3.17). One client is never
|
|
/// served both models: a pulling client is pushed nothing at all.
|
|
pub pull_diagnostics: bool,
|
|
}
|
|
|
|
/// Everything the server owns.
|
|
pub struct Server {
|
|
connection: Connection,
|
|
workspace: Workspace,
|
|
/// Documents whose `lucisv.toml` problem has already been reported. Cleared
|
|
/// for a document whenever its text changes, so the warning is said once
|
|
/// per file change rather than once per format-on-save.
|
|
config_warnings: HashSet<Uri>,
|
|
abilities: ClientAbilities,
|
|
/// The id of the file-watcher registration in force, if any. Kept so a
|
|
/// changed `lucisv.filelist` can replace it: the watched filelist path is
|
|
/// part of the registration, so a new path needs a new registration.
|
|
watchers: Option<String>,
|
|
/// Numbers the file-watcher registrations, so a replacement can name the
|
|
/// one it supersedes.
|
|
registrations: u32,
|
|
/// Numbers the requests made *of* the client. A repeated id is a protocol
|
|
/// error, so this only ever counts up.
|
|
request_ids: u32,
|
|
/// The `workspace/applyEdit` requests still waiting for an answer, by the
|
|
/// id they were sent with, each remembering the command that asked for it
|
|
/// so a refusal can be named. Nothing else the server asks of the client
|
|
/// is recorded here, which is exactly what makes its answer ignorable.
|
|
applying: HashMap<RequestId, String>,
|
|
/// Counts everything that can change what a pull request would answer: a
|
|
/// buffer's text, and the workspace index. It is the whole of a
|
|
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
|
|
generation: u64,
|
|
}
|
|
|
|
impl Server {
|
|
pub fn new(
|
|
connection: Connection,
|
|
roots: Vec<std::path::PathBuf>,
|
|
abilities: ClientAbilities,
|
|
) -> Server {
|
|
let mut workspace = Workspace::default();
|
|
let warnings = workspace.open_roots(roots);
|
|
let mut server = Server {
|
|
connection,
|
|
workspace,
|
|
config_warnings: HashSet::new(),
|
|
abilities,
|
|
watchers: None,
|
|
registrations: 0,
|
|
request_ids: 0,
|
|
applying: HashMap::new(),
|
|
generation: 0,
|
|
};
|
|
server.report_scope(warnings);
|
|
// The earliest legal moment: `main` builds this only after
|
|
// `initialize_finish`, which returns once the client's `initialized`
|
|
// notification has arrived — and consumes it, so the loop below never
|
|
// sees one to hang the registration off instead.
|
|
server.register_watchers();
|
|
server
|
|
}
|
|
|
|
/// Receive until the client shuts us down or the channel closes.
|
|
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
|
while let Ok(message) = self.connection.receiver.recv() {
|
|
match message {
|
|
Message::Request(request) => {
|
|
if self.connection.handle_shutdown(&request)? {
|
|
return Ok(());
|
|
}
|
|
let response = self.request(request);
|
|
self.connection.sender.send(Message::Response(response))?;
|
|
}
|
|
Message::Notification(notification) => self.notification(notification),
|
|
Message::Response(response) => self.response(response),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// requests
|
|
// ------------------------------------------------------------------
|
|
|
|
fn request(&mut self, request: Request) -> Response {
|
|
let id = request.id.clone();
|
|
let method = request.method.clone();
|
|
let result = match method.as_str() {
|
|
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
|
|
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
|
|
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
|
|
let at = p.text_document_position_params;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
self.offset(&uri, position)
|
|
.map(|offset| hover::hover(&self.workspace, &uri, offset))
|
|
.map_or(Ok(Value::Null), to_value)
|
|
}),
|
|
GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| {
|
|
let at = p.text_document_position_params;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
let locations = self
|
|
.offset(&uri, position)
|
|
.map(|offset| nav::definition(&self.workspace, &uri, offset))
|
|
.unwrap_or_default();
|
|
to_value(GotoDefinitionResponse::Array(locations))
|
|
}),
|
|
// The underline half of include navigation. Unresolvable includes
|
|
// are simply absent from the list — never an error, and never a
|
|
// link that goes nowhere.
|
|
DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| {
|
|
to_value(includes::document_links(&self.workspace, &p.text_document.uri))
|
|
}),
|
|
References::METHOD => decode(request).and_then(|p: ReferenceParams| {
|
|
let include = p.context.include_declaration;
|
|
let at = p.text_document_position;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
let locations = self
|
|
.offset(&uri, position)
|
|
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
|
|
.unwrap_or_default();
|
|
to_value(locations)
|
|
}),
|
|
// Two answers behind one request: a scope keyword pairs with its
|
|
// own closer, and anything else is a symbol whose other
|
|
// occurrences in this file are what to draw. A cursor that is
|
|
// neither answers `null` rather than an empty list — an empty list
|
|
// means "no occurrences anywhere", which suppresses the editor's
|
|
// own word highlighting, and losing that everywhere would be a
|
|
// poor trade for gaining this.
|
|
DocumentHighlightRequest::METHOD => {
|
|
decode(request).and_then(|p: DocumentHighlightParams| {
|
|
let at = p.text_document_position_params;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
let found = self.offset(&uri, position).and_then(|offset| {
|
|
let doc = self.workspace.document(&uri)?;
|
|
pairs::highlights(doc, offset)
|
|
.or_else(|| nav::document_highlights(doc, offset))
|
|
});
|
|
found.map_or(Ok(Value::Null), to_value)
|
|
})
|
|
}
|
|
FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| {
|
|
match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) => to_value(folding::folding_ranges(doc)),
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
// Ghost port names on ordered connection lists. Range-scoped, as
|
|
// the protocol asks: the client sends the lines it is showing and
|
|
// gets the hints inside them.
|
|
InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| {
|
|
to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range))
|
|
}),
|
|
SemanticTokensFullRequest::METHOD => {
|
|
decode(request).and_then(|p: SemanticTokensParams| {
|
|
match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) => {
|
|
to_value(SemanticTokensResult::Tokens(tokens::semantic_tokens(doc)))
|
|
}
|
|
None => Ok(Value::Null),
|
|
}
|
|
})
|
|
}
|
|
DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| {
|
|
match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) => {
|
|
to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc)))
|
|
}
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| {
|
|
let uri = p.text_document.uri;
|
|
let only = p.context.only;
|
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
|
// A code-action request carries no `tabSize`, so the width a
|
|
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
|
// or from the built-in default.
|
|
let tab_width =
|
|
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
|
let mut actions =
|
|
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
|
|
// The port refactorings answer for the cursor, not for a range:
|
|
// the request's start is where the user is.
|
|
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
|
{
|
|
let offset = doc.positions().offset(p.range.start);
|
|
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
|
}
|
|
to_value(actions)
|
|
}),
|
|
// Custom method, so it is matched by name rather than through a
|
|
// `lsp_types::request` type. Nothing advertises it: a client that
|
|
// does not know it never asks.
|
|
pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| {
|
|
match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) => to_value(pairs::scope_pairs(doc)),
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
// A rename the engine declines comes back as a request error
|
|
// carrying its own sentence, which is what an editor shows in the
|
|
// rename box. `prepareRename` declines the same way, so the box
|
|
// never opens for a rename that would then fail.
|
|
PrepareRenameRequest::METHOD => {
|
|
decode(request).and_then(|at: TextDocumentPositionParams| {
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
let Some(offset) = self.offset(&uri, position) else {
|
|
return Ok(Value::Null);
|
|
};
|
|
match rename::prepare(&self.workspace, &uri, offset) {
|
|
Ok(response) => to_value(response),
|
|
Err(message) => Err(Failure::Request(message)),
|
|
}
|
|
})
|
|
}
|
|
Rename::METHOD => decode(request).and_then(|p: RenameParams| {
|
|
let new_name = p.new_name;
|
|
let at = p.text_document_position;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
let Some(offset) = self.offset(&uri, position) else {
|
|
return Ok(Value::Null);
|
|
};
|
|
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
|
Ok((edit, warnings)) => {
|
|
self.report_scope(warnings);
|
|
to_value(edit)
|
|
}
|
|
Err(message) => Err(Failure::Request(message)),
|
|
}
|
|
}),
|
|
// The port refactorings. A refusal is the engine's own sentence,
|
|
// returned as `RequestFailed` exactly as a declined rename is.
|
|
ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| {
|
|
match ports::execute(&self.workspace, &p.command, &p.arguments) {
|
|
Ok((edit, warnings)) => {
|
|
self.report_scope(warnings);
|
|
self.deliver(&p.command, edit)
|
|
}
|
|
Err(message) => Err(Failure::Request(message)),
|
|
}
|
|
}),
|
|
// Pull diagnostics, LSP 3.17. Same parse+lint pass the push model
|
|
// publishes; only the timing and the caching differ.
|
|
DocumentDiagnosticRequest::METHOD => {
|
|
decode(request).and_then(|p: DocumentDiagnosticParams| {
|
|
let report = self.document_report(&p.text_document.uri, p.previous_result_id);
|
|
to_value(DocumentDiagnosticReportResult::Report(report))
|
|
})
|
|
}
|
|
WorkspaceDiagnosticRequest::METHOD => {
|
|
decode(request).and_then(|p: WorkspaceDiagnosticParams| {
|
|
let report = self.workspace_report(&p.previous_result_ids);
|
|
to_value(WorkspaceDiagnosticReportResult::Report(report))
|
|
})
|
|
}
|
|
// Expand-selection. One chain per position, in the order asked —
|
|
// a client sends one position per cursor, and a multi-cursor
|
|
// editor matches the answers up by index.
|
|
SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| {
|
|
match self.workspace.document(&p.text_document.uri) {
|
|
Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)),
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
// Module hinting. A position that is not a module item answers
|
|
// `null` rather than an empty list, so the editor's own word
|
|
// completion is left in charge there.
|
|
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
|
|
let at = p.text_document_position;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
|
|
.map_or(Ok(Value::Null), to_value)
|
|
}),
|
|
// Ghost text. `null` for every position that is not one of the
|
|
// two triggers, which is nearly all of them — the request arrives
|
|
// on every keystroke, so the decline has to be the cheap path.
|
|
InlineCompletionRequest::METHOD => {
|
|
decode(request).and_then(|p: InlineCompletionParams| {
|
|
let at = p.text_document_position;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
inline::inline_completions(&self.workspace, &uri, position)
|
|
.map_or(Ok(Value::Null), to_value)
|
|
})
|
|
}
|
|
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
|
|
let at = p.text_document_position_params;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
self.offset(&uri, position)
|
|
.and_then(|offset| signature::signature_help(&self.workspace, &uri, offset))
|
|
.map_or(Ok(Value::Null), to_value)
|
|
}),
|
|
// The module hierarchy. `prepare` answers `null` for a position
|
|
// that is not a module name, which is what stops an editor from
|
|
// opening an empty hierarchy view; the two directions then answer
|
|
// one hop each, and the client drives the expansion.
|
|
CallHierarchyPrepare::METHOD => {
|
|
decode(request).and_then(|p: CallHierarchyPrepareParams| {
|
|
let at = p.text_document_position_params;
|
|
let (uri, position) = (at.text_document.uri, at.position);
|
|
self.offset(&uri, position)
|
|
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
|
|
.map_or(Ok(Value::Null), to_value)
|
|
})
|
|
}
|
|
CallHierarchyIncomingCalls::METHOD => {
|
|
decode(request).and_then(|p: CallHierarchyIncomingCallsParams| {
|
|
to_value(hierarchy::incoming(&self.workspace, &p.item))
|
|
})
|
|
}
|
|
CallHierarchyOutgoingCalls::METHOD => {
|
|
decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| {
|
|
to_value(hierarchy::outgoing(&self.workspace, &p.item))
|
|
})
|
|
}
|
|
WorkspaceSymbolRequest::METHOD => {
|
|
decode(request).and_then(|p: WorkspaceSymbolParams| {
|
|
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
|
|
&self.workspace,
|
|
&p.query,
|
|
)))
|
|
})
|
|
}
|
|
_ => Err(Failure::MethodNotFound(method)),
|
|
};
|
|
match result {
|
|
Ok(value) => Response::new_ok(id, value),
|
|
Err(failure) => failure.into_response(id),
|
|
}
|
|
}
|
|
|
|
fn formatting(&mut self, params: DocumentFormattingParams) -> Result<Value, Failure> {
|
|
let uri = params.text_document.uri;
|
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
|
let result = format::formatting(doc, &settings.config);
|
|
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
|
|
// one, but an editor that refuses to format because of a typo in a
|
|
// config file is an editor the user turns off. The buffer is formatted
|
|
// with the built-in defaults, and the reason is said once per change of
|
|
// the file — a format-on-save loop would otherwise repeat it forever.
|
|
self.warn_about_config(&uri, settings.problem);
|
|
self.edits(result)
|
|
}
|
|
|
|
/// `textDocument/rangeFormatting`, on the same engine and the same
|
|
/// all-or-nothing contract as whole-document formatting.
|
|
fn range_formatting(
|
|
&mut self,
|
|
params: DocumentRangeFormattingParams,
|
|
) -> Result<Value, Failure> {
|
|
let uri = params.text_document.uri;
|
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
|
let result = format::range_formatting(doc, &settings.config, params.range);
|
|
self.warn_about_config(&uri, settings.problem);
|
|
self.edits(result)
|
|
}
|
|
|
|
/// Say once per change of a file that its `lucisv.toml` could not be read.
|
|
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
|
|
if let Some(problem) = problem {
|
|
if self.config_warnings.insert(uri.clone()) {
|
|
self.show_message(
|
|
MessageType::WARNING,
|
|
format!("lucisv: {problem} — formatting with default settings"),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One edit, none, or — when the formatter refused — none plus the reason.
|
|
///
|
|
/// It never emits partial output (CLAUDE.md invariant #1), so neither do
|
|
/// we. Diagnostics are not used for the failure: they belong to the parse
|
|
/// pass and are cleared on the next keystroke, which would erase an
|
|
/// explicit format failure the user asked for.
|
|
fn edits(
|
|
&mut self,
|
|
result: Result<Option<lsp_types::TextEdit>, String>,
|
|
) -> Result<Value, Failure> {
|
|
match result {
|
|
Ok(Some(edit)) => to_value(vec![edit]),
|
|
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
|
|
Err(message) => {
|
|
self.show_message(MessageType::ERROR, format!("lucisv: cannot format — {message}"));
|
|
to_value(Vec::<lsp_types::TextEdit>::new())
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Deliver a command's `WorkspaceEdit` the way the client can take it.
|
|
///
|
|
/// The protocol has no place for an edit in an `executeCommand` *result*:
|
|
/// a client applies what a server pushes with `workspace/applyEdit`, and
|
|
/// drops the result on the floor. So the edit is pushed and the result is
|
|
/// `null` — except for a client that never advertised `workspace.applyEdit`,
|
|
/// which gets the old return-the-edit behavior because for that one it is
|
|
/// the only behavior that could ever work.
|
|
///
|
|
/// The push goes out *before* the command's own response, which the loop
|
|
/// sends when this returns. The protocol allows a server to request at any
|
|
/// time, and a client that waited for the command result before applying
|
|
/// the edit would deadlock on any server that does this — VS Code and
|
|
/// Neovim both apply it immediately.
|
|
fn deliver(&mut self, command: &str, edit: WorkspaceEdit) -> Result<Value, Failure> {
|
|
if !self.abilities.apply_edit {
|
|
return to_value(edit);
|
|
}
|
|
let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit };
|
|
let id = self.send_request(ApplyWorkspaceEdit::METHOD, params);
|
|
self.applying.insert(id, command.to_string());
|
|
Ok(Value::Null)
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// pull diagnostics
|
|
// ------------------------------------------------------------------
|
|
|
|
/// One buffer's diagnostics, or an unchanged report when nothing that
|
|
/// feeds them has moved since the client's last pull.
|
|
fn document_report(&self, uri: &Uri, previous: Option<String>) -> DocumentDiagnosticReport {
|
|
let result_id = self.result_id();
|
|
if previous.as_deref() == Some(result_id.as_str()) {
|
|
let unchanged = UnchangedDocumentDiagnosticReport { result_id };
|
|
return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
|
|
related_documents: None,
|
|
unchanged_document_diagnostic_report: unchanged,
|
|
});
|
|
}
|
|
let full = FullDocumentDiagnosticReport {
|
|
result_id: Some(result_id),
|
|
items: self.diagnostics_of(uri),
|
|
};
|
|
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
|
|
related_documents: None,
|
|
full_document_diagnostic_report: full,
|
|
})
|
|
}
|
|
|
|
/// Every open buffer's diagnostics, in URI order so two pulls of the same
|
|
/// state read the same way.
|
|
///
|
|
/// Open buffers are the whole scope: this server has never diagnosed a
|
|
/// file it was not shown, and pulling would be the wrong place to start —
|
|
/// linting the workspace on a keystroke-driven request is a rescan of
|
|
/// every file per pull. The limit is stated in the feature README.
|
|
fn workspace_report(&self, previous: &[PreviousResultId]) -> WorkspaceDiagnosticReport {
|
|
let result_id = self.result_id();
|
|
let mut uris = self.workspace.open_uris();
|
|
uris.sort();
|
|
let items = uris
|
|
.into_iter()
|
|
.map(|uri| {
|
|
let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id);
|
|
if known {
|
|
let unchanged =
|
|
UnchangedDocumentDiagnosticReport { result_id: result_id.clone() };
|
|
return WorkspaceDocumentDiagnosticReport::Unchanged(
|
|
WorkspaceUnchangedDocumentDiagnosticReport {
|
|
uri,
|
|
version: None,
|
|
unchanged_document_diagnostic_report: unchanged,
|
|
},
|
|
);
|
|
}
|
|
let full = FullDocumentDiagnosticReport {
|
|
result_id: Some(result_id.clone()),
|
|
items: self.diagnostics_of(&uri),
|
|
};
|
|
WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport {
|
|
uri,
|
|
version: None,
|
|
full_document_diagnostic_report: full,
|
|
})
|
|
})
|
|
.collect();
|
|
WorkspaceDiagnosticReport { items }
|
|
}
|
|
|
|
/// What a report is stamped with: the generation everything was computed
|
|
/// against. Coarse on purpose — a change anywhere costs one extra full
|
|
/// report elsewhere, and a stale "unchanged" would cost a wrong squiggle.
|
|
fn result_id(&self) -> String {
|
|
self.generation.to_string()
|
|
}
|
|
|
|
/// Everything the server has to say about a buffer — the one computation
|
|
/// both diagnostic models answer from. A buffer that is not open has
|
|
/// nothing said about it.
|
|
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
|
|
self.workspace.document(uri).map(diagnostics::all).unwrap_or_default()
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// notifications
|
|
// ------------------------------------------------------------------
|
|
|
|
fn notification(&mut self, notification: Notification) {
|
|
let method = notification.method.clone();
|
|
match method.as_str() {
|
|
DidOpenTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
|
let uri = p.text_document.uri;
|
|
self.set_document(uri.clone(), p.text_document.text);
|
|
// With no workspace root the index's scope *is* the open
|
|
// buffers' own directories, so opening a file widens it.
|
|
// With a root, nothing about the scope changed and the
|
|
// save path still owns rebuilding.
|
|
if self.workspace.has_roots() {
|
|
self.publish(&uri);
|
|
} else {
|
|
self.reindex();
|
|
}
|
|
}
|
|
}
|
|
DidChangeTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
|
// Incremental sync: the changes are ranges into the buffer
|
|
// we hold, applied in order. A full-sync client's
|
|
// rangeless change still replaces the whole buffer, so
|
|
// "the last one wins" stays true for it. One notification
|
|
// is one `set_document` — one reparse, one generation
|
|
// bump — however many ranges it carried.
|
|
if p.content_changes.is_empty() {
|
|
return;
|
|
}
|
|
let uri = p.text_document.uri;
|
|
let base = self.workspace.document(&uri).map_or("", |doc| doc.text.as_str());
|
|
let text = sync::apply_changes(base, &p.content_changes);
|
|
self.set_document(uri.clone(), text);
|
|
self.publish(&uri);
|
|
}
|
|
}
|
|
DidSaveTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
|
|
if let Some(text) = p.text {
|
|
self.set_document(p.text_document.uri.clone(), text);
|
|
}
|
|
// A save is one of the things that rebuild the index; the
|
|
// others are a change to `lucisv.exclude`/`lucisv.filelist`
|
|
// below, and a watched file changing on disk. The
|
|
// staleness window that is left is in the feature README.
|
|
self.reindex();
|
|
}
|
|
}
|
|
// Something changed on disk that no buffer told us about — a `git
|
|
// pull`, a checkout, a generated file, an externally edited
|
|
// filelist. One rebuild per *notification*, never one per file:
|
|
// the params carry a list, and a checkout fills it.
|
|
DidChangeWatchedFiles::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
|
|
let filelist = self.workspace.filelist_path();
|
|
if watch::touches_scope(&p.changes, filelist.as_deref()) {
|
|
self.reindex();
|
|
}
|
|
}
|
|
}
|
|
// The `lucisv.*` settings, pushed at startup and on every change.
|
|
// Nothing here trusts the payload — `settings::from_payload`
|
|
// drops whatever it cannot use.
|
|
DidChangeConfiguration::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
|
|
let pushed = settings::from_payload(&p.settings);
|
|
let watched = self.workspace.filelist_path();
|
|
// Only `exclude` and `filelist` change which files exist
|
|
// as far as this server is concerned; the other two are
|
|
// read afresh by the next formatting request and need no
|
|
// invalidation.
|
|
if self.workspace.set_client_settings(pushed) {
|
|
self.reindex();
|
|
}
|
|
// The watched filelist path is baked into the
|
|
// registration, so a new one needs a new registration.
|
|
if self.workspace.filelist_path() != watched {
|
|
self.register_watchers();
|
|
}
|
|
}
|
|
}
|
|
DidCloseTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
|
let uri = p.text_document.uri;
|
|
self.config_warnings.remove(&uri);
|
|
self.workspace.close_document(&uri);
|
|
// Clear what we drew: the buffer is gone.
|
|
self.send_diagnostics(uri, Vec::new());
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// responses to what we asked
|
|
// ------------------------------------------------------------------
|
|
|
|
/// What the client answered.
|
|
///
|
|
/// Only a `workspace/applyEdit` answer is read. The (un)registration of
|
|
/// the file watchers is the other thing ever asked, and there is nothing
|
|
/// to do with *its* answer: a client that refuses simply keeps the
|
|
/// save-only staleness model, and it says so on its own log, not ours. Its
|
|
/// ids are never in `applying`, so they fall out here.
|
|
fn response(&mut self, response: Response) {
|
|
let Some(command) = self.applying.remove(&response.id) else { return };
|
|
// A refusal is worth saying out loud: the user ran a command, watched
|
|
// nothing happen, and would otherwise have no idea why. An answer that
|
|
// does not parse is a refusal too — nothing was seen to be applied.
|
|
let reason = match response.response_result {
|
|
Ok(value) => match serde_json::from_value::<ApplyWorkspaceEditResponse>(value) {
|
|
Ok(applied) if applied.applied => return,
|
|
Ok(applied) => applied.failure_reason,
|
|
Err(problem) => Some(problem.to_string()),
|
|
},
|
|
Err(error) => Some(error.message),
|
|
};
|
|
let message = match reason {
|
|
Some(reason) => {
|
|
format!("lucisv: {command} — the editor did not apply the edit: {reason}")
|
|
}
|
|
None => format!("lucisv: {command} — the editor did not apply the edit."),
|
|
};
|
|
self.show_message(MessageType::ERROR, message);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// outgoing
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Ask the client to watch the source files and the filelist for us,
|
|
/// replacing any registration already in force.
|
|
///
|
|
/// Silent for a client that cannot be asked — that one keeps the save-only
|
|
/// staleness model, which is what it had before this feature existed.
|
|
fn register_watchers(&mut self) {
|
|
if !self.abilities.file_watching {
|
|
return;
|
|
}
|
|
// Unregister first, so a client that keys watchers by id is never
|
|
// holding two registrations that both fire for `**/*.sv`.
|
|
if let Some(id) = self.watchers.take() {
|
|
let params = UnregistrationParams { unregisterations: vec![watch::unregistration(id)] };
|
|
self.send_request(UnregisterCapability::METHOD, params);
|
|
}
|
|
let filelist = self.workspace.filelist_path();
|
|
let registration = watch::registration(self.registrations, filelist.as_deref());
|
|
self.registrations += 1;
|
|
self.watchers = Some(registration.id.clone());
|
|
let params = RegistrationParams { registrations: vec![registration] };
|
|
self.send_request(RegisterCapability::METHOD, params);
|
|
}
|
|
|
|
/// Ask the client something, reporting the id it will answer on — a
|
|
/// repeated id is a protocol error, so this only ever counts up.
|
|
fn send_request(&mut self, method: &str, params: impl serde::Serialize) -> RequestId {
|
|
let id = RequestId::from(format!("lucisv-{}", self.request_ids));
|
|
self.request_ids += 1;
|
|
let request = Request::new(id.clone(), method.to_string(), params);
|
|
// A closed channel means the client is gone; there is nobody left to
|
|
// report the failure to.
|
|
let _ = self.connection.sender.send(Message::Request(request));
|
|
id
|
|
}
|
|
|
|
/// Rescan the workspace and republish every open buffer against the new
|
|
/// index. Every caller changed what the index should contain — a save, a
|
|
/// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk.
|
|
fn reindex(&mut self) {
|
|
let warnings = self.workspace.rebuild_index();
|
|
// Every open buffer's diagnostics are computed against the index, so a
|
|
// pulling client's cached answers are all stale from here.
|
|
self.generation += 1;
|
|
self.report_scope(warnings);
|
|
for uri in self.workspace.open_uris() {
|
|
self.publish(&uri);
|
|
}
|
|
}
|
|
|
|
/// Say what went wrong while working out which files to index — a
|
|
/// filelist naming a file that has moved, an unset variable, an option
|
|
/// lucisv does not know.
|
|
///
|
|
/// Every one is logged, but only the first is *shown*: a filelist that has
|
|
/// drifted from the tree can easily carry forty stale paths, and forty
|
|
/// popups would be worse than the problem. Said once per rebuild, which is
|
|
/// once per save — the same rhythm the `lucisv.toml` warning has.
|
|
fn report_scope(&self, warnings: Vec<String>) {
|
|
for warning in &warnings {
|
|
self.notify(
|
|
LogMessage::METHOD,
|
|
LogMessageParams {
|
|
typ: MessageType::WARNING,
|
|
message: format!("lucisv: {warning}"),
|
|
},
|
|
);
|
|
}
|
|
let Some(first) = warnings.first() else { return };
|
|
let rest = warnings.len() - 1;
|
|
let message = match rest {
|
|
0 => format!("lucisv: {first}"),
|
|
_ => format!("lucisv: {first} (and {rest} more — see the lucisv log)"),
|
|
};
|
|
self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message });
|
|
}
|
|
|
|
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
|
|
/// has moved on, and a config problem is worth saying once more.
|
|
fn set_document(&mut self, uri: Uri, text: String) {
|
|
self.config_warnings.remove(&uri);
|
|
self.workspace.set_document(uri, text);
|
|
self.generation += 1;
|
|
}
|
|
|
|
/// Publish everything known about a buffer — parse errors and lint
|
|
/// warnings — in one notification. Two publishes for one version would
|
|
/// leave only the second on screen, since LSP replaces rather than merges.
|
|
fn publish(&self, uri: &Uri) {
|
|
// `send_diagnostics` would drop this anyway for a pulling client; the
|
|
// early return is so the parse+lint pass is not run for nobody, once
|
|
// per open buffer, on every index rebuild.
|
|
if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() {
|
|
return;
|
|
}
|
|
self.send_diagnostics(uri.clone(), self.diagnostics_of(uri));
|
|
}
|
|
|
|
/// Push one buffer's diagnostics — unless the client pulls them.
|
|
///
|
|
/// A client that advertised `textDocument.diagnostic` owns the timing and
|
|
/// the lifecycle of every diagnostic it shows: it asks when it wants them
|
|
/// and drops them when it closes the document, so a push would be a second
|
|
/// set of squiggles arriving on a schedule it did not choose. This is the
|
|
/// one gate that keeps the two models from ever running for one client —
|
|
/// the `didClose` clear goes through here too, for the same reason.
|
|
fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
|
|
if self.abilities.pull_diagnostics {
|
|
return;
|
|
}
|
|
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
|
|
self.notify(PublishDiagnostics::METHOD, params);
|
|
}
|
|
|
|
fn show_message(&self, typ: MessageType, message: String) {
|
|
self.notify(ShowMessage::METHOD, ShowMessageParams { typ, message: message.clone() });
|
|
self.notify(LogMessage::METHOD, LogMessageParams { typ, message });
|
|
}
|
|
|
|
fn notify(&self, method: &str, params: impl serde::Serialize) {
|
|
let notification = Notification::new(method.to_string(), params);
|
|
// A closed channel means the client is gone; there is nobody left to
|
|
// report the failure to.
|
|
let _ = self.connection.sender.send(Message::Notification(notification));
|
|
}
|
|
|
|
/// The byte offset an LSP position names in an open document.
|
|
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
|
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// decoding and failures
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Why a request could not be answered, in the protocol's own terms.
|
|
enum Failure {
|
|
MethodNotFound(String),
|
|
InvalidParams(String),
|
|
Internal(String),
|
|
/// The request was well-formed and the server declined it, with a reason
|
|
/// meant for the user — LSP's `RequestFailed`.
|
|
Request(String),
|
|
}
|
|
|
|
impl Failure {
|
|
fn into_response(self, id: RequestId) -> Response {
|
|
let (code, message) = match self {
|
|
Failure::MethodNotFound(method) => (
|
|
lsp_server::ErrorCode::MethodNotFound as i32,
|
|
format!("unhandled method: {method}"),
|
|
),
|
|
Failure::InvalidParams(message) => {
|
|
(lsp_server::ErrorCode::InvalidParams as i32, message)
|
|
}
|
|
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
|
|
Failure::Request(message) => {
|
|
(lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}"))
|
|
}
|
|
};
|
|
Response::new_err(id, code, message)
|
|
}
|
|
}
|
|
|
|
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
|
|
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
|
|
}
|
|
|
|
fn to_value(value: impl serde::Serialize) -> Result<Value, Failure> {
|
|
serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string()))
|
|
}
|
|
|
|
/// A notification's params, or `Err` when they do not parse — a malformed
|
|
/// notification is dropped, because there is no id to answer it on.
|
|
fn extract<P: DeserializeOwned>(
|
|
notification: Notification,
|
|
) -> Result<P, ExtractError<Notification>> {
|
|
let method = notification.method.clone();
|
|
notification.extract(&method)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::path::{Path, PathBuf};
|
|
use std::str::FromStr;
|
|
|
|
use lsp_types::{FileChangeType, FileEvent};
|
|
|
|
use crate::uri::path_to_uri;
|
|
|
|
/// A scratch workspace root, removed on drop.
|
|
struct Tree {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl Tree {
|
|
fn new(name: &str) -> Tree {
|
|
let path = std::env::temp_dir()
|
|
.join(format!("lucisv_server_watch_{}_{name}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
std::fs::create_dir_all(&path).expect("temp dir");
|
|
Tree { path }
|
|
}
|
|
|
|
/// A package declaring one localparam, so the index can be asked
|
|
/// whether this file was scanned at all.
|
|
fn package(&self, rel: &str, name: &str) {
|
|
let path = self.path.join(rel);
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).expect("parent");
|
|
}
|
|
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
|
|
.expect("write");
|
|
}
|
|
|
|
fn write(&self, rel: &str, text: &str) {
|
|
std::fs::write(self.path.join(rel), text).expect("write");
|
|
}
|
|
}
|
|
|
|
impl Drop for Tree {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
/// A real `Server` on an in-memory connection, plus the client end of it —
|
|
/// so a test can drive a notification and read every message it produced.
|
|
struct Session {
|
|
server: Server,
|
|
client: Connection,
|
|
}
|
|
|
|
impl Session {
|
|
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
|
Session::with(roots, ClientAbilities { file_watching, ..Default::default() })
|
|
}
|
|
|
|
/// A session against a client that said exactly `abilities`.
|
|
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
|
let (server_end, client) = Connection::memory();
|
|
let server = Server::new(server_end, roots, abilities);
|
|
Session { server, client }
|
|
}
|
|
|
|
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
|
|
self.server.notification(Notification::new(method.to_string(), params));
|
|
}
|
|
|
|
/// Drive one request through the real dispatch, as the loop would.
|
|
fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response {
|
|
let id = RequestId::from(format!("test-{method}"));
|
|
self.server.request(Request::new(id, method.to_string(), params))
|
|
}
|
|
|
|
/// A request's result, or the reason it was refused.
|
|
fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value {
|
|
match self.request(method, params).response_result {
|
|
Ok(value) => value,
|
|
Err(error) => panic!("{method} failed: {error:?}"),
|
|
}
|
|
}
|
|
|
|
/// Answer the last request the server made of us.
|
|
fn answer(&mut self, id: RequestId, result: impl serde::Serialize) {
|
|
self.server.response(Response::new_ok(id, result));
|
|
}
|
|
|
|
/// Everything the server has said since the last drain.
|
|
fn drain(&self) -> Vec<Message> {
|
|
self.client.receiver.try_iter().collect()
|
|
}
|
|
|
|
/// The requests the server has made of the client, as (method, params).
|
|
fn requests(&self) -> Vec<(String, Value)> {
|
|
self.sent().into_iter().map(|request| (request.method, request.params)).collect()
|
|
}
|
|
|
|
/// The requests the server has made of the client, ids included.
|
|
fn sent(&self) -> Vec<Request> {
|
|
self.drain()
|
|
.into_iter()
|
|
.filter_map(|message| match message {
|
|
Message::Request(request) => Some(request),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// 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
|
|
}
|
|
|
|
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 });
|
|
}
|
|
}
|
|
|
|
/// How many times the index holds a package of this name.
|
|
fn indexed(session: &Session, name: &str) -> usize {
|
|
session.server.workspace.index().member(name, "K").len()
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_did_not_ask_is_never_sent_a_registration() {
|
|
// Such a client keeps the save-only staleness model, and must not be
|
|
// sent a request it has no handler for.
|
|
let tree = Tree::new("noregister");
|
|
let session = Session::new(vec![tree.path.clone()], false);
|
|
assert!(session.requests().is_empty(), "nothing may be asked of it");
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_asked_is_registered_after_initialized() {
|
|
let tree = Tree::new("register");
|
|
let session = Session::new(vec![tree.path.clone()], true);
|
|
let requests = session.requests();
|
|
assert_eq!(requests.len(), 1, "{requests:#?}");
|
|
assert_eq!(requests[0].0, RegisterCapability::METHOD);
|
|
assert_eq!(
|
|
requests[0].1,
|
|
serde_json::json!({
|
|
"registrations": [{
|
|
"id": "lucisv-watched-files-0",
|
|
"method": "workspace/didChangeWatchedFiles",
|
|
"registerOptions": {
|
|
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
|
|
},
|
|
}]
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_configured_filelist_is_watched_too() {
|
|
let tree = Tree::new("registerfilelist");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
|
|
|
let session = Session::new(vec![tree.path.clone()], true);
|
|
let requests = session.requests();
|
|
let watchers = &requests[0].1["registrations"][0]["registerOptions"]["watchers"];
|
|
assert_eq!(
|
|
watchers,
|
|
&serde_json::json!([
|
|
{ "globPattern": "**/*.{v,vh,sv,svh}" },
|
|
{ "globPattern": tree.path.join("files.f").to_str().expect("utf-8") },
|
|
]),
|
|
"the filelist is watched by its own path"
|
|
);
|
|
}
|
|
|
|
/// A `lucisv.filelist` push, in the shape a client sends it.
|
|
fn filelist_push(path: &str) -> Value {
|
|
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
|
|
}
|
|
|
|
#[test]
|
|
fn a_new_filelist_setting_replaces_the_registration() {
|
|
// The watched path is baked into the registration, so the old one must
|
|
// go and a new one take its place — otherwise the new filelist is
|
|
// exactly the file nobody is watching.
|
|
let tree = Tree::new("rewatch");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
tree.write("other.f", "rtl/a.sv\n");
|
|
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
assert_eq!(session.requests().len(), 1, "the registration made at startup");
|
|
|
|
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
|
let requests = session.requests();
|
|
assert_eq!(requests.len(), 2, "{requests:#?}");
|
|
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
|
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-0");
|
|
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
|
let registration = &requests[1].1["registrations"][0];
|
|
assert_eq!(registration["id"], "lucisv-watched-files-1", "a fresh id");
|
|
assert_eq!(
|
|
registration["registerOptions"]["watchers"][1]["globPattern"],
|
|
tree.path.join("files.f").to_str().expect("utf-8").to_string()
|
|
);
|
|
|
|
// The same value again moves nothing, so nothing is re-registered.
|
|
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
|
assert!(session.requests().is_empty(), "re-pushing the same path is not a change");
|
|
|
|
// A different one is.
|
|
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
|
|
let requests = session.requests();
|
|
assert_eq!(requests.len(), 2, "{requests:#?}");
|
|
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-1");
|
|
assert_eq!(
|
|
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
|
tree.path.join("other.f").to_str().expect("utf-8").to_string()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_did_not_ask_is_not_re_registered_either() {
|
|
let tree = Tree::new("norewatch");
|
|
tree.write("files.f", "\n");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
|
assert!(session.requests().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn one_notification_rebuilds_the_index_once_however_many_files_it_names() {
|
|
// The `git checkout` shape. Rebuilding per event would re-scan the
|
|
// workspace once per changed file for a single answer.
|
|
let tree = Tree::new("oncepernotification");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(
|
|
&tree.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
|
|
|
for i in 0..40 {
|
|
tree.package(&format!("rtl/f{i}.sv"), &format!("p{i}"));
|
|
}
|
|
let changed: Vec<PathBuf> =
|
|
(0..40).map(|i| tree.path.join(format!("rtl/f{i}.sv"))).collect();
|
|
session.watched(&changed);
|
|
assert_eq!(session.publishes(), 1, "one rebuild for the whole list");
|
|
assert_eq!(indexed(&session, "p0"), 1, "and it really did rebuild");
|
|
assert_eq!(indexed(&session, "p39"), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn a_created_file_reaches_the_index_with_no_save_anywhere() {
|
|
let tree = Tree::new("created");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(
|
|
&tree.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
assert_eq!(indexed(&session, "pulled"), 0, "premise: not there yet");
|
|
|
|
tree.package("rtl/pulled.sv", "pulled");
|
|
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
|
assert_eq!(indexed(&session, "pulled"), 1, "the `git pull` case");
|
|
|
|
// ... and a deletion is a change in the other direction.
|
|
std::fs::remove_file(tree.path.join("rtl/pulled.sv")).expect("remove");
|
|
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
|
assert_eq!(indexed(&session, "pulled"), 0, "the `git checkout` case");
|
|
}
|
|
|
|
#[test]
|
|
fn an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing() {
|
|
// The ladder re-applies during the rebuild, so an unlisted file stays
|
|
// unlisted — and one rebuild for a stray in-tree source is cheaper than
|
|
// deciding, per event, whether the filelist names it.
|
|
let tree = Tree::new("outsidescope");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/unlisted.sv", "unlisted");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
|
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
|
|
|
|
session.watched(&[tree.path.join("rtl/unlisted.sv")]);
|
|
assert_eq!(indexed(&session, "a"), 1, "the listed file survives the rebuild");
|
|
assert_eq!(indexed(&session, "unlisted"), 0, "and the unlisted one stays out");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unrelated_file_event_costs_no_rebuild() {
|
|
let tree = Tree::new("stray");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(
|
|
&tree.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
|
|
|
session.watched(&[tree.path.join("README.md"), tree.path.join("target/build.log")]);
|
|
assert_eq!(session.publishes(), 0, "a stray event is dropped, not re-scanned");
|
|
|
|
session.notify(
|
|
DidChangeWatchedFiles::METHOD,
|
|
DidChangeWatchedFilesParams { changes: Vec::new() },
|
|
);
|
|
assert_eq!(session.publishes(), 0, "and so is an empty notification");
|
|
}
|
|
|
|
#[test]
|
|
fn an_open_buffer_still_beats_disk_after_a_watched_file_rebuild() {
|
|
// The rule the rebuild has always had, checked on the new path into
|
|
// it: an external change must never clobber what the user is looking
|
|
// at. Here the file on disk is *also* the open one, rewritten behind
|
|
// the editor's back — the buffer still wins.
|
|
let tree = Tree::new("overlay");
|
|
tree.package("rtl/open.sv", "on_disk");
|
|
let path = tree.path.join("rtl/open.sv");
|
|
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
|
|
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
|
|
|
|
tree.package("rtl/open.sv", "rewritten_on_disk");
|
|
session.watched(std::slice::from_ref(&path));
|
|
assert_eq!(indexed(&session, "in_buffer"), 1, "the buffer wins the rebuild");
|
|
assert_eq!(indexed(&session, "rewritten_on_disk"), 0, "disk loses");
|
|
assert_eq!(indexed(&session, "on_disk"), 0, "and the stale copy is gone");
|
|
let doc = session.server.workspace.document(&uri).expect("still open");
|
|
assert!(doc.text.contains("in_buffer"), "and the buffer's own text is untouched");
|
|
}
|
|
|
|
#[test]
|
|
fn the_uri_helper_and_the_watch_filter_agree_about_the_filelist() {
|
|
// `touches_scope` compares paths, and the path it compares against is
|
|
// whatever `filelist_path` resolved — a mismatch would silently stop
|
|
// filelist edits from rebuilding anything.
|
|
let tree = Tree::new("filelistevent");
|
|
tree.package("rtl/a.sv", "a");
|
|
tree.package("rtl/b.sv", "b");
|
|
tree.write("files.f", "rtl/a.sv\n");
|
|
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
|
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
|
let _ = session.drain();
|
|
assert_eq!(indexed(&session, "b"), 0, "premise: not listed yet");
|
|
|
|
tree.write("files.f", "rtl/a.sv\nrtl/b.sv\n");
|
|
session.watched(&[tree.path.join("files.f")]);
|
|
assert_eq!(session.publishes(), 1, "the filelist's own edit rebuilds");
|
|
assert_eq!(indexed(&session, "b"), 1, "and the newly listed file is in");
|
|
}
|
|
|
|
#[test]
|
|
fn a_malformed_watched_files_notification_is_dropped() {
|
|
let tree = Tree::new("malformed");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(
|
|
&tree.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
let _ = session.drain();
|
|
|
|
session.notify(DidChangeWatchedFiles::METHOD, serde_json::json!({ "changes": "nonsense" }));
|
|
assert_eq!(session.publishes(), 0, "no id to answer on, so nothing happens");
|
|
}
|
|
|
|
#[test]
|
|
fn a_non_file_uri_in_an_event_is_ignored() {
|
|
let tree = Tree::new("nonfileuri");
|
|
tree.package("rtl/open.sv", "open_pkg");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
session.open(
|
|
&tree.path.join("rtl/open.sv"),
|
|
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
|
);
|
|
let _ = session.drain();
|
|
|
|
let changes = vec![FileEvent {
|
|
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
|
|
typ: FileChangeType::CREATED,
|
|
}];
|
|
session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
|
|
assert_eq!(session.publishes(), 0);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `workspace/applyEdit`
|
|
// ------------------------------------------------------------------
|
|
|
|
const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
|
const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
|
|
|
/// A two-module workspace with `top.sv` open, and the arguments that ask
|
|
/// for the one port its instantiation is missing.
|
|
fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) {
|
|
let tree = Tree::new(name);
|
|
tree.write("sub.sv", SUB);
|
|
tree.write("top.sv", TOP);
|
|
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
|
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
|
let _ = session.drain();
|
|
let params = serde_json::json!({
|
|
"command": ports::PROPAGATE_PORTS,
|
|
"arguments": [uri, { "line": 2, "character": 6 }],
|
|
});
|
|
(tree, session, params)
|
|
}
|
|
|
|
#[test]
|
|
fn a_command_pushes_its_edit_when_the_client_can_apply_one() {
|
|
// The bug this fixes: the edit used to be the request *result*, which
|
|
// the protocol does not define and every stock client drops.
|
|
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
|
let (_tree, mut session, params) = propagating("applyedit", abilities);
|
|
|
|
let result = session.result(ExecuteCommand::METHOD, params);
|
|
assert_eq!(result, Value::Null, "the edit is not the result any more");
|
|
|
|
let sent = session.sent();
|
|
assert_eq!(sent.len(), 1, "{sent:#?}");
|
|
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
|
|
assert_eq!(
|
|
sent[0].params["label"],
|
|
serde_json::json!(format!("lucisv: {}", ports::PROPAGATE_PORTS)),
|
|
"the undo stack needs a name for it"
|
|
);
|
|
let changes = sent[0].params["edit"]["changes"].as_object().expect("changes");
|
|
let edits = changes.values().next().expect("one file edited");
|
|
assert_eq!(edits[0]["newText"], ", .rst(rst)", "{:#?}", sent[0].params);
|
|
}
|
|
|
|
#[test]
|
|
fn a_client_that_cannot_apply_edits_still_gets_the_edit_back() {
|
|
// The documented fallback: for such a client, returning the edit is
|
|
// the only thing that could ever work.
|
|
let (_tree, mut session, params) = propagating("noapplyedit", ClientAbilities::default());
|
|
|
|
let result = session.result(ExecuteCommand::METHOD, params);
|
|
let changes = result["changes"].as_object().expect("the edit is the result");
|
|
let edits = changes.values().next().expect("one file edited");
|
|
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
|
assert!(session.sent().is_empty(), "and nothing is pushed at it");
|
|
}
|
|
|
|
#[test]
|
|
fn an_edit_the_editor_refused_is_reported_to_the_user() {
|
|
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
|
let (_tree, mut session, params) = propagating("refused", abilities);
|
|
session.result(ExecuteCommand::METHOD, params);
|
|
let sent = session.sent();
|
|
let id = sent[0].id.clone();
|
|
|
|
session.answer(
|
|
id,
|
|
serde_json::json!({ "applied": false, "failureReason": "the file is read-only" }),
|
|
);
|
|
let shown = session.shown();
|
|
assert_eq!(shown.len(), 1, "{shown:#?}");
|
|
assert_eq!(shown[0].0, MessageType::ERROR);
|
|
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
|
assert!(shown[0].1.contains("the file is read-only"), "{}", shown[0].1);
|
|
}
|
|
|
|
#[test]
|
|
fn an_edit_the_editor_applied_is_said_nothing_about() {
|
|
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
|
let (_tree, mut session, params) = propagating("applied", abilities);
|
|
session.result(ExecuteCommand::METHOD, params);
|
|
let id = session.sent()[0].id.clone();
|
|
|
|
session.answer(id.clone(), serde_json::json!({ "applied": true }));
|
|
assert!(session.shown().is_empty(), "success is silent");
|
|
|
|
// And the id is spent: a duplicate answer says nothing either.
|
|
session.answer(id, serde_json::json!({ "applied": false }));
|
|
assert!(session.shown().is_empty(), "an answer to nothing is ignored");
|
|
}
|
|
|
|
#[test]
|
|
fn a_malformed_apply_edit_answer_is_reported_as_a_refusal() {
|
|
// QA attack: "a response that does not parse is a refusal" is stated
|
|
// in the Assumptions but was only exercised through `Err` results and
|
|
// a well-typed `applied: false`. This drives the branch where the
|
|
// payload is `Ok` JSON that does not deserialize as
|
|
// `ApplyWorkspaceEditResponse` at all (missing the required `applied`
|
|
// field) — the honest-refusal path, not a panic or a silent success.
|
|
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
|
let (_tree, mut session, params) = propagating("malformedapplyedit", abilities);
|
|
session.result(ExecuteCommand::METHOD, params);
|
|
let id = session.sent()[0].id.clone();
|
|
|
|
session.answer(id, serde_json::json!({ "notApplied": "whatever" }));
|
|
let shown = session.shown();
|
|
assert_eq!(shown.len(), 1, "an unparseable answer must still surface: {shown:#?}");
|
|
assert_eq!(shown[0].0, MessageType::ERROR);
|
|
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
|
}
|
|
|
|
#[test]
|
|
fn a_response_with_a_jsonrpc_error_is_reported_too() {
|
|
// The `Err` half of `response_result` — a client that rejects the
|
|
// `applyEdit` request outright at the JSON-RPC level, rather than
|
|
// answering it with `applied: false`.
|
|
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
|
let (_tree, mut session, params) = propagating("rpcerror", abilities);
|
|
session.result(ExecuteCommand::METHOD, params);
|
|
let id = session.sent()[0].id.clone();
|
|
|
|
session.server.response(Response::new_err(id, 1, "internal error".to_string()));
|
|
let shown = session.shown();
|
|
assert_eq!(shown.len(), 1, "{shown:#?}");
|
|
assert_eq!(shown[0].0, MessageType::ERROR);
|
|
assert!(shown[0].1.contains("internal error"), "{}", shown[0].1);
|
|
}
|
|
|
|
#[test]
|
|
fn a_watcher_registration_answer_is_still_ignored() {
|
|
// The one response that was always ignored must stay ignored now that
|
|
// responses are read at all — including an error one.
|
|
let tree = Tree::new("registeranswer");
|
|
let mut session = Session::new(vec![tree.path.clone()], true);
|
|
let id = session.sent()[0].id.clone();
|
|
session.answer(id.clone(), Value::Null);
|
|
session.server.response(Response::new_err(id, 1, "no thanks".to_string()));
|
|
assert!(session.shown().is_empty(), "nothing to tell the user");
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// pull diagnostics
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A client that pulls diagnostics rather than being pushed them.
|
|
fn pulling() -> ClientAbilities {
|
|
ClientAbilities { pull_diagnostics: true, ..Default::default() }
|
|
}
|
|
|
|
/// A buffer with one parse error and one lint finding in it.
|
|
const BROKEN: &str = "module m;\n\twire ;\nendmodule\n";
|
|
|
|
fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value {
|
|
session.result(
|
|
DocumentDiagnosticRequest::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"identifier": diagnostics::SOURCE,
|
|
"previousResultId": previous,
|
|
}),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn a_pulling_client_is_never_pushed_diagnostics() {
|
|
// Never both models for one client: the second set of squiggles would
|
|
// arrive on a schedule the client did not choose.
|
|
let tree = Tree::new("pullnopush");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let path = tree.path.join("m.sv");
|
|
let uri = session.open(&path, BROKEN);
|
|
assert_eq!(session.publishes(), 0, "`didOpen` pushed nothing");
|
|
|
|
session.notify(
|
|
DidChangeTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri, "version": 2 },
|
|
"contentChanges": [{ "text": BROKEN }],
|
|
}),
|
|
);
|
|
assert_eq!(session.publishes(), 0, "nor did a change");
|
|
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
assert_eq!(session.publishes(), 0, "nor a save's republish");
|
|
|
|
session.notify(
|
|
DidCloseTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
assert_eq!(session.publishes(), 0, "and the close clears nothing it never drew");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pushing_client_keeps_being_pushed() {
|
|
let tree = Tree::new("pushstays");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
session.open(&tree.path.join("m.sv"), BROKEN);
|
|
assert_eq!(session.publishes(), 1, "unchanged from before this feature");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pull_is_full_once_and_unchanged_until_something_moves() {
|
|
let tree = Tree::new("pullunchanged");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
|
|
|
let first = document_pull(&mut session, &uri, None);
|
|
assert_eq!(first["kind"], "full");
|
|
assert!(!first["items"].as_array().expect("items").is_empty(), "{first:#?}");
|
|
let result_id = first["resultId"].as_str().expect("a result id").to_string();
|
|
|
|
let again = document_pull(&mut session, &uri, Some(&result_id));
|
|
assert_eq!(again["kind"], "unchanged", "nothing moved: {again:#?}");
|
|
assert_eq!(again["resultId"], serde_json::json!(result_id), "and it stays namable");
|
|
|
|
// A buffer change moves it.
|
|
session.notify(
|
|
DidChangeTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri, "version": 2 },
|
|
"contentChanges": [{ "text": "module m;\n wire a;\nendmodule\n" }],
|
|
}),
|
|
);
|
|
let after = document_pull(&mut session, &uri, Some(&result_id));
|
|
assert_eq!(after["kind"], "full", "the buffer changed: {after:#?}");
|
|
assert!(after["items"].as_array().expect("items").is_empty(), "and it is clean now");
|
|
assert_ne!(after["resultId"], serde_json::json!(result_id), "a new stamp");
|
|
}
|
|
|
|
#[test]
|
|
fn an_index_rebuild_moves_the_result_id_too() {
|
|
// `inter_file_dependencies: true` is a promise: a save rebuilds the
|
|
// index, and what the index says can change what a *different* buffer
|
|
// reports. A stale "unchanged" there would be a wrong squiggle.
|
|
let tree = Tree::new("pullreindex");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
|
let stamp = document_pull(&mut session, &uri, None)["resultId"]
|
|
.as_str()
|
|
.expect("a result id")
|
|
.to_string();
|
|
|
|
session.notify(
|
|
DidSaveTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
|
);
|
|
let after = document_pull(&mut session, &uri, Some(&stamp));
|
|
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pull_for_a_buffer_that_is_not_open_is_empty_rather_than_an_error() {
|
|
let tree = Tree::new("pullclosed");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
|
let report = document_pull(&mut session, &uri, None);
|
|
assert_eq!(report["kind"], "full");
|
|
assert!(report["items"].as_array().expect("items").is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn the_workspace_pull_reports_every_open_buffer_and_honours_its_stamps() {
|
|
let tree = Tree::new("workspacepull");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
|
let second = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
|
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
|
);
|
|
let items = report["items"].as_array().expect("items").clone();
|
|
assert_eq!(items.len(), 2, "{report:#?}");
|
|
assert!(items.iter().all(|item| item["kind"] == "full"), "{report:#?}");
|
|
let uris: Vec<&str> = items.iter().map(|item| item["uri"].as_str().unwrap_or("")).collect();
|
|
assert!(uris.contains(&first.as_str()) && uris.contains(&second.as_str()), "{uris:?}");
|
|
let mut sorted = uris.clone();
|
|
sorted.sort_unstable();
|
|
assert_eq!(uris, sorted, "URI order, so two pulls of one state read alike");
|
|
let stamp = items[0]["resultId"].as_str().expect("a result id").to_string();
|
|
|
|
// Re-asked with what the client already holds, both come back unchanged.
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({
|
|
"identifier": diagnostics::SOURCE,
|
|
"previousResultIds": [
|
|
{ "uri": first, "value": stamp },
|
|
{ "uri": second, "value": stamp },
|
|
],
|
|
}),
|
|
);
|
|
let items = report["items"].as_array().expect("items");
|
|
assert_eq!(items.len(), 2);
|
|
assert!(items.iter().all(|item| item["kind"] == "unchanged"), "{items:#?}");
|
|
|
|
// A stamp from another generation is not the one we hold.
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({
|
|
"identifier": diagnostics::SOURCE,
|
|
"previousResultIds": [{ "uri": first, "value": "0" }],
|
|
}),
|
|
);
|
|
let items = report["items"].as_array().expect("items");
|
|
assert!(items.iter().all(|item| item["kind"] == "full"), "{items:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_workspace_answers_a_well_formed_empty_report() {
|
|
// QA attack: no open buffers at all — does `workspace/diagnostic`
|
|
// still answer a well-formed (if empty) report, rather than an error
|
|
// or a missing field?
|
|
let tree = Tree::new("workspaceemptypull");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
|
);
|
|
assert_eq!(report["items"], serde_json::json!([]), "{report:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless() {
|
|
// QA attack: the client's `previousResultIds` can name a document it
|
|
// has since closed (it does not have to prune its own cache eagerly).
|
|
// That URI is no longer among the open buffers `workspace_report`
|
|
// walks, so it must simply be absent from the answer — not an error,
|
|
// not a phantom entry.
|
|
let tree = Tree::new("workspaceclosedstamp");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
|
let closed = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
|
let stamp = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
|
)["items"][0]["resultId"]
|
|
.as_str()
|
|
.expect("a result id")
|
|
.to_string();
|
|
|
|
session.notify(
|
|
DidCloseTextDocument::METHOD,
|
|
serde_json::json!({ "textDocument": { "uri": closed } }),
|
|
);
|
|
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({
|
|
"identifier": diagnostics::SOURCE,
|
|
"previousResultIds": [
|
|
{ "uri": first, "value": stamp },
|
|
{ "uri": closed, "value": stamp },
|
|
],
|
|
}),
|
|
);
|
|
let items = report["items"].as_array().expect("items");
|
|
assert_eq!(items.len(), 1, "the closed uri is gone, not phantom-reported: {items:#?}");
|
|
assert_eq!(items[0]["uri"], first.as_str(), "{items:#?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_previous_result_id_for_a_uri_never_seen_is_ignored() {
|
|
// QA attack: a `previousResultIds` entry naming a document this
|
|
// server never opened (a client warm-starting from a stale cache, or
|
|
// simply a typo'd uri) must not confuse the match-up for the uris
|
|
// that *are* open.
|
|
let tree = Tree::new("workspaceneverseenstamp");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let opened = session.open(&tree.path.join("a.sv"), BROKEN);
|
|
let never_seen = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
|
|
|
let report = session.result(
|
|
WorkspaceDiagnosticRequest::METHOD,
|
|
serde_json::json!({
|
|
"identifier": diagnostics::SOURCE,
|
|
"previousResultIds": [{ "uri": never_seen, "value": "0" }],
|
|
}),
|
|
);
|
|
let items = report["items"].as_array().expect("items");
|
|
assert_eq!(items.len(), 1, "{items:#?}");
|
|
assert_eq!(items[0]["uri"], opened.as_str(), "{items:#?}");
|
|
assert_eq!(items[0]["kind"], "full");
|
|
}
|
|
|
|
#[test]
|
|
fn both_models_say_exactly_the_same_thing_about_a_buffer() {
|
|
// One computation, two deliveries. A second conversion path would be
|
|
// a second set of off-by-one bugs.
|
|
let tree = Tree::new("samediagnostics");
|
|
let mut pushed = Session::new(vec![tree.path.clone()], false);
|
|
pushed.open(&tree.path.join("m.sv"), BROKEN);
|
|
let published = pushed.published();
|
|
assert_eq!(published.len(), 1);
|
|
|
|
let mut pulled = Session::with(vec![tree.path.clone()], pulling());
|
|
let uri = pulled.open(&tree.path.join("m.sv"), BROKEN);
|
|
let report = document_pull(&mut pulled, &uri, None);
|
|
|
|
assert_eq!(
|
|
report["items"],
|
|
serde_json::to_value(&published[0].diagnostics).expect("diagnostics"),
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `textDocument/selectionRange`
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn a_selection_range_request_answers_one_chain_per_position() {
|
|
let tree = Tree::new("selection");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
|
let result = session.result(
|
|
SelectionRangeRequest::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"positions": [{ "line": 1, "character": 2 }, { "line": 0, "character": 0 }],
|
|
}),
|
|
);
|
|
let chains = result.as_array().expect("one chain per position");
|
|
assert_eq!(chains.len(), 2, "{result:#?}");
|
|
assert!(chains[0]["parent"].is_object(), "the innermost step has a parent");
|
|
}
|
|
|
|
#[test]
|
|
fn a_selection_range_request_for_an_unopened_buffer_answers_null() {
|
|
let tree = Tree::new("selectionclosed");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
|
let result = session.result(
|
|
SelectionRangeRequest::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"positions": [{ "line": 0, "character": 0 }],
|
|
}),
|
|
);
|
|
assert_eq!(result, Value::Null);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// incremental text sync
|
|
// ------------------------------------------------------------------
|
|
|
|
/// One `didChange`, carrying whatever changes were given.
|
|
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
|
|
session.notify(
|
|
DidChangeTextDocument::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri, "version": version },
|
|
"contentChanges": changes,
|
|
}),
|
|
);
|
|
}
|
|
|
|
/// The text the server currently holds for a buffer.
|
|
fn buffer(session: &Session, uri: &Uri) -> String {
|
|
session.server.workspace.document(uri).expect("an open buffer").text.clone()
|
|
}
|
|
|
|
#[test]
|
|
fn incremental_changes_land_the_same_buffer_as_one_full_change() {
|
|
let tree = Tree::new("incrementalsame");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
|
|
|
// Three ranges, each positioned against what the last one left.
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([
|
|
{ "range": { "start": { "line": 1, "character": 0 },
|
|
"end": { "line": 1, "character": 0 } }, "text": "\n" },
|
|
{ "range": { "start": { "line": 1, "character": 0 },
|
|
"end": { "line": 1, "character": 0 } }, "text": " wire " },
|
|
{ "range": { "start": { "line": 1, "character": 7 },
|
|
"end": { "line": 1, "character": 7 } }, "text": "w;" },
|
|
]),
|
|
);
|
|
let composed = "module m;\n wire w;\nendmodule\n";
|
|
assert_eq!(buffer(&session, &uri), composed);
|
|
|
|
// The same buffer reached by a full-sync client, for comparison.
|
|
let mut full = Session::new(vec![tree.path.clone()], false);
|
|
let other = full.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
|
change(&mut full, &other, 2, serde_json::json!([{ "text": composed }]));
|
|
assert_eq!(buffer(&full, &other), composed);
|
|
|
|
// And the answers computed from it agree, not just the text.
|
|
assert_eq!(
|
|
session.result(
|
|
Formatting::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": uri },
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
),
|
|
full.result(
|
|
Formatting::METHOD,
|
|
serde_json::json!({
|
|
"textDocument": { "uri": other },
|
|
"options": { "tabSize": 2, "insertSpaces": true },
|
|
}),
|
|
),
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn one_notification_is_one_generation_bump_however_many_ranges() {
|
|
// The pull-diagnostics `resultId` is this counter. One reparse and one
|
|
// stamp per notification: a bump per range would make every keystroke
|
|
// look like several to a pulling client, and none would make a
|
|
// changed buffer answer "unchanged".
|
|
let tree = Tree::new("incrementalgeneration");
|
|
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
|
|
|
let before = session.server.generation;
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([
|
|
{ "range": { "start": { "line": 0, "character": 9 },
|
|
"end": { "line": 0, "character": 9 } }, "text": "\n wire a;" },
|
|
{ "range": { "start": { "line": 1, "character": 9 },
|
|
"end": { "line": 1, "character": 9 } }, "text": "\n wire b;" },
|
|
{ "range": { "start": { "line": 2, "character": 7 },
|
|
"end": { "line": 2, "character": 8 } }, "text": "c" },
|
|
]),
|
|
);
|
|
assert_eq!(session.server.generation, before + 1, "one stamp per notification");
|
|
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire c;\nendmodule\n");
|
|
|
|
// An empty batch is not a change: nothing to reparse, nothing to stamp.
|
|
let stamp = session.server.generation;
|
|
change(&mut session, &uri, 3, serde_json::json!([]));
|
|
assert_eq!(session.server.generation, stamp, "an empty batch moves nothing");
|
|
}
|
|
|
|
#[test]
|
|
fn a_full_sync_clients_batch_still_lets_the_last_change_win() {
|
|
// A client that ignores the new capability and keeps sending whole
|
|
// buffers must behave exactly as it did before this feature.
|
|
let tree = Tree::new("incrementalfullsync");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([
|
|
{ "text": "module a;\nendmodule\n" },
|
|
{ "text": "module b;\nendmodule\n" },
|
|
{ "text": "module c;\nendmodule\n" },
|
|
]),
|
|
);
|
|
assert_eq!(buffer(&session, &uri), "module c;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_change_naming_a_buffer_that_was_never_opened_is_taken_as_written() {
|
|
// Out of protocol, but a full-text change used to be adopted whatever
|
|
// the state was, and still is: there is no base text to be wrong
|
|
// about. A *ranged* change against nothing lands its text at the
|
|
// start, which is the clamping rule, not a special case.
|
|
let tree = Tree::new("incrementalunopened");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
|
change(&mut session, &uri, 1, serde_json::json!([{ "text": "module m;\nendmodule\n" }]));
|
|
assert_eq!(buffer(&session, &uri), "module m;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_ranged_change_over_multi_byte_text_edits_the_right_columns() {
|
|
// The whole reason positions are converted rather than counted: the
|
|
// comment above the edited line is four characters and nine bytes.
|
|
let tree = Tree::new("incrementalunicode");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri =
|
|
session.open(&tree.path.join("m.sv"), "// é ✓ 🎉\nmodule m;\n wire a;\nendmodule\n");
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([{
|
|
"range": { "start": { "line": 2, "character": 7 },
|
|
"end": { "line": 2, "character": 8 } },
|
|
"text": "renamed",
|
|
}]),
|
|
);
|
|
assert_eq!(buffer(&session, &uri), "// é ✓ 🎉\nmodule m;\n wire renamed;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_ranged_change_republishes_diagnostics_for_what_it_produced() {
|
|
let tree = Tree::new("incrementalpublish");
|
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
|
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
|
let _ = session.published();
|
|
|
|
// Delete the `a`, leaving `wire ;` — a parse error.
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
2,
|
|
serde_json::json!([{
|
|
"range": { "start": { "line": 1, "character": 7 },
|
|
"end": { "line": 1, "character": 8 } },
|
|
"text": "",
|
|
}]),
|
|
);
|
|
let published = session.published();
|
|
assert_eq!(published.len(), 1, "one publish per notification: {published:#?}");
|
|
assert!(!published[0].diagnostics.is_empty(), "the broken buffer is reported");
|
|
|
|
// Put it back: the diagnostics clear.
|
|
change(
|
|
&mut session,
|
|
&uri,
|
|
3,
|
|
serde_json::json!([{
|
|
"range": { "start": { "line": 1, "character": 7 },
|
|
"end": { "line": 1, "character": 7 } },
|
|
"text": "a",
|
|
}]),
|
|
);
|
|
let published = session.published();
|
|
assert_eq!(published.len(), 1);
|
|
assert!(published[0].diagnostics.is_empty(), "{published:#?}");
|
|
}
|
|
}
|