//! `vfmt-server` — the vfmt language server, speaking LSP over stdio. //! //! One binary for every editor: VS Code through a thin extension, Vim/Neovim //! through built-in LSP config. No editor-specific logic lives below the //! protocol layer, and no language logic lives in it — every answer comes from //! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See //! `docs/features/vfmt-server/README.md`. mod candidates; mod code_action; mod completion; mod convert; mod diagnostics; mod folding; mod format; mod hover; mod inlay; mod lint; mod locate; mod nav; mod pairs; mod ports; mod rename; mod server; mod settings; mod signature; mod state; mod symbols; mod templates; mod tokens; mod uri; use std::error::Error; use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; use crate::server::Server; use crate::uri::uri_to_path; fn main() -> Result<(), Box> { let (connection, io_threads) = Connection::stdio(); let (id, params) = connection.initialize_start()?; // A client that sends params we cannot read still gets a server; every // field we want is optional anyway. let params: InitializeParams = serde_json::from_value(params).unwrap_or_default(); let roots = workspace_roots(¶ms); let snippets = snippet_support(¶ms); connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?; Server::new(connection, roots, snippets).run()?; io_threads.join()?; Ok(()) } /// What the server tells the client it can do. Nothing is advertised that is /// not implemented: a capability an editor discovers to be a lie is worse than /// one it never had. fn capabilities() -> ServerCapabilities { ServerCapabilities { // The protocol default, and what the conversion in `convert.rs` // implements. Stated rather than left implicit. position_encoding: Some(PositionEncodingKind::UTF16), text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)), document_formatting_provider: Some(OneOf::Left(true)), document_range_formatting_provider: Some(OneOf::Left(true)), definition_provider: Some(OneOf::Left(true)), references_provider: Some(OneOf::Left(true)), // The cursor on a `begin` highlights its own `end`, matched over the // token stream; anywhere else, the symbol under it highlights its own // other occurrences in this file. The handler declines a position // that is neither, which leaves the editor's word highlighting in // charge there. document_highlight_provider: Some(OneOf::Left(true)), // One range per matched scope pair and per multi-line block comment, // off the same matcher the rainbow reads. folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), document_symbol_provider: Some(OneOf::Left(true)), workspace_symbol_provider: Some(OneOf::Left(true)), // `prepareProvider` is what stops an editor from offering a rename the // engine would refuse: the client asks first, and a refusal there costs // the user nothing. rename_provider: Some(OneOf::Right(RenameOptions { prepare_provider: Some(true), work_done_progress_options: WorkDoneProgressOptions::default(), })), // The kinds are listed rather than `Simple(true)` so a client can ask // for one of them alone — which is how fix-on-save is configured. code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions { code_action_kinds: Some(vec![ CodeActionKind::QUICKFIX, CodeActionKind::new(code_action::FIX_ALL), CodeActionKind::new(ports::REFACTOR_PORTS), ]), work_done_progress_options: WorkDoneProgressOptions::default(), // Every action is returned complete; there is nothing to resolve. resolve_provider: None, })), // The port refactorings. `vfmt.addPort` needs a declaration typed by // the user, which no code action can carry, and a Vim user has no // lightbulb at all — so all three are commands as well. execute_command_provider: Some(ExecuteCommandOptions { commands: ports::commands(), work_done_progress_options: WorkDoneProgressOptions::default(), }), // Module hinting. No trigger characters: an identifier being typed is // what asks for these, and the handler declines every position that is // not a module item, so an unprompted request costs a token scan. completion_provider: Some(CompletionOptions { // Every item is returned complete — skeleton, documentation and // all — so there is nothing for `completionItem/resolve` to do. resolve_provider: None, trigger_characters: None, all_commit_characters: None, work_done_progress_options: WorkDoneProgressOptions::default(), completion_item: None, }), // `(` opens a connection or parameter list and `,` moves to the next // entry; between them they cover every place the ports are worth // showing. signature_help_provider: Some(SignatureHelpOptions { trigger_characters: Some( signature::TRIGGERS.iter().map(|t| (*t).to_string()).collect(), ), retrigger_characters: None, work_done_progress_options: WorkDoneProgressOptions::default(), }), // Port and parameter names on ordered connection lists. Every hint is // returned complete — a label, a position and nothing to fetch later — // so there is no `inlayHint/resolve`. inlay_hint_provider: Some(OneOf::Right(InlayHintServerCapabilities::Options( InlayHintOptions { work_done_progress_options: WorkDoneProgressOptions::default(), resolve_provider: None, }, ))), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), legend: SemanticTokensLegend { token_types: tokens::token_types(), token_modifiers: tokens::token_modifiers(), }, range: None, full: Some(SemanticTokensFullOptions::Bool(true)), }, )), ..Default::default() } } fn initialize_result() -> lsp_types::InitializeResult { lsp_types::InitializeResult { capabilities: capabilities(), server_info: Some(lsp_types::ServerInfo { name: "vfmt-server".to_string(), version: Some(env!("CARGO_PKG_VERSION").to_string()), }), } } /// Whether the client can expand `${1:x}` tabstops in a completion item. /// /// A client that did not say so gets the skeleton as plain text: a literal /// `${1:clk}` written into a buffer is worse than no tabstops at all, and the /// protocol gives no way to find out after the fact. fn snippet_support(params: &InitializeParams) -> bool { params .capabilities .text_document .as_ref() .and_then(|text_document| text_document.completion.as_ref()) .and_then(|completion| completion.completion_item.as_ref()) .and_then(|item| item.snippet_support) .unwrap_or(false) } /// The directories to index: the client's workspace folders, or the /// deprecated single root when that is all it sent. fn workspace_roots(params: &InitializeParams) -> Vec { if let Some(folders) = ¶ms.workspace_folders { let roots: Vec = folders.iter().filter_map(|f| uri_to_path(&f.uri)).collect(); if !roots.is_empty() { return roots; } } #[allow(deprecated)] // `root_uri` is how older clients name the workspace. params.root_uri.as_ref().and_then(uri_to_path).into_iter().collect() } #[cfg(test)] mod tests { use super::*; #[test] fn every_advertised_capability_is_implemented() { let caps = capabilities(); assert!(caps.document_formatting_provider.is_some()); assert!(caps.document_range_formatting_provider.is_some()); assert!(caps.definition_provider.is_some()); assert!(caps.references_provider.is_some()); assert!(caps.document_highlight_provider.is_some()); assert!(caps.folding_range_provider.is_some()); assert!(caps.hover_provider.is_some()); assert!(caps.document_symbol_provider.is_some()); assert!(caps.workspace_symbol_provider.is_some()); assert!(caps.semantic_tokens_provider.is_some()); assert!(caps.code_action_provider.is_some()); assert!(caps.rename_provider.is_some()); assert!(caps.execute_command_provider.is_some()); assert!(caps.completion_provider.is_some()); assert!(caps.signature_help_provider.is_some()); assert!(caps.inlay_hint_provider.is_some()); } #[test] fn inlay_hints_resolve_nothing_because_every_hint_is_complete() { let Some(OneOf::Right(InlayHintServerCapabilities::Options(options))) = capabilities().inlay_hint_provider else { panic!("inlay hints must carry options, not a bare `true`"); }; assert_eq!(options.resolve_provider, None); } #[test] fn signature_help_advertises_the_characters_the_handler_answers_on() { let options = capabilities().signature_help_provider.expect("signature help"); assert_eq!(options.trigger_characters, Some(vec!["(".to_string(), ",".to_string()])); } #[test] fn completion_resolves_nothing_because_every_item_is_complete() { let options = capabilities().completion_provider.expect("completion"); assert_eq!(options.resolve_provider, None); assert_eq!(options.trigger_characters, None); } #[test] fn snippet_support_is_read_from_the_clients_own_capabilities() { use lsp_types::{ ClientCapabilities, CompletionClientCapabilities, CompletionItemCapability, TextDocumentClientCapabilities, }; assert!(!snippet_support(&InitializeParams::default()), "silence means no"); let saying = |snippet_support: Option| InitializeParams { capabilities: ClientCapabilities { text_document: Some(TextDocumentClientCapabilities { completion: Some(CompletionClientCapabilities { completion_item: Some(CompletionItemCapability { snippet_support, ..Default::default() }), ..Default::default() }), ..Default::default() }), ..Default::default() }, ..Default::default() }; assert!(super::snippet_support(&saying(Some(true)))); assert!(!super::snippet_support(&saying(Some(false)))); assert!(!super::snippet_support(&saying(None))); } #[test] fn rename_advertises_prepare_so_the_editor_asks_before_offering() { let Some(OneOf::Right(options)) = capabilities().rename_provider else { panic!("rename must carry options, not a bare `true`"); }; assert_eq!(options.prepare_provider, Some(true)); } #[test] fn the_legend_and_the_encoder_agree_on_length() { // The wire format carries indices into these arrays, so a mismatch // between the legend and the encoder is a silent mis-colouring. assert_eq!(tokens::token_types().len(), 14); assert_eq!(tokens::token_modifiers().len(), 1); } #[test] fn the_code_action_kinds_are_named_in_the_capability() { // A client filtering by kind (fix-on-save does) sees nothing unless the // kinds it may ask for are advertised. let Some(CodeActionProviderCapability::Options(options)) = capabilities().code_action_provider else { panic!("the kinds must be listed, not just `true`"); }; let kinds = options.code_action_kinds.expect("kinds"); assert!(kinds.contains(&CodeActionKind::QUICKFIX)); assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL))); assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS))); } #[test] fn every_advertised_command_is_one_the_server_runs() { let options = capabilities().execute_command_provider.expect("commands"); assert_eq!(options.commands, ports::commands()); assert!(options.commands.iter().all(|c| c.starts_with("vfmt.")), "{:?}", options.commands); } #[test] fn utf16_is_advertised_because_that_is_what_convert_implements() { assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16)); } }