//! LSP lifecycle, document synchronization, and diagnostic publication. use crate::diagnostics::{parse_diagnostics, DiagnosticData}; use crate::edits::workspace_edit; use crate::presentation::hover_for_line; use crate::VsgRunner; use serde_json::Value; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tokio::sync::RwLock; use tower_lsp::jsonrpc::{Error, Result}; use tower_lsp::lsp_types::{ CodeAction, CodeActionKind, CodeActionOptions, CodeActionOrCommand, CodeActionParams, CodeActionProviderCapability, CodeActionResponse, Command, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, ExecuteCommandOptions, ExecuteCommandParams, Hover, HoverParams, HoverProviderCapability, InitializeParams, InitializeResult, InitializedParams, MessageType, SaveOptions, ServerCapabilities, ShowDocumentParams, TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, TextDocumentSyncSaveOptions, Url, }; use tower_lsp::{Client, LanguageServer}; /// Server-owned command for opening VSG's rule documentation. const SHOW_RULE_DOCUMENTATION: &str = "vsg.showRuleDocumentation"; /// LSP source action implemented through VSG's normal formatter invocation. const FIX_ALL_KIND: CodeActionKind = CodeActionKind::new("source.fixAll.vsg"); /// Current contents and client version of an open document. #[derive(Clone, Debug)] struct Document { /// Complete current document text. text: String, /// Monotonically increasing version supplied by the LSP client. version: i32, /// Most recent validated diagnostics for this version. diagnostics: Vec, } /// VSG-backed implementation of the Language Server Protocol. #[derive(Debug)] pub struct Backend { /// Channel used to publish diagnostics and user-visible errors. client: Client, /// Replaceable VSG execution boundary. runner: Arc, /// Configuration arguments forwarded verbatim to VSG. vsg_arguments: Vec, /// In-memory full-text snapshots keyed by document URI. documents: RwLock>, /// Whether the initialized client accepts `window/showDocument` requests. show_document_supported: AtomicBool, /// Enables the opt-in multi-rule action without changing stable actions. experimental_multi_rule_line_fix: bool, } impl Backend { /// Creates a backend for one client connection. #[must_use] pub fn new(client: Client, runner: Arc, vsg_arguments: Vec) -> Self { Self { client, runner, vsg_arguments, documents: RwLock::new(HashMap::new()), show_document_supported: AtomicBool::new(false), experimental_multi_rule_line_fix: false, } } /// Enables or disables the experimental multi-rule line action. #[must_use] pub fn with_experimental_multi_rule_line_fix(mut self, enabled: bool) -> Self { self.experimental_multi_rule_line_fix = enabled; self } /// Runs VSG and publishes results only if the snapshot is still current. async fn lint_and_publish(&self, uri: Url, document: Document) { let result = self .runner .lint(&document.text, &self.vsg_arguments) .await .and_then(|output| parse_diagnostics(&output, &document.text)); match result { Ok(diagnostics) => { let mut documents = self.documents.write().await; let Some(current) = documents.get_mut(&uri) else { return; }; if current.version != document.version { return; } current.diagnostics.clone_from(&diagnostics); drop(documents); self.client .publish_diagnostics(uri, diagnostics, Some(document.version)) .await; } Err(error) => { if self.is_current(&uri, document.version).await { self.client .show_message(MessageType::ERROR, error.to_string()) .await; } } } } /// Reports whether a URI still refers to the supplied document version. async fn is_current(&self, uri: &Url, version: i32) -> bool { self.documents .read() .await .get(uri) .is_some_and(|document| document.version == version) } /// Returns the current snapshot for a URI, if the document is open. async fn snapshot(&self, uri: &Url) -> Option { self.documents.read().await.get(uri).cloned() } } /// Applies LSP's hierarchical `context.only` filtering to an offered action. fn action_kind_requested(parameters: &CodeActionParams, offered: &CodeActionKind) -> bool { parameters.context.only.as_ref().is_none_or(|requested| { requested.iter().any(|kind| { offered.as_str() == kind.as_str() || offered .as_str() .strip_prefix(kind.as_str()) .is_some_and(|suffix| suffix.starts_with('.')) }) }) } #[tower_lsp::async_trait] impl LanguageServer for Backend { async fn initialize(&self, parameters: InitializeParams) -> Result { let show_document_supported = parameters .capabilities .window .and_then(|window| window.show_document) .is_some_and(|capability| capability.support); self.show_document_supported .store(show_document_supported, Ordering::Relaxed); Ok(InitializeResult { capabilities: ServerCapabilities { text_document_sync: Some(TextDocumentSyncCapability::Options( TextDocumentSyncOptions { open_close: Some(true), change: Some(TextDocumentSyncKind::FULL), save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions { include_text: Some(true), })), ..TextDocumentSyncOptions::default() }, )), hover_provider: Some(HoverProviderCapability::Simple(true)), code_action_provider: Some(CodeActionProviderCapability::Options( CodeActionOptions { code_action_kinds: Some(vec![CodeActionKind::QUICKFIX, FIX_ALL_KIND]), resolve_provider: Some(false), ..CodeActionOptions::default() }, )), execute_command_provider: show_document_supported.then(|| ExecuteCommandOptions { commands: vec![SHOW_RULE_DOCUMENTATION.to_owned()], ..ExecuteCommandOptions::default() }), ..ServerCapabilities::default() }, ..InitializeResult::default() }) } async fn initialized(&self, _: InitializedParams) { self.client .log_message(MessageType::INFO, "VSG bridge initialized") .await; } async fn shutdown(&self) -> Result<()> { let open_uris: Vec<_> = self .documents .write() .await .drain() .map(|(uri, _)| uri) .collect(); for uri in open_uris { self.client.publish_diagnostics(uri, Vec::new(), None).await; } Ok(()) } async fn hover(&self, parameters: HoverParams) -> Result> { let text_document_position = parameters.text_document_position_params; let Some(document) = self .snapshot(&text_document_position.text_document.uri) .await else { return Ok(None); }; Ok(hover_for_line( &document.diagnostics, text_document_position.position.line, )) } async fn execute_command(&self, parameters: ExecuteCommandParams) -> Result> { if parameters.command != SHOW_RULE_DOCUMENTATION { return Err(Error::invalid_params("unknown VSG command")); } if !self.show_document_supported.load(Ordering::Relaxed) { return Err(Error::invalid_request()); } let url = parameters .arguments .first() .and_then(Value::as_str) .ok_or_else(|| Error::invalid_params("expected one documentation URL"))?; let url = Url::parse(url).map_err(|_| Error::invalid_params("invalid documentation URL"))?; if url.scheme() != "https" || url.host_str().is_none() { return Err(Error::invalid_params("documentation URL must use HTTPS")); } self.client .show_document(ShowDocumentParams { uri: url, external: Some(true), take_focus: Some(true), selection: None, }) .await?; Ok(None) } async fn code_action( &self, parameters: CodeActionParams, ) -> Result> { let uri = parameters.text_document.uri.clone(); let Some(document) = self.snapshot(&uri).await else { return Ok(None); }; let mut actions = Vec::new(); if action_kind_requested(¶meters, &CodeActionKind::QUICKFIX) { let mut selectors = std::collections::BTreeSet::new(); let mut documentation_urls = std::collections::BTreeSet::new(); let mut multi_rule_lines = std::collections::BTreeMap::< u32, (std::collections::BTreeSet, Vec<_>), >::new(); for requested in ¶meters.context.diagnostics { let Some(current) = document .diagnostics .iter() .find(|diagnostic| *diagnostic == requested) else { continue; }; let Some(value) = current.data.clone() else { continue; }; let Ok(data) = serde_json::from_value::(value) else { continue; }; if data.schema_version != 1 || data.rule.is_empty() || data.line == 0 { continue; } if data.metadata.fixable { let (rules, diagnostics) = multi_rule_lines.entry(data.line).or_default(); if rules.insert(data.rule.clone()) { diagnostics.push(current.clone()); } } if data.metadata.fixable && selectors.insert((data.rule.clone(), data.line)) { match self .runner .fix_rules( &document.text, &self.vsg_arguments, &[(data.rule.clone(), data.line)], ) .await { Ok(corrected) => { if !self.is_current(&uri, document.version).await { return Err(Error::invalid_request()); } if let Some(edit) = workspace_edit( uri.clone(), document.version, &document.text, &corrected, ) { actions.push(CodeActionOrCommand::CodeAction(CodeAction { title: format!( "{} (fix all {} findings on line {})", current.message, data.rule, data.line ), kind: Some(CodeActionKind::QUICKFIX), diagnostics: Some(vec![current.clone()]), edit: Some(edit), is_preferred: Some(true), ..CodeAction::default() })); } } Err(error) => { self.client .show_message(MessageType::ERROR, error.to_string()) .await; } } } if self.show_document_supported.load(Ordering::Relaxed) { if let Some(url) = data.metadata.documentation.rule { if documentation_urls.insert(url.clone()) { actions.push(CodeActionOrCommand::CodeAction(CodeAction { title: format!("Show {} documentation", data.rule), kind: Some(CodeActionKind::QUICKFIX), diagnostics: Some(vec![current.clone()]), command: Some(Command { title: "Show VSG rule documentation".to_owned(), command: SHOW_RULE_DOCUMENTATION.to_owned(), arguments: Some(vec![Value::String(url)]), }), ..CodeAction::default() })); } } } } if self.experimental_multi_rule_line_fix { for (line, (rules, diagnostics)) in multi_rule_lines { if rules.len() < 2 { continue; } let selectors: Vec<_> = rules.into_iter().map(|rule| (rule, line)).collect(); match self .runner .fix_rules(&document.text, &self.vsg_arguments, &selectors) .await { Ok(corrected) => { if !self.is_current(&uri, document.version).await { return Err(Error::invalid_request()); } if let Some(edit) = workspace_edit( uri.clone(), document.version, &document.text, &corrected, ) { actions.push(CodeActionOrCommand::CodeAction(CodeAction { title: format!( "Experimental: fix {} VSG rules on line {line}", selectors.len() ), kind: Some(CodeActionKind::QUICKFIX), diagnostics: Some(diagnostics), edit: Some(edit), ..CodeAction::default() })); } } Err(error) => { self.client .show_message(MessageType::ERROR, error.to_string()) .await; } } } } } if action_kind_requested(¶meters, &FIX_ALL_KIND) { match self .runner .fix_all(&document.text, &self.vsg_arguments) .await { Ok(corrected) => { if !self.is_current(&uri, document.version).await { return Err(Error::invalid_request()); } if let Some(edit) = workspace_edit(uri, document.version, &document.text, &corrected) { actions.push(CodeActionOrCommand::CodeAction(CodeAction { title: "Fix all VSG findings".to_owned(), kind: Some(FIX_ALL_KIND), edit: Some(edit), ..CodeAction::default() })); } } Err(error) => { self.client .show_message(MessageType::ERROR, error.to_string()) .await; } } } Ok((!actions.is_empty()).then_some(actions)) } async fn did_open(&self, parameters: DidOpenTextDocumentParams) { let uri = parameters.text_document.uri; let document = Document { text: parameters.text_document.text, version: parameters.text_document.version, diagnostics: Vec::new(), }; self.documents .write() .await .insert(uri.clone(), document.clone()); self.lint_and_publish(uri, document).await; } async fn did_change(&self, parameters: DidChangeTextDocumentParams) { let Some(change) = parameters.content_changes.into_iter().last() else { return; }; let uri = parameters.text_document.uri; let document = Document { text: change.text, version: parameters.text_document.version, diagnostics: Vec::new(), }; self.documents .write() .await .insert(uri.clone(), document.clone()); self.lint_and_publish(uri, document).await; } async fn did_save(&self, parameters: DidSaveTextDocumentParams) { let uri = parameters.text_document.uri; let Some(mut document) = self.snapshot(&uri).await else { return; }; if let Some(text) = parameters.text { document.text = text; document.diagnostics.clear(); self.documents .write() .await .insert(uri.clone(), document.clone()); } self.lint_and_publish(uri, document).await; } async fn did_close(&self, parameters: DidCloseTextDocumentParams) { let uri = parameters.text_document.uri; self.documents.write().await.remove(&uri); self.client.publish_diagnostics(uri, Vec::new(), None).await; } } #[cfg(test)] mod tests { //! In-process JSON-RPC tests for lifecycle and document synchronization. use super::{Backend, Document}; use crate::VsgRunner; use anyhow::{anyhow, Result}; use futures::{SinkExt, StreamExt}; use serde_json::{json, Value}; use std::sync::{Arc, Mutex}; use tokio::sync::Notify; use tokio::time::{timeout, Duration}; use tower::{Service, ServiceExt}; use tower_lsp::jsonrpc::{Request, Response}; use tower_lsp::lsp_types::{CodeActionParams, PublishDiagnosticsParams, TextDocumentSyncKind}; use tower_lsp::LspService; /// Empty valid VSG diagnostic protocol document. const EMPTY_DIAGNOSTICS: &str = r#"{"schema":"vsg.diagnostics","schema_version":1,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{},"diagnostics":[]}"#; /// Valid VSG result containing one warning. const ONE_DIAGNOSTIC: &str = r#"{"schema":"vsg.diagnostics","schema_version":1,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{"rule_001":{"severity":{"name":"Warning","type":"warning"},"fixable":true,"phase":1,"subphase":1,"configuration":{"disable":false},"documentation":{"rule":"https://example.com/rule-001","configuration":null}}},"diagnostics":[{"rule":"rule_001","location":{"start_line":1,"end_line":1},"message":"use lower case"}]}"#; /// Builds complete wire metadata for an action test rule. fn action_rule(fixable: bool) -> Value { json!({ "severity": {"name": "Warning", "type": "warning"}, "fixable": fixable, "phase": 1, "subphase": 1, "configuration": {"disable": false}, "documentation": {"rule": null, "configuration": null} }) } /// Builds a complete VSG diagnostic protocol fixture. fn action_document(rules: Value, diagnostics: Value) -> String { json!({ "schema": "vsg.diagnostics", "schema_version": 1, "tool": {"name": "vsg", "version": "3.35.0"}, "source": {"name": "stdin"}, "rules": rules, "diagnostics": diagnostics }) .to_string() } /// Deterministic runner that records inputs and returns a configured result. #[derive(Debug)] struct MockRunner { /// Source buffers received from the server. inputs: Mutex>, /// Arguments received from the server. arguments: Mutex>>, /// Output or error returned for each invocation. result: std::result::Result, } /// Runner whose response is held until a test changes document state. #[derive(Debug)] struct DelayedRunner { /// Signals that linting captured its source snapshot. started: Notify, /// Releases the pending lint result. release: Notify, } /// Runner that records correction requests and returns configured text. #[derive(Debug)] struct ActionRunner { /// Diagnostic protocol output returned before actions are requested. lint: String, /// Corrected text or scoped-fix failure. scoped: std::result::Result, /// Corrected text or fix-all failure. all: std::result::Result, /// Selectors received by scoped correction calls. selectors: Mutex>>, } /// Runner that pauses a scoped fix so version races can be exercised. #[derive(Debug)] struct DelayedActionRunner { /// Signals that correction started. started: Notify, /// Releases the correction result. release: Notify, } impl ActionRunner { /// Creates a runner with successful scoped and whole-document output. fn successful(scoped: &str, all: &str) -> Self { Self { lint: ONE_DIAGNOSTIC.to_owned(), scoped: Ok(scoped.to_owned()), all: Ok(all.to_owned()), selectors: Mutex::new(Vec::new()), } } } impl MockRunner { /// Creates a runner that returns fixed VSG output. fn successful(output: &str) -> Self { Self { inputs: Mutex::new(Vec::new()), arguments: Mutex::new(Vec::new()), result: Ok(output.to_owned()), } } /// Creates a runner that reports a fixed execution failure. fn failing(message: &str) -> Self { Self { inputs: Mutex::new(Vec::new()), arguments: Mutex::new(Vec::new()), result: Err(message.to_owned()), } } } #[tower_lsp::async_trait] impl VsgRunner for MockRunner { async fn lint(&self, source: &str, arguments: &[String]) -> Result { self.inputs .lock() .expect("input lock") .push(source.to_owned()); self.arguments .lock() .expect("argument lock") .push(arguments.to_vec()); self.result.clone().map_err(|message| anyhow!(message)) } } #[tower_lsp::async_trait] impl VsgRunner for DelayedRunner { async fn lint(&self, _: &str, _: &[String]) -> Result { self.started.notify_one(); self.release.notified().await; Ok(ONE_DIAGNOSTIC.to_owned()) } } #[tower_lsp::async_trait] impl VsgRunner for ActionRunner { async fn lint(&self, _: &str, _: &[String]) -> Result { Ok(self.lint.clone()) } async fn fix_rules( &self, _: &str, _: &[String], selectors: &[(String, u32)], ) -> Result { self.selectors .lock() .expect("selector lock") .push(selectors.to_vec()); self.scoped.clone().map_err(|message| anyhow!(message)) } async fn fix_all(&self, _: &str, _: &[String]) -> Result { self.all.clone().map_err(|message| anyhow!(message)) } } #[tower_lsp::async_trait] impl VsgRunner for DelayedActionRunner { async fn lint(&self, _: &str, _: &[String]) -> Result { Ok(ONE_DIAGNOSTIC.to_owned()) } async fn fix_rules(&self, _: &str, _: &[String], _: &[(String, u32)]) -> Result { self.started.notify_one(); self.release.notified().await; Ok("ENTITY demo IS".to_owned()) } } /// Initializes a test service and verifies the response is successful. async fn initialize(service: &mut LspService) -> Response { initialize_with(service, json!({})).await } /// Initializes a test service with explicit client capabilities. async fn initialize_with(service: &mut LspService, capabilities: Value) -> Response { let request = Request::build("initialize") .params(json!({"capabilities": capabilities})) .id(1) .finish(); service .ready() .await .expect("service ready") .call(request) .await .expect("initialize call") .expect("initialize response") } /// Sends an LSP notification through the service. async fn notify(service: &mut LspService, method: &'static str, params: Value) { let request = Request::build(method).params(params).finish(); let response = service .ready() .await .expect("service ready") .call(request) .await .expect("notification call"); assert!(response.is_none()); } /// Reads and deserializes one published diagnostic notification. async fn published_diagnostics( socket: &mut tower_lsp::ClientSocket, ) -> PublishDiagnosticsParams { let request = socket.next().await.expect("client notification"); assert_eq!(request.method(), "textDocument/publishDiagnostics"); serde_json::from_value(request.params().cloned().expect("notification params")) .expect("publish diagnostics params") } /// Requests code actions and returns the successful JSON-RPC result. async fn request_code_actions( service: &mut LspService, diagnostics: Value, only: Value, ) -> Value { let request = Request::build("textDocument/codeAction") .params(json!({ "textDocument": {"uri": "file:///tmp/example.vhd"}, "range": { "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 18} }, "context": {"diagnostics": diagnostics, "only": only} })) .id(9) .finish(); let response = service .ready() .await .expect("service ready") .call(request) .await .expect("code action call") .expect("code action response"); serde_json::to_value(response).expect("serialize response")["result"].clone() } /// Builds typed quick-fix parameters from current published diagnostics. fn quick_fix_parameters(diagnostics: &[tower_lsp::lsp_types::Diagnostic]) -> CodeActionParams { serde_json::from_value(json!({ "textDocument": {"uri": "file:///tmp/example.vhd"}, "range": { "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 18} }, "context": { "diagnostics": diagnostics, "only": ["quickfix"] } })) .expect("valid code action parameters") } /// Initialization advertises full synchronization and save text. #[tokio::test] async fn advertises_only_implemented_synchronization() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let (mut service, _socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); let response = initialize(&mut service).await; let value = serde_json::to_value(response).expect("serialize response"); assert_eq!( value["result"]["capabilities"]["textDocumentSync"]["change"], serde_json::to_value(TextDocumentSyncKind::FULL).expect("serialize sync kind") ); assert_eq!( value["result"]["capabilities"]["textDocumentSync"]["openClose"], json!(true) ); assert_eq!( value["result"]["capabilities"]["textDocumentSync"]["save"]["includeText"], json!(true) ); assert_eq!( value["result"]["capabilities"]["hoverProvider"], json!(true) ); assert_eq!( value["result"]["capabilities"]["codeActionProvider"]["codeActionKinds"], json!(["quickfix", "source.fixAll.vsg"]) ); assert!(value["result"]["capabilities"]["executeCommandProvider"].is_null()); } /// Documentation commands are advertised only to supporting clients. #[tokio::test] async fn advertises_documentation_command_to_supporting_clients() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let (mut service, _socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); let response = initialize_with( &mut service, json!({"window": {"showDocument": {"support": true}}}), ) .await; let value = serde_json::to_value(response).expect("serialize response"); assert_eq!( value["result"]["capabilities"]["executeCommandProvider"]["commands"], json!(["vsg.showRuleDocumentation"]) ); } /// The initialized notification emits one concise client log message. #[tokio::test] async fn logs_when_initialization_finishes() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify(&mut service, "initialized", json!({})).await; let request = socket.next().await.expect("log notification"); assert_eq!(request.method(), "window/logMessage"); assert_eq!( request.params().expect("log params")["message"], json!("VSG bridge initialized") ); } /// Opening an unsaved buffer lints its text and publishes parsed diagnostics. #[tokio::test] async fn lints_open_document_text() { let runner = Arc::new(MockRunner::successful(ONE_DIAGNOSTIC)); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| { Backend::new( client, runner.clone(), vec!["-c".to_owned(), "rules.yaml".to_owned()], ) }); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({ "textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 4, "text": "ENTITY demo IS" } }), ) .await; let published = published_diagnostics(&mut socket).await; assert_eq!(published.version, Some(4)); assert_eq!(published.diagnostics.len(), 1); assert_eq!(published.diagnostics[0].message, "use lower case"); assert_eq!( observed_runner .inputs .lock() .expect("input lock") .as_slice(), ["ENTITY demo IS"] ); assert_eq!( observed_runner .arguments .lock() .expect("argument lock") .as_slice(), [vec!["-c".to_owned(), "rules.yaml".to_owned()]] ); } /// Hover reads the current validated diagnostic metadata for a line. #[tokio::test] async fn provides_hover_for_current_diagnostic() { let runner = Arc::new(MockRunner::successful(ONE_DIAGNOSTIC)); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; published_diagnostics(&mut socket).await; let request = Request::build("textDocument/hover") .params(json!({ "textDocument": {"uri": "file:///tmp/example.vhd"}, "position": {"line": 0, "character": 2} })) .id(7) .finish(); let response = service .ready() .await .expect("service ready") .call(request) .await .expect("hover call") .expect("hover response"); let value = serde_json::to_value(response).expect("serialize response"); assert!(value["result"]["contents"]["value"] .as_str() .expect("Markdown hover") .contains("VSG `rule_001`")); } /// The documentation command delegates a validated HTTPS URL to the client. #[tokio::test] async fn opens_rule_documentation_for_supporting_client() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let (mut service, socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize_with( &mut service, json!({"window": {"showDocument": {"support": true}}}), ) .await; let (mut requests, mut responses) = socket.split(); let execute = async { let request = Request::build("workspace/executeCommand") .params(json!({ "command": "vsg.showRuleDocumentation", "arguments": ["https://example.com/rule-001"] })) .id(8) .finish(); service .ready() .await .expect("service ready") .call(request) .await .expect("execute command call") .expect("execute command response") }; let answer_client = async { let request = requests.next().await.expect("show document request"); assert_eq!(request.method(), "window/showDocument"); assert_eq!( request.params().expect("show document params")["uri"], json!("https://example.com/rule-001") ); responses .send(Response::from_ok( request.id().cloned().expect("show document request ID"), json!({"success": true}), )) .await .expect("answer show document request"); }; let (response, ()) = tokio::join!(execute, answer_client); assert!(response.is_ok()); } /// A fixable diagnostic produces a versioned rule-scoped quick fix. #[tokio::test] async fn provides_rule_scoped_quick_fix() { let runner = Arc::new(ActionRunner::successful("ENTITY demo IS", "unused")); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 4, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert_eq!(result[0]["kind"], json!("quickfix")); assert!(result[0]["title"] .as_str() .expect("action title") .contains("fix all rule_001 findings on line 1")); assert_eq!( result[0]["edit"]["documentChanges"][0]["textDocument"]["version"], json!(4) ); assert_eq!( observed_runner .selectors .lock() .expect("selector lock") .as_slice(), [vec![("rule_001".to_owned(), 1)]] ); } /// Multiple findings from one rule and line produce one scoped action. #[tokio::test] async fn deduplicates_same_rule_and_line() { let mut runner = ActionRunner::successful("ENTITY demo IS", "unused"); runner.lint = action_document( json!({"rule_001": action_rule(true)}), json!([ {"rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "first"}, {"rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "second"} ]), ); let runner = Arc::new(runner); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert_eq!(result.as_array().expect("action list").len(), 1); assert_eq!( observed_runner .selectors .lock() .expect("selector lock") .len(), 1 ); } /// Different rules on one line retain separate stable quick fixes. #[tokio::test] async fn keeps_different_rules_separate() { let mut runner = ActionRunner::successful("ENTITY demo IS", "unused"); runner.lint = action_document( json!({"rule_001": action_rule(true), "rule_002": action_rule(true)}), json!([ {"rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "first"}, {"rule": "rule_002", "location": {"start_line": 1, "end_line": 1}, "message": "second"} ]), ); let runner = Arc::new(runner); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert_eq!(result.as_array().expect("action list").len(), 2); assert_eq!( observed_runner .selectors .lock() .expect("selector lock") .as_slice(), [ vec![("rule_001".to_owned(), 1)], vec![("rule_002".to_owned(), 1)] ] ); } /// The opt-in path sends all same-line rules through one additional process. #[tokio::test] async fn offers_experimental_multi_rule_line_fix_when_enabled() { let mut runner = ActionRunner::successful("ENTITY demo IS", "unused"); runner.lint = action_document( json!({"rule_001": action_rule(true), "rule_002": action_rule(true)}), json!([ {"rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "first"}, {"rule": "rule_002", "location": {"start_line": 1, "end_line": 1}, "message": "second"} ]), ); let runner = Arc::new(runner); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| { Backend::new(client, runner.clone(), Vec::new()) .with_experimental_multi_rule_line_fix(true) }); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert_eq!(result.as_array().expect("action list").len(), 3); assert!(result .as_array() .expect("action list") .iter() .any(|action| action["title"] == "Experimental: fix 2 VSG rules on line 1")); assert_eq!( observed_runner .selectors .lock() .expect("selector lock") .last(), Some(&vec![ ("rule_001".to_owned(), 1), ("rule_002".to_owned(), 1) ]) ); } /// Non-fixable rule metadata never produces a correction action. #[tokio::test] async fn omits_non_fixable_rule_actions() { let mut runner = ActionRunner::successful("ENTITY demo IS", "unused"); runner.lint = action_document( json!({"rule_001": action_rule(false)}), json!([{ "rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "cannot be fixed" }]), ); let runner = Arc::new(runner); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert!(result.is_null()); assert!(observed_runner .selectors .lock() .expect("selector lock") .is_empty()); } /// The explicit source action wraps VSG's whole-document formatter. #[tokio::test] async fn provides_whole_document_fix_all() { let runner = Arc::new(ActionRunner::successful("unused", "ENTITY demo IS")); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 5, "text": "entity demo is" }}), ) .await; published_diagnostics(&mut socket).await; let result = request_code_actions(&mut service, json!([]), json!(["source.fixAll.vsg"])).await; assert_eq!(result[0]["kind"], json!("source.fixAll.vsg")); assert_eq!(result[0]["title"], json!("Fix all VSG findings")); assert_eq!( result[0]["edit"]["documentChanges"][0]["textDocument"]["version"], json!(5) ); } /// VSG no-op output does not produce a misleading correction action. #[tokio::test] async fn omits_noop_corrections() { let runner = Arc::new(ActionRunner::successful("entity demo is", "entity demo is")); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; assert!(result.is_null()); } /// Correction failures are shown to the user and yield no unsafe edit. #[tokio::test] async fn reports_scoped_fix_failure() { let runner = Arc::new(ActionRunner { lint: ONE_DIAGNOSTIC.to_owned(), scoped: Err("installed VSG does not support --fix_rule".to_owned()), all: Ok("unused".to_owned()), selectors: Mutex::new(Vec::new()), }); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let result = request_code_actions( &mut service, serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), json!(["quickfix"]), ) .await; let notification = socket.next().await.expect("fix failure notification"); assert!(result.is_null()); assert_eq!(notification.method(), "window/showMessage"); assert!(notification.params().expect("message params")["message"] .as_str() .expect("message text") .contains("--fix_rule")); } /// A document change while VSG is fixing rejects the stale workspace edit. #[tokio::test] async fn rejects_scoped_fix_after_concurrent_change() { let runner = Arc::new(DelayedActionRunner { started: Notify::new(), release: Notify::new(), }); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let parameters = quick_fix_parameters(&published.diagnostics); let uri = tower_lsp::lsp_types::Url::parse("file:///tmp/example.vhd").expect("valid test URI"); let correction = tower_lsp::LanguageServer::code_action(service.inner(), parameters); let replace = async { observed_runner.started.notified().await; service.inner().documents.write().await.insert( uri, Document { text: "changed while fixing".to_owned(), version: 2, diagnostics: Vec::new(), }, ); observed_runner.release.notify_one(); }; let (result, ()) = tokio::join!(correction, replace); assert!(result.is_err()); } /// Dropping a canceled correction does not retain the document lock. #[tokio::test] async fn cancels_pending_scoped_fix_without_locking_documents() { let runner = Arc::new(DelayedActionRunner { started: Notify::new(), release: Notify::new(), }); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "entity demo is" }}), ) .await; let published = published_diagnostics(&mut socket).await; let parameters = quick_fix_parameters(&published.diagnostics); assert!(timeout( Duration::from_millis(20), tower_lsp::LanguageServer::code_action(service.inner(), parameters) ) .await .is_err()); assert!( timeout(Duration::from_millis(20), service.inner().documents.write()) .await .is_ok() ); } /// Full changes replace the snapshot and save reuses the latest text. #[tokio::test] async fn changes_and_saves_latest_snapshot() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "old" }}), ) .await; published_diagnostics(&mut socket).await; notify( &mut service, "textDocument/didChange", json!({ "textDocument": {"uri": "file:///tmp/example.vhd", "version": 2}, "contentChanges": [{"text": "new"}] }), ) .await; assert_eq!(published_diagnostics(&mut socket).await.version, Some(2)); notify( &mut service, "textDocument/didSave", json!({"textDocument": {"uri": "file:///tmp/example.vhd"}}), ) .await; assert_eq!(published_diagnostics(&mut socket).await.version, Some(2)); assert_eq!( observed_runner .inputs .lock() .expect("input lock") .as_slice(), ["old", "new", "new"] ); } /// Closing a document clears diagnostics and removes the stored snapshot. #[tokio::test] async fn close_clears_diagnostics_and_prevents_later_save() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let observed_runner = Arc::clone(&runner); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "source" }}), ) .await; published_diagnostics(&mut socket).await; notify( &mut service, "textDocument/didClose", json!({"textDocument": {"uri": "file:///tmp/example.vhd"}}), ) .await; let cleared = published_diagnostics(&mut socket).await; assert!(cleared.diagnostics.is_empty()); assert_eq!(cleared.version, None); notify( &mut service, "textDocument/didSave", json!({"textDocument": {"uri": "file:///tmp/example.vhd"}}), ) .await; assert_eq!(observed_runner.inputs.lock().expect("input lock").len(), 1); } /// Graceful shutdown clears every open URI before a client starts a new server. #[tokio::test] async fn shutdown_clears_open_document_diagnostics() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; let uri = tower_lsp::lsp_types::Url::parse("file:///tmp/example.vhd").expect("valid test URI"); service.inner().documents.write().await.insert( uri.clone(), Document { text: "source".to_owned(), version: 1, diagnostics: Vec::new(), }, ); let shutdown = tower_lsp::LanguageServer::shutdown(service.inner()); let receive_clear = published_diagnostics(&mut socket); let (shutdown_result, cleared) = tokio::join!(shutdown, receive_clear); shutdown_result.expect("shutdown succeeds"); assert_eq!(cleared.uri, uri); assert!(cleared.diagnostics.is_empty()); assert_eq!(cleared.version, None); assert!(service.inner().documents.read().await.is_empty()); } /// Runner failures become user-visible error notifications. #[tokio::test] async fn reports_runner_failures_to_the_client() { let runner = Arc::new(MockRunner::failing("VSG is unavailable")); let (mut service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didOpen", json!({"textDocument": { "uri": "file:///tmp/example.vhd", "languageId": "vhdl", "version": 1, "text": "source" }}), ) .await; let request = socket.next().await.expect("show-message notification"); assert_eq!(request.method(), "window/showMessage"); assert_eq!( request.params().expect("show-message params")["message"], json!("VSG is unavailable") ); } /// A completed lint cannot publish after the open document version changes. #[tokio::test] async fn suppresses_stale_document_diagnostics() { let runner = Arc::new(DelayedRunner { started: Notify::new(), release: Notify::new(), }); let observed_runner = Arc::clone(&runner); let (service, mut socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); let uri = tower_lsp::lsp_types::Url::parse("file:///tmp/example.vhd").expect("valid test URI"); let original = Document { text: "old".to_owned(), version: 1, diagnostics: Vec::new(), }; service .inner() .documents .write() .await .insert(uri.clone(), original.clone()); let lint = service.inner().lint_and_publish(uri.clone(), original); let replace = async { observed_runner.started.notified().await; service.inner().documents.write().await.insert( uri, Document { text: "new".to_owned(), version: 2, diagnostics: Vec::new(), }, ); observed_runner.release.notify_one(); }; tokio::join!(lint, replace); assert!(timeout(Duration::from_millis(20), socket.next()) .await .is_err()); } /// Empty change lists are ignored without invoking VSG. #[tokio::test] async fn ignores_empty_change_notifications() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); let observed_runner = Arc::clone(&runner); let (mut service, _socket) = LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); initialize(&mut service).await; notify( &mut service, "textDocument/didChange", json!({ "textDocument": {"uri": "file:///tmp/example.vhd", "version": 2}, "contentChanges": [] }), ) .await; assert!(observed_runner .inputs .lock() .expect("input lock") .is_empty()); } }