range-formatting: --lines M-N[,M-N...] formats only the top-level
items intersecting the ranges; modules/packages split head/body/tail
with independent decisions, everything else is atomic, and
unselected units are emitted as merged verbatim source slices (the
run-merge is load-bearing: per-item slices let separators collapse
blank lines between untouched items). Convergence via Selection
replay -- same-selection re-runs are fixed points, sound because the
equivalence check has already proven token identity; QA's sabotage
of the replay failed immediately on real RTL. The honest limit
(same line numbers can sweep in a neighbor after lines move;
449/8236 corpus trials, all settled next run) is measured and
pinned. Fence wins over range; alignment groups split at verbatim
boundaries; cache fully bypassed; LSP rangeFormatting advertised and
consumes only lines (no UTF-16 column math); tools/vfmt-changed.sh
derives ranges from git diff. Default behavior provably unchanged
(TSV md5 + all-578-file byte-compare vs a pre-round binary).
lint-rules-2: visit.rs walks class bodies (closing the classes
handshake; +6 real findings in UVM code), five new rules with
evidence-based defaults -- parameter/enum/struct-union-name-style ON
with Verible's exact names and published defaults (vendored waivers
now honored), module-name-style OFF (Verible has no such rule; the
brief's premise was checked and corrected), wire-reg-mixup ON (0
corpus noise in .v, 209 findings on a .sv rename -- both zeroes
proven). rules_markdown() generates the rule reference; 13 rules
total, zero CLI/server wiring needed.
Also: lead notes in classes and shared-fence-filter READMEs
documenting the fence asymmetry lint-rules-2 QA found (a fence in a
class body protects fixes via the scan backstop even though the
formatter ignores it there).
768 workspace tests. Dev: 2 Opus agents; QA: 2 Sonnet agents;
reviews in docs/features/{range-formatting,lint-rules-2}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
355 lines
16 KiB
Rust
355 lines
16 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/vfmt-server/README.md`.
|
|
|
|
use std::collections::HashSet;
|
|
use std::error::Error;
|
|
|
|
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
|
|
use lsp_types::notification::{
|
|
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument,
|
|
LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
|
|
};
|
|
use lsp_types::request::{
|
|
CodeActionRequest, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest,
|
|
RangeFormatting, References, Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest,
|
|
};
|
|
use lsp_types::{
|
|
CodeActionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
|
|
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
|
|
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
|
|
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, LogMessageParams, MessageType,
|
|
Position, PublishDiagnosticsParams, ReferenceParams, SemanticTokensParams,
|
|
SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse,
|
|
};
|
|
use serde::de::DeserializeOwned;
|
|
use serde_json::Value;
|
|
|
|
use crate::state::Workspace;
|
|
use crate::{code_action, diagnostics, format, hover, nav, symbols, tokens};
|
|
|
|
/// Everything the server owns.
|
|
pub struct Server {
|
|
connection: Connection,
|
|
workspace: Workspace,
|
|
/// Documents whose `vfmt.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>,
|
|
}
|
|
|
|
impl Server {
|
|
pub fn new(connection: Connection, roots: Vec<std::path::PathBuf>) -> Server {
|
|
let mut workspace = Workspace::default();
|
|
workspace.open_roots(roots);
|
|
Server { connection, workspace, config_warnings: HashSet::new() }
|
|
}
|
|
|
|
/// 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),
|
|
// Nothing is requested *of* the client except the messages
|
|
// below, which want no answer.
|
|
Message::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))
|
|
}),
|
|
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)
|
|
}),
|
|
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;
|
|
match self.workspace.document(&uri) {
|
|
Some(doc) => {
|
|
// A code-action request carries no `tabSize`, so the
|
|
// width a `no-tabs` fix writes comes from the buffer's
|
|
// own `vfmt.toml` or from the built-in default.
|
|
let tab_width = format::indent_width(doc.path.as_deref());
|
|
to_value(code_action::code_actions(
|
|
&uri,
|
|
doc,
|
|
p.range,
|
|
p.context.only.as_deref(),
|
|
tab_width,
|
|
))
|
|
}
|
|
None => Ok(Value::Null),
|
|
}
|
|
}),
|
|
WorkspaceSymbolRequest::METHOD => {
|
|
decode(request).and_then(|p: WorkspaceSymbolParams| {
|
|
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
|
|
&self.workspace,
|
|
&p.query,
|
|
)))
|
|
})
|
|
}
|
|
_ => Err(Failure::MethodNotFound(method)),
|
|
};
|
|
match result {
|
|
Ok(value) => Response::new_ok(id, value),
|
|
Err(failure) => failure.into_response(id),
|
|
}
|
|
}
|
|
|
|
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, ¶ms.options);
|
|
let result = format::formatting(doc, &settings.config);
|
|
// A broken `vfmt.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, ¶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 `vfmt.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!("vfmt: {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!("vfmt: cannot format — {message}"));
|
|
to_value(Vec::<lsp_types::TextEdit>::new())
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// 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);
|
|
self.publish(&uri);
|
|
}
|
|
}
|
|
DidChangeTextDocument::METHOD => {
|
|
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
|
// Full-text sync: the last change carries the whole buffer.
|
|
if let Some(change) = p.content_changes.into_iter().next_back() {
|
|
let uri = p.text_document.uri;
|
|
self.set_document(uri.clone(), change.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);
|
|
}
|
|
// The index is rebuilt on save and nowhere else; the
|
|
// staleness window that opens is in the feature README.
|
|
self.workspace.rebuild_index();
|
|
for uri in self.workspace.open_uris() {
|
|
self.publish(&uri);
|
|
}
|
|
}
|
|
}
|
|
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());
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// outgoing
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Replace a buffer's text, re-arming its `vfmt.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);
|
|
}
|
|
|
|
/// 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) {
|
|
let Some(doc) = self.workspace.document(uri) else { return };
|
|
self.send_diagnostics(uri.clone(), diagnostics::all(doc));
|
|
}
|
|
|
|
fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
|
|
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),
|
|
}
|
|
|
|
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),
|
|
};
|
|
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)
|
|
}
|