//! Language Server Protocol diagnostics backed by VHDL Style Guide. //! //! The crate keeps protocol handling, diagnostic parsing, and subprocess //! execution separate so each boundary can be tested independently. #![warn(clippy::missing_docs_in_private_items)] mod diagnostics; mod edits; mod presentation; mod runner; mod server; use clap::Parser; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite}; use tower_lsp::{LspService, Server}; pub use runner::{ProcessVsgRunner, VsgRunner}; pub use server::Backend; /// Package version paired with the source revision used for this build. pub const VERSION: &str = concat!( env!("CARGO_PKG_VERSION"), "+git.", env!("VSG_BRIDGE_GIT_SHA") ); /// Command-line configuration for the language server. #[derive(Clone, Debug, Parser, PartialEq, Eq)] #[command(version = VERSION, about, long_about = None)] pub struct Options { /// VSG configuration files, in the order in which VSG should load them. #[arg(short, long)] pub configuration: Vec, /// Offers an opt-in action that fixes all reported rules on one line. #[arg(long)] pub experimental_multi_rule_line_fix: bool, } impl Options { /// Converts configuration paths into the argument vector expected by VSG. #[must_use] pub fn vsg_arguments(&self) -> Vec { self.configuration .iter() .flat_map(|path| ["-c".to_owned(), path.clone()]) .collect() } } /// Runs the language server over standard input and standard output. pub async fn run_stdio(options: Options) { let runner: Arc = Arc::new(ProcessVsgRunner::default()); run(tokio::io::stdin(), tokio::io::stdout(), options, runner).await; } /// Runs one language-server connection over the supplied byte streams. /// /// This is useful for embedding the bridge and keeps the protocol transport /// independently testable. Normal command-line users should call /// [`run_stdio`] instead. pub async fn run(input: I, output: O, options: Options, runner: Arc) where I: AsyncRead + Unpin, O: AsyncWrite, { let vsg_arguments = options.vsg_arguments(); let (service, socket) = LspService::new(move |client| { Backend::new(client, Arc::clone(&runner), vsg_arguments.clone()) .with_experimental_multi_rule_line_fix(options.experimental_multi_rule_line_fix) }); Server::new(input, output, socket).serve(service).await; } #[cfg(test)] mod tests { //! Unit tests for command-line option translation. use super::{run, Options, VERSION}; use crate::VsgRunner; use anyhow::Result; use clap::{CommandFactory, Parser}; use std::sync::Arc; use tokio::io::{AsyncReadExt, AsyncWriteExt}; /// Runner used when exercising requests that do not invoke VSG. #[derive(Debug)] struct UnusedRunner; #[tower_lsp::async_trait] impl VsgRunner for UnusedRunner { async fn lint(&self, _: &str, _: &[String]) -> Result { panic!("lifecycle-only transport test must not invoke VSG"); } } /// Frames a JSON-RPC payload according to the LSP base protocol. fn frame(payload: &str) -> String { format!("Content-Length: {}\r\n\r\n{payload}", payload.len()) } /// Reads one LSP frame and returns its JSON-RPC payload. async fn read_frame(reader: &mut (impl tokio::io::AsyncRead + Unpin)) -> String { let mut header = Vec::new(); while !header.ends_with(b"\r\n\r\n") { let mut byte = [0]; reader.read_exact(&mut byte).await.expect("read LSP header"); header.push(byte[0]); } let header = String::from_utf8(header).expect("ASCII LSP header"); let content_length = header .lines() .find_map(|line| line.strip_prefix("Content-Length: ")) .expect("content-length header") .parse::() .expect("numeric content length"); let mut payload = vec![0; content_length]; reader .read_exact(&mut payload) .await .expect("read LSP payload"); String::from_utf8(payload).expect("UTF-8 JSON-RPC payload") } /// Configuration paths retain their input order and each receive `-c`. #[test] fn builds_vsg_configuration_arguments() { let options = Options::try_parse_from([ "vsg_bridge_ls", "-c", "first.yaml", "--configuration", "second.yaml", ]) .expect("valid command-line options"); assert_eq!( options.vsg_arguments(), ["-c", "first.yaml", "-c", "second.yaml"] ); } /// No configuration option produces an empty VSG argument vector. #[test] fn accepts_no_configuration_files() { let options = Options::try_parse_from(["vsg_bridge_ls"]) .expect("options without configuration files are valid"); assert!(options.vsg_arguments().is_empty()); assert!(!options.experimental_multi_rule_line_fix); } /// CLI version output identifies both the release and source revision. #[test] fn version_includes_source_revision() { assert_eq!(Options::command().get_version(), Some(VERSION)); assert!(VERSION.starts_with("0.2.0+git.")); assert!(VERSION .strip_prefix("0.2.0+git.") .is_some_and(|revision| revision == "unknown" || (revision.len() == 8 && revision.bytes().all(|byte| byte.is_ascii_hexdigit())))); } /// The multi-rule line action requires an explicit runtime opt-in. #[test] fn parses_experimental_multi_rule_line_flag() { let options = Options::try_parse_from(["vsg_bridge_ls", "--experimental-multi-rule-line-fix"]) .expect("experimental flag is valid"); assert!(options.experimental_multi_rule_line_fix); } /// The byte-stream transport processes a complete LSP lifecycle. #[tokio::test] async fn serves_lsp_over_supplied_streams() { let (mut request_writer, request_reader) = tokio::io::duplex(4096); let (response_writer, mut response_reader) = tokio::io::duplex(4096); let server = tokio::spawn(run( request_reader, response_writer, Options { configuration: Vec::new(), experimental_multi_rule_line_fix: false, }, Arc::new(UnusedRunner), )); request_writer .write_all( frame( r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}"#, ) .as_bytes(), ) .await .expect("write initialize request"); let initialize_response = read_frame(&mut response_reader).await; request_writer .write_all(frame(r#"{"jsonrpc":"2.0","id":2,"method":"shutdown"}"#).as_bytes()) .await .expect("write shutdown request"); let shutdown_response = read_frame(&mut response_reader).await; request_writer .write_all(frame(r#"{"jsonrpc":"2.0","method":"exit"}"#).as_bytes()) .await .expect("write exit notification"); request_writer .shutdown() .await .expect("close request stream"); server.await.expect("server task"); assert!(initialize_response.contains(r#""id":1"#)); assert!(initialize_response.contains(r#""textDocumentSync""#)); assert!(shutdown_response.contains(r#""id":2"#)); assert!(shutdown_response.contains(r#""result":null"#)); } }