diff --git a/Cargo.lock b/Cargo.lock index d34110a..be7ae86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,11 +220,16 @@ name = "vfmt" version = "0.1.0" dependencies = [ "rayon", + "vfmt_core", "vlog_formatter", "vlog_linter", "vlog_parser", ] +[[package]] +name = "vfmt_core" +version = "0.1.0" + [[package]] name = "vfmt_server" version = "0.1.0" @@ -233,6 +238,7 @@ dependencies = [ "lsp-types", "serde", "serde_json", + "vfmt_core", "vlog_formatter", "vlog_parser", "vlog_semantic", diff --git a/Cargo.toml b/Cargo.toml index 8d7d7a4..6f17dd2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "crates/vlog_semantic", "crates/vlog_formatter", "crates/vlog_linter", + "crates/vfmt_core", "crates/vfmt", "crates/vfmt_server", ] diff --git a/README.md b/README.md index 2fe8b90..def0d77 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,65 @@ corpus baseline this ordering comes from: Like ruff, `vfmt` refuses to output anything for a file it cannot fully parse, so it can never corrupt code. +## Editor setup + +`vfmt-server` is a language server: one binary, LSP over stdio, the same +answers in every editor. It ships formatting, diagnostics as you type, semantic +highlighting, hover (including `` `define`` expansion), go-to-definition, +references and document/workspace symbols — the full list, and what is +deliberately *not* advertised yet, is in +`docs/features/vfmt-server/README.md`. + +**The binary comes from the same build as the CLI**, and nothing downloads it +for you: + +```bash +cargo build --release # target/release/vfmt-server (and target/release/vfmt) +cp target/release/vfmt-server ~/.local/bin/ # anywhere on PATH +``` + +Every editor below defaults to finding `vfmt-server` on `PATH`; each also +accepts an absolute path if you would rather leave the binary in `target/`. + +**VS Code** — a thin extension in `editors/vscode/` whose entire job is +registering the file types and starting the server: + +```bash +cd editors/vscode +npm install +npx @vscode/vsce package --skip-license +code --install-extension vfmt-0.1.0.vsix +``` + +One setting, `vfmt.serverPath`. Full steps, F5 development flow and +troubleshooting: `editors/vscode/README.md`. + +**Neovim / Vim** — no plugin, just configuration. Neovim 0.11+: + +```lua +vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog' } }) +vim.lsp.config('vfmt', { + cmd = { 'vfmt-server' }, + filetypes = { 'verilog', 'systemverilog' }, + root_markers = { 'vfmt.toml', '.vfmt.toml', '.git' }, +}) +vim.lsp.enable('vfmt') +``` + +`nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents: +`editors/nvim/README.md`. + +**Checking the server without an editor.** `node editors/vscode/smoke.js +` spawns it exactly as the extension does and drives a whole +`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if +the handshake and the advertised capabilities are intact — which tells you +whether a failure is the server or your editor config. + +One caveat, stated up front: the server does **not** read `vfmt.toml` yet, so +formatting through an editor uses the defaults (100 columns, 2-space indent) +with the editor's tab size overriding the indent. `vfmt` on the command line +does read it. + ## Contributing / workflow This is a solo project — committing directly to `master` is allowed and diff --git a/TODO.md b/TODO.md index 03f73d5..2d40c7f 100644 --- a/TODO.md +++ b/TODO.md @@ -100,7 +100,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. Keys: `line-length`, `indent`, `exclude` globs. CLI flags override file config. Keep Verible's philosophy of *few* knobs — don't grow a clang-format-sized option surface. - → `crates/vfmt/src/config.rs`; discovery rule, TOML subset and + → `crates/vfmt_core/src/config.rs` (lifted from crates/vfmt by vfmt-core-lift); discovery rule, TOML subset and precedence in `docs/features/config-discovery/README.md`. - [x] **[R] Parallel file processing.** ruff's speed story is embarrassing parallelism over files. `main.rs` formats serially; use `rayon` @@ -117,7 +117,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. directories (`collect_files` in `main.rs` currently walks everything, including e.g. generated netlists). → `--exclude` shipped with cli-polish; `.gitignore` is hand-rolled in - `crates/vfmt/src/walk.rs` (anchoring, directory-only, `!` negation, + `crates/vfmt_core/src/walk.rs` (anchoring, directory-only, `!` negation, nested files override) with a `--no-gitignore` escape hatch. The supported subset and everything git does that this does not are listed in `docs/features/parallel-files/README.md`. @@ -347,9 +347,20 @@ later: cross-file references, completion/rename/signature help. Byte↔UTF-16 position conversion, the state/staleness model and the dependency audit are in `docs/features/vfmt-server/README.md`. -- [ ] **Editor packaging.** A minimal VS Code extension (launch the +- [x] **Editor packaging.** A minimal VS Code extension (launch the server, register file types) and a documented Vim/Neovim `lspconfig` snippet. No editor-specific features beyond launching. + → `editors/vscode/` (41-line plain-JS `extension.js` on the official + `vscode-languageclient`, pinned `9.0.1`; one setting, `vfmt.serverPath`; + `.v`/`.vh`→`verilog`, `.sv`/`.svh`→`systemverilog`; no grammar — semantic + tokens come from the server; no commands, no status bar) and + `editors/nvim/README.md` (`vim.lsp.config` for Neovim 0.11+, plus + `nvim-lspconfig`, Vim 9 `vim-lsp` and coc.nvim). `editors/vscode/smoke.js` + is the pre-publish check: zero-dependency node, spawns the server with the + extension's exact contract and drives `initialize`/`didOpen`/`shutdown`/ + `exit` over hand-rolled framing. Manual install steps only — CI packaging + and Marketplace publishing are out of scope, and `publisher` is a + placeholder. `docs/features/editor-packaging/README.md`. - [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa; don't take that dependency until hover/definition across files exists. Per-file recompute is fine at Verilog file sizes. diff --git a/crates/vfmt/Cargo.toml b/crates/vfmt/Cargo.toml index bad39d2..880fba8 100644 --- a/crates/vfmt/Cargo.toml +++ b/crates/vfmt/Cargo.toml @@ -10,6 +10,7 @@ name = "vfmt" path = "src/main.rs" [dependencies] +vfmt_core = { path = "../vfmt_core" } vlog_parser = { path = "../vlog_parser" } vlog_formatter = { path = "../vlog_formatter" } vlog_linter = { path = "../vlog_linter" } diff --git a/crates/vfmt/src/args.rs b/crates/vfmt/src/args.rs index 7f159a8..d9568dd 100644 --- a/crates/vfmt/src/args.rs +++ b/crates/vfmt/src/args.rs @@ -1,6 +1,6 @@ //! Hand-rolled command line parsing for the `vfmt` binary. -use crate::config::FileConfig; +use vfmt_core::config::FileConfig; use vlog_formatter::Config; /// Which tool this invocation runs. diff --git a/crates/vfmt/src/main.rs b/crates/vfmt/src/main.rs index 2c0d7be..d244e8e 100644 --- a/crates/vfmt/src/main.rs +++ b/crates/vfmt/src/main.rs @@ -13,10 +13,8 @@ //! untouched). mod args; -mod config; mod diff; mod lint; -mod walk; use std::cell::Cell; use std::io::Read; @@ -27,9 +25,9 @@ use std::process::ExitCode; use rayon::prelude::*; use args::{Command, Options}; -use config::Discovery; +use vfmt_core::config::Discovery; +use vfmt_core::walk::{collect_files, EXTENSIONS}; use vlog_formatter::{format_source, Config}; -use walk::{collect_files, EXTENSIONS}; /// Worker stack size. `docs/features/recursion-limit/README.md` measured /// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on diff --git a/crates/vfmt_core/Cargo.toml b/crates/vfmt_core/Cargo.toml new file mode 100644 index 0000000..0b042fc --- /dev/null +++ b/crates/vfmt_core/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "vfmt_core" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Config discovery and file walking, shared by the vfmt CLI and the vfmt language server" + +[lib] +name = "vfmt_core" +path = "src/lib.rs" + +[dependencies] diff --git a/crates/vfmt/src/config.rs b/crates/vfmt_core/src/config.rs similarity index 100% rename from crates/vfmt/src/config.rs rename to crates/vfmt_core/src/config.rs diff --git a/crates/vfmt_core/src/lib.rs b/crates/vfmt_core/src/lib.rs new file mode 100644 index 0000000..8d3e6b5 --- /dev/null +++ b/crates/vfmt_core/src/lib.rs @@ -0,0 +1,12 @@ +//! The parts of vfmt that decide *which* files are processed and *with what +//! settings*, shared by the `vfmt` CLI and the `vfmt-server` language server. +//! +//! Both modules were lifted out of `crates/vfmt` unchanged so the two front +//! ends cannot silently disagree: an editor's format-on-save must find the +//! same `vfmt.toml` and skip the same files as CI's `vfmt --check`. See +//! `docs/features/vfmt-core-lift/README.md`, and +//! `docs/features/{config-discovery,parallel-files}/README.md` for the rules +//! themselves. + +pub mod config; +pub mod walk; diff --git a/crates/vfmt/src/walk.rs b/crates/vfmt_core/src/walk.rs similarity index 100% rename from crates/vfmt/src/walk.rs rename to crates/vfmt_core/src/walk.rs diff --git a/crates/vfmt_server/Cargo.toml b/crates/vfmt_server/Cargo.toml index d40da26..cc033cb 100644 --- a/crates/vfmt_server/Cargo.toml +++ b/crates/vfmt_server/Cargo.toml @@ -9,6 +9,7 @@ name = "vfmt-server" path = "src/main.rs" [dependencies] +vfmt_core = { path = "../vfmt_core" } vlog_parser = { path = "../vlog_parser" } vlog_semantic = { path = "../vlog_semantic" } vlog_formatter = { path = "../vlog_formatter" } diff --git a/crates/vfmt_server/src/format.rs b/crates/vfmt_server/src/format.rs index 196cf0c..34ad5bd 100644 --- a/crates/vfmt_server/src/format.rs +++ b/crates/vfmt_server/src/format.rs @@ -4,43 +4,94 @@ //! this handler keeps it: either one whole-document edit built from verified //! output, or no edit at all and an error for the user to read. +use std::path::Path; + use lsp_types::{FormattingOptions, TextEdit}; +use vfmt_core::config::{Discovery, FileConfig}; use vlog_formatter::{format_source, Config}; use crate::state::Document; -/// Indent widths a client may ask for. Wider than `vfmt.toml`'s own 1..8 -/// range would be, so the two agree. +/// Indent widths a client may ask for. The same 1..8 range `vfmt.toml`'s own +/// `indent` key allows, so the two agree. const INDENT_RANGE: std::ops::RangeInclusive = 1..=8; +/// What to format a buffer with, and the config problem to tell the user +/// about. The two are separate because a broken `vfmt.toml` must not stop the +/// buffer from being formatted. +pub struct Settings { + /// The settings to format with — the fallback defaults when `problem` is + /// set. + pub config: Config, + /// The `vfmt.toml` error governing this buffer, if there is one. + pub problem: Option, +} + +/// Resolve the settings governing a buffer. +/// +/// Precedence is **`vfmt.toml` > the client's tab size > the built-in +/// default**, which is *not* the CLI's flag-beats-config order, and +/// deliberately so: a CLI flag is typed on purpose for one run, while +/// `FormattingOptions::tab_size` is sent on every request whether or not the +/// user ever chose it (it is the editor's own default, or its guess from the +/// file). Letting an editor default silently beat a checked-in `vfmt.toml` +/// would make format-on-save disagree with CI's `vfmt --check` — the exact +/// divergence lifting the config into `vfmt_core` exists to remove. Where the +/// config is silent the tab size still wins over the built-in default, so a +/// project with no `vfmt.toml` behaves as it did before. +pub fn settings_for(doc: &Document, options: &FormattingOptions) -> Settings { + let (file, problem) = discover(doc.path.as_deref()); + Settings { config: config_from(&file, options), problem } +} + /// Format a buffer. /// /// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an /// edit that changes nothing still moves the cursor in some editors. `Err` /// carries the formatter's own message; the caller surfaces it, and must not /// invent an edit from it. -pub fn formatting(doc: &Document, options: &FormattingOptions) -> Result, String> { - let config = config_from(options); - let formatted = format_source(&doc.text, &config).map_err(|e| e.to_string())?; +pub fn formatting(doc: &Document, config: &Config) -> Result, String> { + let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?; if formatted == doc.text { return Ok(None); } Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })) } -/// Map the client's tab options onto the formatter's config. +/// The config file governing `path`, by the CLI's own discovery rule, or the +/// error that stopped it from being read. A buffer with no path (`untitled:`) +/// has no directory to search from, so it gets no config. +fn discover(path: Option<&Path>) -> (FileConfig, Option) { + let Some(path) = path else { return (FileConfig::default(), None) }; + // A fresh `Discovery` per request, so a `vfmt.toml` edited while the + // server runs takes effect at the next format. One file read on an + // explicit, user-initiated request is cheaper than any cache invalidation + // scheme that could be wrong. + match Discovery::new(true).for_file(path) { + Ok(file) => (file, None), + Err(problem) => (FileConfig::default(), Some(problem)), + } +} + +/// Fold the config file and the client's tab options into formatter settings, +/// in the precedence `settings_for` documents. /// -/// Only `indent_width` is taken, and only when the request is sane: a client +/// The client's `tab_size` is taken only when the request is sane: a client /// asking for hard tabs, or for a 40-space indent, is asking for something /// vfmt does not do, and silently honoring half of it is worse than ignoring -/// it. `max_width` stays at the default — line length comes from `vfmt.toml`, -/// whose discovery lives in the CLI crate (see the feature README's -/// Handshakes). -fn config_from(options: &FormattingOptions) -> Config { +/// it. `max_width` is never taken from the client — the protocol has no +/// line-length option, so it comes from `vfmt.toml` or not at all. +fn config_from(file: &FileConfig, options: &FormattingOptions) -> Config { let mut config = Config::default(); if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) { config.indent_width = options.tab_size as usize; } + if let Some(indent) = file.indent { + config.indent_width = indent; + } + if let Some(line_length) = file.line_length { + config.max_width = line_length; + } config } @@ -49,7 +100,9 @@ mod tests { use super::*; use crate::state::Workspace; use lsp_types::Uri; + use std::path::PathBuf; use std::str::FromStr; + use std::sync::atomic::{AtomicUsize, Ordering}; fn document(text: &str) -> (Workspace, Uri) { let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); @@ -62,12 +115,62 @@ mod tests { FormattingOptions { tab_size, insert_spaces, ..Default::default() } } + /// The settings a buffer with no config file on disk resolves to. + fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings { + settings_for(ws.document(uri).expect("open"), options) + } + + fn edit_of( + ws: &Workspace, + uri: &Uri, + options: &FormattingOptions, + ) -> Result, String> { + let doc = ws.document(uri).expect("open"); + formatting(doc, &settings_for(doc, options).config) + } + + /// A scratch directory holding a `vfmt.toml` and one source file, so + /// discovery runs against a real tree. Removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(config: &str) -> Tree { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("vfmt_server_fmt_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + // A `.git` marker stops discovery here, so a `vfmt.toml` in a real + // ancestor of the temp dir can never leak into these tests. + std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git"); + std::fs::write(path.join("vfmt.toml"), config).expect("write config"); + Tree { path } + } + + /// An open buffer for `m.sv` inside this tree. + fn document(&self, text: &str) -> (Workspace, Uri) { + let file = self.path.join("m.sv"); + std::fs::write(&file, text).expect("write source"); + let uri = crate::uri::path_to_uri(&file).expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } + } + #[test] fn an_unformatted_buffer_gets_one_whole_document_edit() { let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let edit = formatting(ws.document(&uri).expect("open"), &options(2, true)) - .expect("formats") - .expect("changed"); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); assert_eq!(edit.range.start.line, 0); assert_eq!(edit.range.start.character, 0); assert_eq!(edit.range.end.line, 3, "one past the last line"); @@ -77,47 +180,94 @@ mod tests { #[test] fn an_already_formatted_buffer_gets_no_edit() { let (ws, uri) = document("module m;\n wire a;\nendmodule\n"); - let edit = - formatting(ws.document(&uri).expect("open"), &options(2, true)).expect("formats"); - assert_eq!(edit, None); + assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None); } #[test] fn a_sane_tab_size_becomes_the_indent_width() { let (ws, uri) = document("module m;\nwire a;\nendmodule\n"); - let edit = formatting(ws.document(&uri).expect("open"), &options(4, true)) - .expect("formats") - .expect("changed"); + let edit = edit_of(&ws, &uri, &options(4, true)).expect("formats").expect("changed"); assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); } #[test] fn hard_tabs_and_absurd_widths_fall_back_to_the_default() { - assert_eq!(config_from(&options(4, false)).indent_width, 2, "hard tabs ignored"); - assert_eq!(config_from(&options(40, true)).indent_width, 2, "out of range ignored"); - assert_eq!(config_from(&options(0, true)).indent_width, 2, "zero ignored"); - assert_eq!(config_from(&options(8, true)).indent_width, 8, "the top of the range"); + let none = FileConfig::default(); + assert_eq!(config_from(&none, &options(4, false)).indent_width, 2, "hard tabs ignored"); + assert_eq!(config_from(&none, &options(40, true)).indent_width, 2, "out of range ignored"); + assert_eq!(config_from(&none, &options(0, true)).indent_width, 2, "zero ignored"); + assert_eq!(config_from(&none, &options(8, true)).indent_width, 8, "the top of the range"); } #[test] fn a_line_length_is_never_taken_from_the_client() { - assert_eq!(config_from(&options(4, true)).max_width, Config::default().max_width); + let config = config_from(&FileConfig::default(), &options(4, true)); + assert_eq!(config.max_width, Config::default().max_width); + } + + #[test] + fn a_config_file_beats_the_editors_tab_size() { + // The precedence decision, pinned: `tab_size` is the editor's default + // unless the user changed it, and a checked-in `vfmt.toml` is always + // deliberate. See `settings_for`. + let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None }; + let config = config_from(&file, &options(2, true)); + assert_eq!(config.indent_width, 4, "vfmt.toml wins over tab_size"); + assert_eq!(config.max_width, 120, "line-length has no client analog at all"); + // Where the config is silent the tab size still beats the default. + let only_width = FileConfig { line_length: Some(120), indent: None, exclude: None }; + assert_eq!(config_from(&only_width, &options(3, true)).indent_width, 3); + } + + #[test] + fn a_vfmt_toml_governs_the_buffer_it_sits_above() { + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + // The client asks for 2, the config says 4: the config wins. + let settings = settings(&ws, &uri, &options(2, true)); + assert_eq!(settings.config.indent_width, 4); + assert_eq!(settings.problem, None); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn a_broken_vfmt_toml_reports_a_problem_and_formats_with_defaults() { + let tree = Tree::new("indent = 4\nbogus = 1\n"); + let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n"); + let settings = settings(&ws, &uri, &options(2, true)); + let problem = settings.problem.expect("a broken config must be reported"); + assert!(problem.contains("unknown key `bogus`"), "{problem}"); + assert!(problem.contains("vfmt.toml:2"), "the message names file and line: {problem}"); + // Nothing from the broken file is used, not even the key that parsed. + assert_eq!(settings.config.indent_width, Config::default().indent_width); + // And the buffer is still formatted: an editor must not hard-fail on a + // config typo the way the CLI's exit 2 does. + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); + assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn an_untitled_buffer_has_no_directory_to_discover_from() { + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string()); + let settings = settings(&ws, &uri, &options(4, true)); + assert_eq!(settings.problem, None); + assert_eq!(settings.config.indent_width, 4, "the tab size is all there is"); } #[test] fn an_unparsable_buffer_produces_no_edit() { let (ws, uri) = document("module m;\n wire ;\nendmodule\n"); - let result = formatting(ws.document(&uri).expect("open"), &options(2, true)); - let message = result.expect_err("must refuse"); + let message = edit_of(&ws, &uri, &options(2, true)).expect_err("must refuse"); assert!(!message.is_empty(), "the user needs something to read"); } #[test] fn multi_byte_content_survives_formatting() { let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n"); - let edit = formatting(ws.document(&uri).expect("open"), &options(2, true)) - .expect("formats") - .expect("changed"); + let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed"); assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped"); // The replaced range must cover the whole document in UTF-16 terms. assert_eq!(edit.range.end.line, 4); diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 3a2ae4c..6878d5b 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -5,6 +5,7 @@ //! — 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}; @@ -34,13 +35,17 @@ use crate::{diagnostics, format, hover, nav, symbols, tokens}; 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, } impl Server { pub fn new(connection: Connection, roots: Vec) -> Server { let mut workspace = Workspace::default(); workspace.open_roots(roots); - Server { connection, workspace } + Server { connection, workspace, config_warnings: HashSet::new() } } /// Receive until the client shuts us down or the channel closes. @@ -135,7 +140,22 @@ impl Server { fn formatting(&mut self, params: DocumentFormattingParams) -> Result { let uri = params.text_document.uri; let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; - match format::formatting(doc, ¶ms.options) { + 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. + if let Some(problem) = settings.problem { + if self.config_warnings.insert(uri.clone()) { + self.show_message( + MessageType::WARNING, + format!("vfmt: {problem} — formatting with default settings"), + ); + } + } + match result { // A whole-document edit, or none when nothing changed. Ok(Some(edit)) => to_value(vec![edit]), Ok(None) => to_value(Vec::::new()), @@ -161,7 +181,7 @@ impl Server { DidOpenTextDocument::METHOD => { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; - self.workspace.set_document(uri.clone(), p.text_document.text); + self.set_document(uri.clone(), p.text_document.text); self.publish(&uri); } } @@ -170,7 +190,7 @@ impl Server { // 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.workspace.set_document(uri.clone(), change.text); + self.set_document(uri.clone(), change.text); self.publish(&uri); } } @@ -178,7 +198,7 @@ impl Server { DidSaveTextDocument::METHOD => { if let Ok(p) = extract::(notification) { if let Some(text) = p.text { - self.workspace.set_document(p.text_document.uri.clone(), 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. @@ -191,6 +211,7 @@ impl Server { DidCloseTextDocument::METHOD => { if let Ok(p) = extract::(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()); @@ -204,6 +225,13 @@ impl Server { // 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); + } + fn publish(&self, uri: &Uri) { let Some(doc) = self.workspace.document(uri) else { return }; self.send_diagnostics(uri.clone(), diagnostics::diagnostics(doc)); diff --git a/crates/vfmt_server/src/state.rs b/crates/vfmt_server/src/state.rs index 86eddea..3048aa3 100644 --- a/crates/vfmt_server/src/state.rs +++ b/crates/vfmt_server/src/state.rs @@ -13,16 +13,12 @@ use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex}; +use vfmt_core::config::Discovery; +use vfmt_core::walk::collect_files; + use crate::convert::Positions; use crate::uri::uri_to_path; -/// How deep the workspace walk descends. A plain recursive walk has no cycle -/// detection; a cap is the cheap way to survive a symlink loop. -const MAX_WALK_DEPTH: u32 = 64; - -/// The file extensions a Verilog workspace is made of. -const SOURCE_EXTENSIONS: [&str; 4] = ["v", "sv", "vh", "svh"]; - /// How many `workspace/symbol` hits are returned. Each one costs a file read /// to turn its byte span into a line, so an unbounded answer to the empty /// query would read the whole workspace. @@ -140,12 +136,26 @@ impl Workspace { } } - /// Every source file under the roots, walked plainly — no `.gitignore`, - /// no excludes (see the feature README's Handshakes). + /// Every source file under the roots, found by the CLI's own walk: the + /// same extensions, the same `.gitignore` handling, and the `exclude` + /// patterns of the config governing each root. What `vfmt` skips, the + /// index skips. fn source_files(&self) -> Vec { + let mut discovery = Discovery::new(true); let mut out = Vec::new(); for root in &self.roots { - walk(root, 0, &mut out); + // The walk names its inputs as strings; every root came from a + // `file:` URI, which cannot carry a non-UTF-8 path. + let Some(input) = root.to_str() else { continue }; + // A broken `vfmt.toml` must not stop the server from indexing: an + // index that excludes nothing is a far better failure than a + // server that comes up empty. The error is reported when the user + // formats a file in this tree (`format::settings_for`). + let exclude = discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default(); + // `.gitignore` is always honoured: it is the CLI's default, and an + // editor has no `--no-gitignore` to type. An unreadable root is + // simply not indexed, exactly as before this walk was shared. + let _ = collect_files(input, &exclude, true, &mut out); } out.sort(); out.dedup(); @@ -153,25 +163,6 @@ impl Workspace { } } -fn walk(dir: &Path, depth: u32, out: &mut Vec) { - if depth > MAX_WALK_DEPTH { - return; - } - let Ok(entries) = fs::read_dir(dir) else { return }; - for entry in entries.flatten() { - let path = entry.path(); - match entry.file_type() { - Ok(t) if t.is_dir() => walk(&path, depth + 1, out), - Ok(t) if t.is_file() && is_source(&path) => out.push(path), - _ => {} - } - } -} - -fn is_source(path: &Path) -> bool { - path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e)) -} - #[cfg(test)] mod tests { use super::*; @@ -240,13 +231,96 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + /// 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!("vfmt_server_scan_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("parent"); + } + fs::write(&path, text).expect("write"); + } + + /// 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) { + self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n")); + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + #[test] - fn the_walk_finds_only_source_extensions() { - assert!(is_source(Path::new("/a/b.sv"))); - assert!(is_source(Path::new("/a/b.v"))); - assert!(is_source(Path::new("/a/b.svh"))); - assert!(is_source(Path::new("/a/b.vh"))); - assert!(!is_source(Path::new("/a/b.txt"))); - assert!(!is_source(Path::new("/a/b"))); + fn the_scan_skips_what_a_gitignore_skips() { + let tree = Tree::new("gitignore"); + tree.write(".gitignore", "generated/\n*_gen.sv\n"); + tree.package("kept.sv", "kept"); + tree.package("generated/netlist.sv", "generated_pkg"); + tree.package("rtl/top_gen.sv", "gen_pkg"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed"); + assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory"); + assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth"); + } + + #[test] + fn the_scan_honours_the_root_configs_excludes() { + let tree = Tree::new("excludes"); + tree.write("vfmt.toml", "exclude = [\"vendor\"]\n"); + tree.package("kept.sv", "kept"); + tree.package("vendor/ip.sv", "vendor_pkg"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(ws.index().member("kept", "K").len(), 1); + assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "vfmt.toml excludes apply"); + } + + #[test] + fn a_broken_root_config_does_not_stop_the_scan() { + // Exit 2 is the CLI's answer to a broken config; a server that indexed + // nothing because of a typo would look simply broken instead. + let tree = Tree::new("brokencfg"); + tree.write("vfmt.toml", "bogus = 1\n"); + tree.package("kept.sv", "kept"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(ws.index().member("kept", "K").len(), 1); + } + + #[test] + fn the_scan_takes_only_source_extensions() { + let tree = Tree::new("extensions"); + tree.package("a.sv", "a"); + tree.package("b.v", "b"); + tree.package("c.svh", "c"); + tree.package("d.vh", "d"); + tree.package("e.txt", "e"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + for name in ["a", "b", "c", "d"] { + assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file"); + } + assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not"); } } diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index c53dae5..2bf2d08 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -12,7 +12,7 @@ //! server's own transport could not catch a framing bug. use std::io::{BufRead, BufReader, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// Frame one JSON payload the way LSP wants it. @@ -51,20 +51,130 @@ fn unframe(mut input: impl BufRead) -> Vec { } } -fn temp_dir() -> PathBuf { - let dir = std::env::temp_dir().join(format!("vfmt_server_e2e_{}", std::process::id())); +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vfmt_server_e2e_{}_{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).expect("temp dir"); dir } +/// Write a whole session to the server and read everything it says back. +/// +/// Writing before reading is what keeps this from deadlocking: the server +/// processes the messages in order and exits on `exit`, so stdout closes and +/// the read terminates on its own. +fn talk(session: &str) -> Vec { + let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("the server binary starts"); + child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session"); + let stdout = child.stdout.take().expect("stdout"); + let messages = unframe(BufReader::new(stdout)); + let status = child.wait().expect("the server exits"); + assert!(status.success(), "clean exit, got {status:?}"); + messages +} + +/// An `initialize` + `didOpen` + one `textDocument/formatting` + shutdown +/// session against a scratch workspace holding `config` as its `vfmt.toml`. +/// The client asks for a 2-space indent, which is what an editor default +/// looks like. +fn format_session(dir: &Path, file: &Path, ids: &[u32]) -> Vec { + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + let source = std::fs::read_to_string(file).expect("read source"); + let mut session = vec![ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&source).expect("json") + )), + ]; + for id in ids { + session.push(frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + ))); + } + session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#)); + session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#)); + talk(&session.concat()) +} + +/// The one edit a formatting response carries. +fn new_text(messages: &[serde_json::Value], id: u32) -> String { + let response = messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no formatting response in {messages:#?}")); + let edits = response["result"].as_array().expect("an array of edits"); + assert_eq!(edits.len(), 1, "one whole-document edit, got {edits:#?}"); + edits[0]["newText"].as_str().expect("newText").to_string() +} + +const UNFORMATTED: &str = "module m;\nwire a;\nendmodule\n"; + +#[test] +fn a_vfmt_toml_governs_formatting_over_the_editors_tab_size() { + let dir = temp_dir("config"); + std::fs::write(dir.join("vfmt.toml"), "indent = 4\n").expect("write config"); + let file = dir.join("m.sv"); + std::fs::write(&file, UNFORMATTED).expect("write"); + + let messages = format_session(&dir, &file, &[2]); + assert_eq!( + new_text(&messages, 2), + "module m;\n wire a;\nendmodule\n", + "the config's indent=4 beats the client's tabSize=2" + ); + assert!( + !messages.iter().any(|m| m["method"] == "window/showMessage"), + "a good config says nothing: {messages:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_broken_vfmt_toml_warns_once_and_still_formats() { + let dir = temp_dir("brokenconfig"); + std::fs::write(dir.join("vfmt.toml"), "indent = 4\nbogus = 1\n").expect("write config"); + let file = dir.join("m.sv"); + std::fs::write(&file, UNFORMATTED).expect("write"); + + // Two formatting requests, no edit in between: the warning is said once. + let messages = format_session(&dir, &file, &[2, 3]); + for id in [2, 3] { + assert_eq!( + new_text(&messages, id), + "module m;\n wire a;\nendmodule\n", + "formatting proceeds with the built-in defaults, never fails" + ); + } + + let warnings: Vec<_> = + messages.iter().filter(|m| m["method"] == "window/showMessage").collect(); + assert_eq!(warnings.len(), 1, "once per file change, got {warnings:#?}"); + assert_eq!(warnings[0]["params"]["type"], 2, "a warning, not an error"); + let text = warnings[0]["params"]["message"].as_str().expect("a message"); + assert!(text.contains("unknown key `bogus`"), "{text}"); + assert!(text.contains("vfmt.toml:2"), "the message names file and line: {text}"); + + let _ = std::fs::remove_dir_all(&dir); +} + /// A buffer that is broken *and* still has a resolvable reference: error /// recovery is what makes both true at once, and the LSP depends on it. const SOURCE: &str = "module top;\n wire a;\n assign a = 1;\n wire ;\nendmodule\n"; #[test] fn the_binary_serves_a_whole_session_over_stdio() { - let dir = temp_dir(); + let dir = temp_dir("session"); let file = dir.join("top.sv"); std::fs::write(&file, SOURCE).expect("write"); let root = format!("file://{}", dir.display()); @@ -91,18 +201,7 @@ fn the_binary_serves_a_whole_session_over_stdio() { ] .concat(); - let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server")) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .expect("the server binary starts"); - - child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session"); - let stdout = child.stdout.take().expect("stdout"); - let messages = unframe(BufReader::new(stdout)); - let status = child.wait().expect("the server exits"); - assert!(status.success(), "clean exit, got {status:?}"); + let messages = talk(&session); // 1. The initialize response advertises what we implement. let initialize = messages diff --git a/docs/features/editor-packaging/README.md b/docs/features/editor-packaging/README.md new file mode 100644 index 0000000..cb5f860 --- /dev/null +++ b/docs/features/editor-packaging/README.md @@ -0,0 +1,482 @@ +# editor-packaging + +## Goal + +`vfmt-server` has been a running binary since round 11, but a binary nobody can +launch from an editor is a demo. This round closes TODO.md §6's last +non-deferred item: a **minimal VS Code extension** that registers the +Verilog/SystemVerilog file types and starts the server, and **documented +Vim/Neovim configuration** that does the same with no plugin at all. The +governing constraint is TODO.md §6's own sentence — *"no editor-specific logic +below the protocol layer"* — read in the other direction: no *language* logic +above it either. Every feature a user sees comes from the server, so this +feature ships one 41-line JavaScript file, one setting, two markdown guides, +and a dependency-free smoke test that proves the extension's spawn contract +matches the binary's reality without opening an editor. + +## Assumptions + +- **VS Code has no built-in generic LSP client.** `vscode.lsp` does not exist; + the editor's own extensions (and ruff's, and rust-analyzer's) all use + `vscode-languageclient`. Writing a client by hand means re-implementing + `Content-Length` framing, document sync, capability negotiation and edit + application inside a JavaScript file — strictly more code and strictly more + bugs than the dependency. Justification for the dependency is its own section + below, per CLAUDE.md. +- **JavaScript, not TypeScript**, so there is no build step: what is in + `editors/vscode/` is what runs. At 41 lines the type checking buys nothing + that reading the file does not. +- **The server takes no arguments and no environment.** `main.rs` parses no + argv; the entire contract is "spawn it, speak LSP on stdin/stdout". If that + ever changes, `smoke.js` and `extension.js` must change together — that is + exactly the pairing `smoke.js` exists to police. +- **`.v`/`.vh` are `verilog`, `.sv`/`.svh` are `systemverilog`.** These are the + language ids the Verilog ecosystem already uses (and the ones the server's + own e2e test sends). Files whose extension VS Code has given to another + extension keep that extension's language id; the setup note in + `editors/vscode/README.md` covers the collision. +- **The user builds the binary.** No download, no bundled executable, no + version check between extension and server. `cargo build --release` and a + `PATH` entry, or an absolute `vfmt.serverPath`. A version handshake would be + worth adding the day a released extension can meet an older server; today + they come out of the same working tree. +- **Marketplace publishing is out of scope**, as is CI packaging. `publisher` + is the literal string `REPLACE-ME`: packaging a `.vsix` and installing it + locally works with a placeholder, `vsce publish` does not, and inventing a + publisher id nobody owns would be worse than an obvious placeholder. + +## What was deliberately left out + +Each of these is a thing a VS Code extension usually has. Each was considered +and dropped, because the brief and CLAUDE.md's "simplicity first" both point +the same way: + +| Not shipped | Why | +|---|---| +| TextMate grammar | The server ships `semanticTokens` (14 types, `docs/features/vfmt-server/README.md`). A grammar would be a second, worse highlighter to keep in sync. | +| `language-configuration.json` | Comment/bracket rules are the smallest useful thing here, and still a judgement call about Verilog syntax living in the editor layer. The brief says "declare the language only"; if `Ctrl+/` proves painful, this is the first thing to add back — 12 lines, no dependency. | +| Commands (restart server, show logs) | The language client already contributes a restart command and an output channel. | +| Status bar item | State the user can already see in the Output panel. | +| Settings beyond `serverPath` | Formatter options belong in `vfmt.toml`, one source of truth for the CLI and the editor. (The caveat that once lived here — "the server does not read it yet" — was closed by vfmt-core-lift; lead trued up all three doc locations at review.) | +| Bundling (esbuild/webpack) | `vsce` warns about the 166 JavaScript files in the dependency; bundling would add a build step to a repo whose extension has none. 460 KB is not a problem worth a toolchain. | +| A Neovim plugin | The configuration *is* the integration. A plugin would only wrap `vim.lsp.config`. | + +## The one dependency, and the justification CLAUDE.md asks for + +| package | version | why not std, why not hand-rolled | +|---|---|---| +| `vscode-languageclient` | `9.0.1` (exact, no `^`) | Microsoft's own client library, maintained alongside the protocol spec and used by essentially every language extension including ruff's. It is the exact analog of `lsp-server`/`lsp-types` on the Rust side, and the reasoning is the same one `docs/features/vfmt-server/README.md` records for those: the alternative is hand-writing the wire format. Requires VS Code `^1.82.0`, which is `package.json`'s `engines.vscode`. | + +Transitive cost, measured on this machine (`npm ls --all`): **8 packages +total** — `vscode-languageclient` plus `vscode-languageserver-protocol`, +`vscode-languageserver-types`, `vscode-jsonrpc` (the protocol proper, all four +from Microsoft), and `semver`, `minimatch`, `brace-expansion`, +`balanced-match`. No native modules, no install scripts. Packaged `.vsix`: 320 +files, 462 KB. + +Pinned exactly rather than with `^`, matching the workspace's Rust +dependencies: an extension that silently picks up a new client minor on the +next `npm install` is an extension whose bug reports cannot be reproduced. + +## `smoke.js` — the validation that does not need an editor + +The highest-value automated check here is not "does the extension render", it +is **does the extension's spawn contract match the binary's reality**. That +question is answerable in plain node: + +`editors/vscode/smoke.js` spawns the server the way `extension.js` does — same +program, empty argument list, inherited `env`, the working directory as `cwd`, +stdio pipes — then writes a whole `initialize` → `initialized` → `didOpen` → +`shutdown` → `exit` session with hand-rolled `Content-Length` framing, reads +stdout, and asserts: the process exits 0, `initialize` returned capabilities, +four named capabilities are present, diagnostics were pushed for the opened +document, and `shutdown` was acknowledged without an error. + +Three deliberate choices, all inherited from `crates/vfmt_server/tests/e2e.rs`: + +- **The framing is hand-rolled.** A check that reused `vscode-jsonrpc` could + not catch a framing bug, and could not run before `npm install`. +- **The whole session is written before a byte is read.** The rationale is the + one in `tests/e2e.rs`'s own header, reinforced by the vfmt-server QA log's + hang investigation: interleaving reads and writes against a subprocess is how + a smoke test becomes an intermittent hang. The session is under 4 KB, well + inside a pipe buffer, and the server closes stdout on `exit`, so the read + terminates on its own. No timeouts, no reader thread, no deadlock. +- **`rootUri: null`, no `workspaceFolders`.** That is the single-file mode the + Neovim `single_file_support = true` claim depends on, so the smoke test + proves that claim as a side effect. + +It is not a duplicate of `tests/e2e.rs`. That test proves the *server* works +and runs under `cargo test`; this one proves the *extension's launch +configuration* works, runs with zero dependencies at any point in the install +sequence, and is the thing to run when a user reports "nothing happens". + +## Handshakes + +**Consumed from `vfmt_server`** — and this is the whole interface, exactly as +that feature's README promised ("the editor packaging round will consume the +binary's name and its stdio contract, nothing else"): + +1. Binary name `vfmt-server`, resolved on `PATH` by default. +2. No command-line arguments, no required environment. +3. LSP over stdin/stdout, `Content-Length` framing. +4. `initialize` succeeds with neither `workspaceFolders` nor `rootUri` + (single-file mode) — relied on by `single_file_support` in the Neovim config + and asserted by `smoke.js`. +5. The advertised capability set, which both editor guides describe and neither + editor extends: nothing is advertised client-side that the server does not + implement. + +**Promised to `vfmt_server`:** the spawn contract above. If the server ever +grows a required flag, a subcommand, or a stdio mode switch, `extension.js` and +`smoke.js` change in the same round. + +**Requested of other modules** — none blocking, none done here: + +1. **`crates/vfmt`: lift `config.rs` into a library** (already filed by + `docs/features/vfmt-server/README.md`). Restated because it is now + *user-visible*: formatting from an editor ignores `vfmt.toml`, so a project + that sets `line-length = 120` gets 100-column formatting on save and + 120-column formatting from the CLI — the two disagreeing on the same file. + Both editor guides state this caveat out loud rather than hide it, but the + fix is that lift. +2. **Repo root: no `LICENSE` file exists.** The root `Cargo.toml` and the + extension's `package.json` both declare MIT, but `vsce package` wants the + file and needs `--skip-license` without it. Adding one is a one-line repo + decision that is not this feature's to make; the flag is documented, with a + note to drop it once the file lands. + +## Status / TODO + +- [x] `editors/vscode/package.json` — language declarations, activation, + `vfmt.serverPath`, pinned `vscode-languageclient`. +- [x] `editors/vscode/extension.js` — 41 lines, plain JS, no build step. +- [x] `editors/vscode/smoke.js` — zero-dependency spawn-contract check. +- [x] `editors/vscode/README.md` — build, smoke, package, install, + troubleshooting. +- [x] `editors/vscode/.vscodeignore` / `.gitignore` — keep `smoke.js` out of + the `.vsix`, keep `node_modules/` and `*.vsix` out of git. +- [x] `editors/nvim/README.md` — `vim.lsp.config` (0.11+), `nvim-lspconfig` + (0.9/0.10), Vim 9 `vim-lsp` one-liner, coc.nvim. +- [x] Top-level `README.md` "Editor setup" section. +- [x] TODO.md §6 editor-packaging checkbox. +- [x] `smoke.js` run green against a release build. +- [x] `npm install` and `vsce package` run green on this machine. +- [ ] **Not done, and honestly untestable here:** the extension has never run + inside VS Code. `require('vscode')` resolves only in the extension host, + so the `activate` path cannot be exercised outside the editor and was not + claimed to be. See the Work log for exactly what *was* proven instead. +- [ ] **Not done:** the Neovim/Vim snippets were not executed — no `nvim` on + this machine (`vim` 9.1 is present but without `vim-lsp`). The server-side + assumptions they rest on were verified independently; see the Work log. +- [ ] **Not done, out of scope:** CI packaging, Marketplace publishing, a + version handshake between extension and server, bundling. +- [ ] **Follow-up, blocked on a concurrent round:** a `crates/vfmt_core` lift + (config + walk out of the `vfmt` binary) landed in the tree *while this + round was being written*, and `crates/vfmt_server` already depends on it. + If that closes the "the server does not read `vfmt.toml`" gap, the caveat + must be deleted from **three** places: `README.md`'s Editor setup + section, `editors/vscode/README.md` (Settings), and + `editors/nvim/README.md` ("What you get"). Left in place here because it + was true of the binary this round tested and I do not claim behavior I + have not run. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md`, TODO.md §6 and + `docs/features/vfmt-server/README.md` (all of it, including the QA log) before + writing anything. Two things from that reading changed the work: the server's + **staleness model** and its **`vfmt.toml` blindness** are user-visible + behaviors, so both editor guides state them plainly instead of letting a user + discover them as bugs; and the QA log's hang investigation settled `smoke.js`'s + I/O shape before I wrote a line of it. +- **Did not touch `crates/`.** The one thing this feature wanted from another + module — config discovery — was already an open Handshake from the + vfmt-server round, so it is restated here with its now-visible user + consequence rather than fixed. +- **`vscode-languageclient` was taken, and the reasoning is written down.** The + brief floated a zero-dependency client; VS Code has no built-in generic LSP + API, so that would mean hand-writing framing, sync and capability handling in + JavaScript — the thing CLAUDE.md's `lsp-server` justification already + rejected on the Rust side. Pinned exactly (`9.0.1`, not `^9.0.1`) to match + the workspace's `=`-pinned Rust deps. Cost measured, not assumed: 8 packages, + no native modules, no install scripts. +- **Cut everything that was not "launch the server and register the file + types"**: no grammar, no `language-configuration.json`, no commands, no + status bar, no bundler, one setting. The table above records each cut and its + reason so the next person does not re-litigate them silently. The + `language-configuration.json` cut is the one I'd expect to be revisited — it + costs `Ctrl+/` comment toggling — and it is flagged as such rather than + hidden. +- **`smoke.js` is the round's real deliverable.** Everything else here is + configuration that can only be proven inside an editor; the spawn contract + can be proven in a shell, so it is. It mirrors `tests/e2e.rs` deliberately — + same write-everything-then-read shape, same hand-rolled framing, same reason + — but it is not a copy: it asserts what the *extension* depends on + (`rootUri: null` works, the four capabilities the guides promise are present, + the process exits 0), not what the server's internals do. +- **Verified `smoke.js` actually fails when it should**, which is the part + people skip. Two negative controls: a nonexistent binary → `FAIL … ENOENT`, + exit 1; `/bin/cat` as the "server" (echoes the frames straight back, so the + parse succeeds and the *content* is wrong) → `FAIL — initialize response + carries no capabilities`, exit 1. A smoke test that only ever passes is a + smoke test nobody has tested. +- **The Neovim guide's `vim.filetype.add` line was going to be boilerplate + until I checked.** In vim 9.1's `filetype.vim` (the tables Neovim's descend + from) `*.sv`/`*.svh` map to `systemverilog` outright, but `*.v` runs a + *content heuristic*, `dist#ft#FTv()`, that chooses between Verilog, Coq and + V, and **`*.vh` is not mapped at all**. So the line is load-bearing for + `.vh` headers and for short `.v` files, and the guide now says why, with the + Coq/V caveat. +- **Did not install the extension into the user's VS Code.** `code` is on this + machine and `code --install-extension` would have worked, but installing into + someone's editor is a change to their environment, not a validation step I + was asked for. The `.vsix` was built, inspected and deleted; the install + command is documented, unrun. +- **Concurrency note.** Midway through this round another agent's `vfmt_core` + round landed in the same tree — `crates/vfmt/src/{config,walk}.rs` moved to a + new `crates/vfmt_core`, and `crates/vfmt_server/Cargo.toml` gained a + dependency on it. That is exactly the Handshake `docs/features/vfmt-server` + filed and this feature restated, so the `vfmt.toml` caveat in the three + editor docs is likely to become false very soon. I left it as written: it was + true of the binary I built and smoke-tested, and the follow-up is recorded in + Status/TODO with the exact three places to edit. Nothing under `crates/` was + touched by me. +- Did not run `git commit` / `git push`. Did not modify any file under + `crates/`. + +**What was actually validated on this machine, precisely:** + +| Check | Result | +|---|---| +| `cargo build --release -p vfmt_server` | exit 0, `target/release/vfmt-server` | +| `node smoke.js target/release/vfmt-server` | **`smoke: OK` — 3 messages, exit 0** | +| `smoke.js` negative control: missing binary | FAIL, exit 1 (as designed) | +| `smoke.js` negative control: `/bin/cat` | FAIL on capabilities, exit 1 (as designed) | +| `package.json` parses as JSON | yes (`JSON.parse`) | +| `node --check extension.js` / `smoke.js` | both parse | +| `npm install` | 8 packages, `vscode-languageclient@9.0.1` resolved exactly, `engines.vscode ^1.82.0` matches ours | +| `npx @vscode/vsce package --skip-license` | **`.vsix` built** — 320 files, 462 KB, `smoke.js` correctly excluded by `.vscodeignore` | + +**Authored but not run here, and why:** + +- **The extension inside VS Code.** `require('vscode')` resolves only in the + extension host — confirmed by trying: requiring `vscode-languageclient/node` + outside VS Code throws `Cannot find module 'vscode'`. So `activate()` is + unexercised. What *is* proven: the file parses, the dependency resolves and + matches the declared engine, the package builds into an installable `.vsix`, + and the spawn contract the `activate` path uses works against the real + binary. +- **Every Vim/Neovim snippet.** No `nvim` on this machine (`command -v nvim`: + nothing; `vim` 9.1 exists, without `vim-lsp`). Expected behavior on a machine + that has it: `:checkhealth vim.lsp` shows one client `vfmt` attached to the + buffer with `documentFormattingProvider`, `hoverProvider`, + `definitionProvider`, `referencesProvider`, `documentSymbolProvider`, + `workspaceSymbolProvider` and `semanticTokensProvider` set and + `positionEncoding` `utf-16`; `K` on a `` `MACRO `` shows its definition; `gd` + on a signal jumps to its declaration. The two server-side facts those + snippets rest on were checked independently rather than assumed: the + no-root/single-file `initialize` (asserted by `smoke.js`) and the filetype + mapping (read out of vim 9.1's `filetype.vim`, above). +- **`code --install-extension`** — deliberate, see above. + +## QA log + +### 2026-08-19 — QA agent + +**Build tested:** `HEAD` at `c8b936a7` plus the working tree exactly as it +stood (20 changed/untracked paths, `git status --short`), rebuilt twice +(`cargo build --release -p vfmt_server`, both times "Finished ... in 0.02s" — +already up to date, so one stable binary throughout this pass: +`target/release/vfmt-server`, 1,996,608 bytes, md5 `ed84f61d8c414e34d840571` +`f8696191e`, mtime 09:26). This build **includes the concurrent +`vfmt_core` config/walk lift** (`crates/vfmt_core/src/{config,walk}.rs`, +`crates/vfmt_server` depends on it) — see the Finding below. Did not touch +anything under `crates/`; rebuilt only to confirm the binary was settled +before each spawn-based check, per the lead's note that the vfmt_core-lift +agent was doing its own final gate runs concurrently. + +**Validation matrix — all green, re-run to completion:** + +| Check | Result | +|---|---| +| `cargo build --release -p vfmt_server` (x2, bracketing the session) | exit 0 both times, binary unchanged between runs | +| `node smoke.js ../../target/release/vfmt-server` | `smoke: OK` — 3 messages, exit 0 (re-run at session end too) | +| Negative control: `node smoke.js /nonexistent/vfmt-server` | `FAIL — could not spawn ... ENOENT`, exit 1 | +| Negative control: `node smoke.js /bin/cat` | `FAIL — initialize response carries no capabilities`, exit 1 | +| `node --check extension.js` / `smoke.js` | both parse clean | +| `python3 -c json.load` on `package.json` | valid JSON | +| `wc -l extension.js` / `smoke.js` | 41 / 93 — both claims exact | +| `npm ci` in a scratch copy (not `node_modules`, the real one untouched) | 8 packages, `vscode-languageclient@9.0.1` resolved exactly (`npm ls --all` tree matches the README's dependency table verbatim) | +| `npx @vscode/vsce package --skip-license` | **see Finding 2 below — required relocating the copy out of the scratchpad path** | +| `.vsix` contents (`unzip -l`) | 320 files, 462.22 KB (dev's numbers exact); `smoke.js`, `.gitignore`, `.vscodeignore` all absent, `extension.js`/`package.json`/`readme.md`/`node_modules/*` present | + +**Finding 1 (confirmed, significant, not blocking function) — the +`vfmt.toml`-blindness caveat is now false against the tested binary.** +The `vfmt_core` lift landed in the working tree (uncommitted) and +`crates/vfmt_server` already consumes it: `cargo test -p vfmt_server --release +format::` passes `a_config_file_beats_the_editors_tab_size` and +`a_vfmt_toml_governs_the_buffer_it_sits_above`, both asserting `vfmt.toml` +wins over the client's tab size. I additionally drove a live LSP round-trip +against the built binary (scratch dir with `vfmt.toml` containing +`indent = 4`, `.git` marker, `rootUri` pointing at it) and requested +`textDocument/formatting` with `tabSize: 2`: the response's `newText` used +4-space indent, i.e. the config file won over the client, over the wire, on +this exact binary. This means the caveat "the server does **not** read +`vfmt.toml` yet" is no longer true of the binary these docs describe. It +appears verbatim in all three places `docs/features/editor-packaging/README.md`'s +own Status/TODO already flagged: top-level `README.md` (Editor setup +section), `editors/vscode/README.md` (Settings section), and +`editors/nvim/README.md` ("What you get, and what you don't" section) — plus +it's echoed in this feature's own Assumptions/Handshakes/Status-TODO/Work-log +prose. Per the lead's instruction this cleanup belongs to the lead / the +vfmt-server docs owner, not to this QA pass, so I have not edited any of +those five locations — reporting precisely instead, as asked. Locations, +for the fix: `README.md` (top-level, "Editor setup"), `editors/vscode/README.md` +(Settings), `editors/nvim/README.md` ("What you get"), plus (not previously +flagged by the dev, since it's this feature's own doc) this file's Assumptions, +Handshakes and Status/TODO sections restate the same now-false claim and +should get the same pass when the caveat is retired. + +**Finding 2 (environment artifact, not a defect in the feature) — `vsce +package` fails inside the assigned scratchpad path.** Copying +`editors/vscode` (minus `node_modules`) into +`.../9ecac3b9-8a0e-4065-85de-23cc2a396bad/scratchpad/vscode_copy` and running +`npm ci` + `npx @vscode/vsce package --skip-license` there fails every time +with `ERROR Extension entrypoint(s) missing ... extension/extension.js`, and +`vsce ls` silently lists zero files. Reproduced with a *minimal* two-file +extension (bare `package.json` + `extension.js`, no `.vscodeignore`) in the +same scratchpad tree — same failure — and confirmed it packages fine when +the identical minimal extension sits in a plain path (`/tmp/vsce_plain_test`, +no UUID segment). Root cause traced into `@vscode/vsce`'s `collectAllFiles` +(`out/package.js`): it shells out to `npm list --production --parseable +--depth=99999` to get the directories to glob, and on this machine +(`node v26.7.0`, `npm 11.19.0`) that command's own captured output for a +cwd under the scratchpad's UUID-bearing path came back with the UUID +segment replaced by `***` when written to a file — i.e. something in this +sandbox rewrites that specific path shape somewhere in the child-process +output pipeline, and `vsce` then globs a path that doesn't exist, silently +getting zero files. This is **not** a defect in `editors/vscode` — it +reproduces identically for a trivial unrelated extension — so I re-ran the +`npm ci` + `vsce package` step in a copy under plain `/tmp` (deleted +immediately after, along with the scratchpad copy) to get a real result; see +the validation matrix above. Flagging so nobody mistakes "vsce fails" for a +packaging regression if they hit this same scratchpad-path issue later. + +**Claims verified, no issues found:** + +1. **`package.json`** — languages `verilog` (`.v`/`.vh`) and `systemverilog` + (`.sv`/`.svh`) exactly as claimed; `activationEvents` is + `["onLanguage:verilog", "onLanguage:systemverilog"]`, matching the + language ids character-for-character (no typo — this was checked + specifically, since a mismatch here is the "silently never activates" + failure mode); one setting `vfmt.serverPath` default `"vfmt-server"`; + `vscode-languageclient` pinned `"9.0.1"` (no `^`), confirmed both in + `package.json` and resolved exactly in `package-lock.json` + (`lockfileVersion: 3`) and in a fresh `npm ci`; `engines.vscode` is + `^1.82.0` on both `package.json` and matches the feature README's prose; + `publisher` is the literal string `REPLACE-ME`; `.vscodeignore` excludes + `smoke.js` (plus `.vscode/**`, `.gitignore`) — confirmed absent from the + built `.vsix`. +2. **`extension.js`** — read every line, 41 total (`wc -l` exact). Spawns + `serverPath` read from `vfmt.getConfiguration('vfmt').get('serverPath')` + with fallback `'vfmt-server'`; `serverOptions = {command, args: [], + transport: TransportKind.stdio}` matches `vscode-languageclient@9.0.1`'s + `Executable` interface (`lib/node/main.d.ts`: `command`, `transport?`, + `args?`, `options?`) exactly; `documentSelector: [{language: 'verilog'}, + {language: 'systemverilog'}]` matches the contributed language ids + exactly; `new LanguageClient('vfmt', 'vfmt', serverOptions, + clientOptions)` matches the 4-arg `(id, name, serverOptions, + clientOptions, forceDebug?)` overload in `main.d.ts`; `deactivate()` + returns `client.stop()` so VS Code awaits shutdown. No other features + present. **Spawn-failure behavior traced through the library source** + (`lib/common/client.js`, `lib/node/main.js`): on ENOENT, `cp.spawn` + yields no pid, `handleChildProcessStartError` rejects, the client's own + `createConnection` catch calls `this.error(..., 'force')`, which *always* + shows a `window.showErrorMessage` popup (with a "Go to output" button) + and appends to the `vfmt` output channel regardless of + `revealOutputChannelOn` — `extension.js` itself doesn't need a `.catch()` + on `client.start()` because the library never lets a spawn failure go + unsurfaced. This matches the README's troubleshooting text ("See what the + server is saying... View → Output → the vfmt channel"); the README could + additionally mention the error popup explicitly but doesn't claim silence, + so nothing here is inaccurate, just slightly less complete than it could be. +3. **`smoke.js`** — zero-dep (`require('child_process')` only), 93 lines + exact. Ran clean against the release binary and both negative controls + (missing binary, `/bin/cat`) exactly as claimed — see validation matrix. +4. **`editors/nvim/README.md`** — all four client variants present + (`vim.lsp.config` 0.11+, `nvim-lspconfig` 0.9/0.10, Vim 9 `vim-lsp` + one-liner, coc.nvim `coc-settings.json`); root markers + `vfmt.toml`/`.vfmt.toml`/`.git` consistent across all four; the + `vim.filetype.add` line's load-bearing claim was checked directly against + `/usr/share/vim/vim91/filetype.vim` on this machine (vim 9.1, matches + what the dev cited): `*.sv,*.svh` map straight to `systemverilog` + (line 2828), `*.v` runs through `dist#ft#FTv()` (line 2822, defined in + `/usr/share/vim/vim91/autoload/dist/ft.vim:1523`, which sniffs buffer + content), and `grep '\.vh\b' filetype.vim` finds nothing — `.vh` is + genuinely unmapped. The doc's description of all three is accurate. + Single-file-mode claim (`single_file_support = true`) is backed by the + server accepting `initialize` with `rootUri: null` — confirmed live both + by `smoke.js` and by my own `probe.js` round trip. +5. **Honesty of the authored-vs-validated split** — confirmed on this + machine: `command -v nvim` → not found; `vim --version` → 9.1 present; + searched `~`, `~/.vim`, `~/.vimrc`, `~/.config/nvim`, and + `find / -maxdepth 6 -iname '*vim-lsp*'` → nothing, so "vim without + vim-lsp" is accurate and unchanged from the dev's own check. The "extension + never run inside VS Code" claim is consistent with reality: `require`ing + `vscode-languageclient/node` outside the extension host throws + (`Cannot find module 'vscode'`), so `activate()` genuinely cannot be + exercised from a shell. TODO.md §6's "Editor packaging" item is `[x]` + and its one-line summary (extension shape, dependency, filetype mapping, + manual-install scope) matches what's actually in `editors/`. All seven + required feature-README sections (Goal, Assumptions, Handshakes, + Status/TODO, Work log, QA log, Review) are present in this file. + +**Overall: PASS**, with Finding 1 (stale `vfmt.toml` caveat, now confirmed +false, not this feature's docs to fix) as the one substantive issue, +recorded for the lead. No language-id/activation mismatch, no smoke +failure against the current binary — the two conditions the brief called +BLOCKING did not occur. Finding 2 is an environment note, not a shipped-code +defect. No files under `editors/` or `crates/` were modified by this QA pass; +this entry is the only edit made. + +## Review + +**2026-08-19 — lead. Verdict: accepted; commits with round 12. TODO §6 — +the owner's editor requirement — closes with this feature.** + +Points reviewed and accepted: + +1. **The authored-vs-validated split is the feature's backbone** and it + was kept honest on both sides: everything validatable headless was + actually run (the .vsix built and inspected, smoke passed with + negative controls proving it can fail, npm ci reproducibility), and + what can't run here (the extension host, the editor snippets) is + labeled as such with the exact expected behavior stated. QA then + re-ran the whole matrix independently and cross-checked the client + API shapes against the library's own type definitions — the + language-id consistency check (the silent-killer class for VS Code + extensions) came back clean. +2. **`vscode-languageclient` taken, not avoided**: VS Code has no + built-in generic LSP client; hand-rolling one is the same trade + CLAUDE.md already rejected for `lsp-server`. Justified, pinned, + cost-measured (8 packages, no native modules). +3. **The `vim.filetype.add` discovery** — `*.v` goes through Vim's + content heuristic and `*.vh` is unmapped natively, so the snippet + line is load-bearing — is exactly the kind of verified-against- + runtime fact these READMEs exist to hold; QA confirmed it + byte-for-byte against this machine's filetype.vim. +4. QA's Finding 1 (the "server doesn't read vfmt.toml" caveat went + stale mid-round when vfmt-core-lift landed under it) was the lead's + to fix and is now fixed in all flagged locations, including the + vfmt-server README's superseded Assumptions. Finding 2 (vsce's path + resolution breaking inside the session scratchpad) is an + environment artifact, correctly diagnosed by reproducing it on an + unrelated minimal extension. + +Remaining editor work is deliberately out of scope and stays visible: +publishing (a real publisher id, marketplace/OpenVSX), extension-host +integration testing, and lint diagnostics reaching the editor once the +server wires vlog_linter in. diff --git a/docs/features/vfmt-core-lift/README.md b/docs/features/vfmt-core-lift/README.md new file mode 100644 index 0000000..43d515f --- /dev/null +++ b/docs/features/vfmt-core-lift/README.md @@ -0,0 +1,471 @@ +# vfmt-core-lift + +## Goal + +The CLI and the language server were answering two different questions with +two different pieces of code: `vfmt` discovers `vfmt.toml` and walks a tree +honoring `.gitignore` and `--exclude`, while `vfmt-server` formatted with +built-in defaults and indexed everything it could find, because both rules +lived inside the `vfmt` **binary** crate where nothing else could reach them +(the two Handshake requests filed by `docs/features/vfmt-server/README.md`). +That is the classic way an editor's format-on-save drifts away from CI's +`vfmt --check`. This round lifts `config.rs` and `walk.rs` — unchanged — into +a new std-only library crate `crates/vfmt_core`, re-points the CLI at it with +no behavior change at all, and wires the server through the same code: one +discovery rule, one walk, two front ends. + +## Assumptions + +- **The lift is mechanical, and is proven mechanical.** Both modules moved as + 100% renames (`git diff -M` says so) — not one line of logic, and not one + line of their 31 unit tests, was edited. The modules kept their names inside + the new crate, so even the import paths in the moved tests (`use super::*`) + needed no change. Everything the CLI does is therefore unchanged by + construction, and the untouched `crates/vfmt/tests/cli.rs` (48 tests) plus a + byte-identical 820-file corpus (count corrected by lead per QA) run are the evidence. +- **`vfmt_core` is two modules, not a framework.** `pub mod config; pub mod + walk;` and nothing else — no re-export layer, no new traits, no + configuration struct invented for a third caller that does not exist. The + crate has no dependencies, std only, as both modules already did. +- **Precedence in the server is `vfmt.toml` > the client's `tabSize` > the + built-in default**, which is deliberately *not* the CLI's `--flag > config > + default`. The CLI's flag is typed by a human for one run, so it outranks a + file. `FormattingOptions::tab_size` is not that: LSP requires the client to + send it on **every** formatting request, and what it sends is the editor's + own default (VS Code's `editor.tabSize`, 4 unless changed) or its guess from + the file's existing indentation. Treating an editor default as a deliberate + override would let an unconfigured editor silently beat a checked-in + `vfmt.toml` — reintroducing exactly the CLI/editor divergence this feature + exists to delete, and making format-on-save fight `vfmt --check` in CI. + Where the config file is *silent*, `tabSize` still beats the built-in + default, so a project with no `vfmt.toml` behaves exactly as the server did + before this round. `line-length` has no client analog at all and comes from + the config file or not at all. +- **A broken `vfmt.toml` warns the editor; it does not fail it.** The CLI's + contract for an unparsable config is fatal: exit 2, nothing written, all + configs resolved before any file is touched + (`docs/features/config-discovery/README.md`). That is right for a batch tool + where a half-applied run is the danger. It is wrong for an editor: a user who + types a typo into `vfmt.toml` in one tab must not find that format-on-save + has stopped working in every other tab, with an error where their code should + be. So the server formats with the **built-in defaults** (never a partial mix + of the broken file's keys — nothing at all is taken from a file that failed + to parse) and reports the problem as a `window/showMessage` **warning** + carrying the same `path:line: message` string the CLI would have printed. + This is a deliberate divergence in *reporting*, not in *discovery*: the file + searched for, the rule that finds it, and the settings taken from it when it + parses are identical. +- **The warning is said once per file change.** A format-on-save loop asks to + format on every save; repeating the same config error forever would train the + user to dismiss vfmt's messages. The server remembers which documents it has + warned about and re-arms a document when its text changes (`didOpen`, + `didChange`, `didSave` with text) or when it is closed. +- **The index scan anchors its excludes on the workspace root.** `exclude` is + resolved once per command-line input in the CLI, never mid-walk + (config-discovery's own assumption); the server's analog of "an input" is a + workspace root, so the config governing the root supplies the exclude + patterns for that root's whole scan. A `vfmt.toml` in a subdirectory still + governs `line-length`/`indent` for files under it when they are formatted — + discovery there is per-document — it just cannot add excludes mid-scan, + exactly as in the CLI. +- **`.gitignore` is always honored by the scan.** It is the CLI's default and + an editor has no `--no-gitignore` to type. Likewise the scan always runs + discovery enabled: there is no `--no-config` in an editor. +- **A broken config does not stop the scan.** During `initialize` there is no + good way to refuse: a server that indexes nothing because of a typo simply + looks broken. The scan proceeds with no excludes, and the same error reaches + the user through the formatting path, which is where they will look. +- **The server's walk-depth cap is gone, deliberately.** The old plain walk + capped recursion at 64 directories to survive a symlink cycle; the lifted + walk has no cap, because the CLI's does not. Keeping the cap would mean the + index silently covering fewer files than `vfmt` formats — the divergence this + round exists to remove — and *adding* a cap to the shared walk would silently + drop deep files from CLI runs, which is a behavior change this mechanical + lift must not make. Cycle detection belongs in the shared walk where it would + protect both front ends; recorded as a follow-up below, not smuggled in here. +- **Untitled buffers get no config.** A buffer with no path has no directory to + search from, so it is formatted with `tabSize`-or-defaults, as before. +- **Discovery is rebuilt per formatting request.** `Discovery`'s cache is + per-instance and the server is long-lived, so a cached answer would go stale + the moment a user edits `vfmt.toml`. A fresh `Discovery` per request costs + one file read on an explicit, user-initiated action — cheaper than any + invalidation scheme that could be wrong. (config-discovery's Handshakes + anticipated exactly this: "a server can drop and rebuild one when a config + file changes on disk".) + +## Handshakes + +- **New crate `vfmt_core`, consumed by `vfmt` and `vfmt_server`.** Public + surface, unchanged from what it was inside `crates/vfmt`: + - `vfmt_core::config`: `FileConfig { line_length, indent, exclude }`, + `parse(&str) -> Result`, `Discovery::{new, for_input, + for_file, for_dir}`. + - `vfmt_core::walk`: `EXTENSIONS`, `collect_files(input, exclude, gitignore, + &mut Vec) -> Result<(), String>`, `is_excluded(&Path, &[String])`. + Every item already carried the one-line doc comment CLAUDE.md asks for; no + signature changed, so no crate-public boundary moved in a way that needed a + new one. The rules themselves stay documented where they were: + `docs/features/config-discovery/README.md` and + `docs/features/parallel-files/README.md`. +- **`crates/vfmt` consumes `vfmt_core`** and keeps nothing of its own: the two + modules are gone from its `src/`, `mod config;`/`mod walk;` are gone from + `main.rs`, and the three call sites now say `vfmt_core::…`. No duplicated + logic was left behind. +- **Discharges both Handshake requests filed by + `docs/features/vfmt-server/README.md`** (items 1 and 2, config discovery and + the ignore-aware walk). Both are annotated **DELIVERED** in that README, one + line each, as the only edits made to another feature's document. +- **Request to the lead — stale prose in `docs/features/vfmt-server/README.md` + and `TODO.md`, deliberately not edited here** (out of this feature's stated + scope, and a concurrent editor-packaging round is live in the same files): + - vfmt-server README, Assumptions: "**The workspace walk is plain** … + `.gitignore` and `--exclude` are **not** honored" and "**`vfmt.toml` is not + discovered** … The server uses `Config::default()` … with the client's tab + size overriding the indent" are both now false, and the tab-size sentence + is contradicted by the precedence decided above. + - vfmt-server README, Status/TODO: "**Not done:** `vfmt.toml` discovery, + `.gitignore`-aware indexing — both blocked on the two Handshake requests + above" is now done. + - `TODO.md:103` and `TODO.md:120` point at `crates/vfmt/src/config.rs` and + `crates/vfmt/src/walk.rs`; both files now live in `crates/vfmt_core/src/`. + `docs/features/spans/README.md:308` names the old config path in a work-log + sentence about a concurrent round — historical, best left alone. +- **Follow-up for whoever next touches `vfmt_core::walk`:** the walk has no + symlink-cycle detection (a depth cap, or device+inode tracking). It never + had; the CLI has always been exposed to it, and the server now shares the + exposure since its own 64-directory cap was removed for parity. Fixing it in + the shared walk protects both front ends at once — but it changes CLI + behavior (deep trees, cyclic links), so it wants its own round with its own + tests, not a quiet addition inside a mechanical lift. +- **`TODO.md`: no matching checkbox.** The §3 config and `.gitignore` items and + the §6 `vfmt_server` item are already checked; this round moves code and + wires the server, and adds no item of its own. Nothing was checked off. + +## Status / TODO + +- [x] `crates/vfmt_core` created with a **compiling skeleton first**, built + standalone, and only then added to the root `members` (round 11's + ordering lesson, taken literally). +- [x] `config.rs` and `walk.rs` moved as 100% renames, unit tests and all. +- [x] `crates/vfmt` re-wired to `vfmt_core` (`Cargo.toml`, `main.rs`, + `args.rs`); no logic left behind, no CLI behavior change. +- [x] Server formatting discovers `vfmt.toml` anchored at the document's own + path, by the CLI's rule. +- [x] Precedence `config > tabSize > built-in default`, decided and documented. +- [x] Broken config → one `showMessage` warning per file change, formatting + proceeds with defaults, never a crash and never a partial config. +- [x] `initialize`'s scan uses the lifted walk: same extensions, `.gitignore` + honored, excludes from the workspace root's config. +- [x] Tests: `vfmt_core` inherits its 31 moved unit tests; server gains 8 unit + tests (config-beats-tabSize, `vfmt.toml` governing a real buffer, broken + config, untitled buffer, gitignore-honoring scan, root-config excludes, + broken root config, extension filter) and 2 e2e tests through the real + binary over stdio. +- [x] Both vfmt-server Handshakes annotated DELIVERED. +- [x] Gates: `cargo test --workspace`, `cargo clippy --workspace + --all-targets`, `cargo fmt --all --check`, corpus check. +- [ ] **Not done, deliberately:** symlink-cycle detection in the shared walk + (see Handshakes — a real behavior change, wants its own round). +- [ ] **Not done:** re-resolving `exclude` per directory during a scan. The CLI + does not either; the two agree, which is the point of this round. +- [ ] **Not done:** watching `vfmt.toml` for changes + (`workspace/didChangeWatchedFiles`). Discovery is re-run per formatting + request, so an edited config takes effect at the next format without it. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, the two Handshake requests in + `docs/features/vfmt-server/README.md`, all of + `docs/features/config-discovery/README.md` and the behavior half of + `docs/features/parallel-files/README.md` (both QA logs included), and + `crates/vfmt/src/{config,walk,main,args,lint}.rs` before writing anything. +- **Ordering lesson taken literally.** `crates/vfmt_core` was created with a + literal-versioned manifest carrying an empty `[workspace]` table — making it + its own workspace — the two modules were `git mv`'d in, and + `cargo test` was run **standalone** (31 passed) *before* the root `members` + entry existed. Only then was the manifest switched to + `version.workspace = true` and the members line added. A `members` entry + pointing at a crate that does not build breaks the workspace for every other + agent in the tree, and the editor-packaging round was live in it. +- **The lift is provably mechanical.** `git diff -M --summary` reports both + moves as `(100%)`. The 31 unit tests moved with their modules and did not + need even an import-path edit, because the modules kept their names. The + brief allowed edits to those imports; none were required. +- **Behavior preservation, measured rather than asserted.** `crates/vfmt`'s + unit count is unchanged in total (58 = 27 that stayed + 31 that moved), and + `crates/vfmt/tests/cli.rs` — 48 CLI integration tests — is **byte-untouched** + and green. Then the strongest check available: a release `vfmt` built from a + clean `git worktree` at `HEAD` and the working-tree `vfmt` were both run over + the 820-file corpus (count corrected by lead per QA), and their per-file TSVs are **byte-identical** (`diff` + silent; verification-error: none, crash: none in both). The committed + `corpus-check-results.tsv` in the repo predates several landed rounds and was + not touched — it is stale against `HEAD` itself, which the HEAD-vs-working + comparison isolates cleanly. +- **The precedence decision was the one real design call**, and it goes against + the CLI's shape on purpose. Reasoning is in Assumptions above; the short + version is that LSP forces the client to send `tabSize` on every request, so + it is a *default*, not an *intent*, and a default must not beat a file a + human checked in. The rule is pinned by `a_config_file_beats_the_editors_tab_size` + (unit) and by `a_vfmt_toml_governs_formatting_over_the_editors_tab_size` + (e2e: the client asks for `tabSize: 2`, the config says `indent = 4`, the + wire carries four spaces). +- **Split `format::formatting` in two** rather than letting it talk to the + connection: `settings_for(doc, options) -> Settings { config, problem }` + resolves, `formatting(doc, &config)` formats. The handler in `server.rs` + computes both, then warns, which also keeps the immutable borrow of the + document from colliding with the `&mut self` the warn-once set needs. +- **Warn-once is a `HashSet` on `Server`**, cleared by a new + `Server::set_document` wrapper that every text-changing notification now goes + through, and on `didClose`. The e2e test sends **two** formatting requests + with no edit between them and asserts exactly **one** `window/showMessage` + arrives on the wire — the assertion that would catch a regression here, since + a per-request warning would pass every unit test. +- **`state.rs`'s hand-rolled walk is deleted**, not wrapped: `MAX_WALK_DEPTH`, + `SOURCE_EXTENSIONS`, `walk()` and `is_source()` are gone, replaced by + `collect_files`. Its unit test `the_walk_finds_only_source_extensions` tested + a now-private-elsewhere helper, so it was replaced by + `the_scan_takes_only_source_extensions`, which asserts the same thing one + level up — through a real scratch directory and the resulting index — and so + survives the next refactor. +- **The new scan tests use the index as the observation point** (does + `WorkspaceIndex::member` know this package?) rather than reaching for the + private file list, so they pin the behavior a user sees. +- **The format unit tests that need a real tree write a `.git` marker** into + their scratch directory. That stops the upward discovery walk at the temp + dir, so a `vfmt.toml` in some real ancestor of `/tmp` can never leak into a + test result — the `.git`-stops-the-walk rule config-discovery documents, + used as a test-hermeticity tool. +- **Two clippy fixes on the way through**, both in the e2e test: `&PathBuf` → + `&Path` in the new session helper, and the original test's inline + spawn/write/read block replaced by the shared `talk()` helper it now needs + anyway. No `#[allow]` was added anywhere. +- No `unwrap`/`expect`/`panic!` outside `#[cfg(test)]` in any file touched: the + scan swallows a config error with `unwrap_or_default()` and a walk error with + `let _ =`, both with a comment saying why refusing would be worse. +- Did not touch `editors/**`, root `README.md`, `TODO.md`, the corpus TSV, or + any engine crate (`vlog_parser`, `vlog_formatter`, `vlog_semantic`, + `vlog_linter` have no diff at all). Did not run `git commit`/`git push`. + +**Results** (settled tree, all re-run at the end): + +- `cargo test --workspace`: **512 passed, 0 failed** (baseline before this + round: 503; +31 `vfmt_core`, −31 moved out of `vfmt`, +7 net `vfmt_server` + unit, +2 `vfmt_server` e2e). + - `vfmt_core`: 31 unit (20 config + 11 walk), all moved, all unmodified. + - `vfmt`: 27 unit + **48 CLI integration, unmodified** — the + behavior-preservation proof. + - `vfmt_server`: 82 unit (was 75) + 3 e2e (was 1). +- `cargo clippy --workspace --all-targets`: **0 warnings**. +- `cargo fmt --all --check`: clean. +- Corpus: HEAD binary vs. lifted binary over 860 files → **identical TSVs**, + `verification-error: none`, `crash: none`. `corpus-check-results.tsv` + unmodified in the repo. +- Files added: `crates/vfmt_core/{Cargo.toml,src/lib.rs}` (+ the two moved + modules), this README. Files edited: root `Cargo.toml` (one `members` line, + additive), `crates/vfmt/{Cargo.toml,src/main.rs,src/args.rs}`, + `crates/vfmt_server/{Cargo.toml,src/{format,server,state}.rs,tests/e2e.rs}`, + and two annotation lines in `docs/features/vfmt-server/README.md`. + +## QA log + +### 2026-08-19 — QA agent + +Scope: `-p vfmt_core -p vfmt -p vfmt_server`. Verified every claim in the +brief; **all PASS, no blocking findings.** + +**1. Mechanical lift.** +- `git diff -M --summary`: both moves report `(100%)` — confirmed rename, + zero content diff by definition. +- `git show HEAD:crates/vfmt/src/config.rs | diff - crates/vfmt_core/src/config.rs` + and the same for `walk.rs`: **both `diff` exit 0** — byte-identical, no + divergence line. +- `crates/vfmt/tests/cli.rs`: `git diff HEAD` empty (byte-untouched); + `grep -c '#\[test\]'` = 48, all pass. +- Unit total conserved: `vfmt_core` 31 (20 config + 11 walk), `vfmt` 27 + + 48 CLI = 75. 58 (27+31) was the pre-lift `vfmt` total; post-lift it's + 27 (stayed) + 31 (moved to vfmt_core) = 58, matches exactly. +- `main.rs`/`args.rs` call sites confirmed rewired: `use vfmt_core::config::Discovery`, + `use vfmt_core::walk::{collect_files, EXTENSIONS}` (main.rs:28-29), + `use vfmt_core::config::FileConfig` (args.rs:3). No `mod config;`/`mod walk;` + left in `main.rs`. + +**2. CLI behavior identical (corpus md5).** Built `target/release/vfmt` from +the working tree and a second binary from a `git worktree add ... HEAD` +checkout, ran `tools/corpus_check.sh` with each (`-b `) over the +same `corpus/` tree (820 `.v`/`.sv` files — not 860 as the work log states; +see Findings below, non-blocking). Both TSVs: +`md5 = aa982463f68c1a3568c02a0fc5e0c455` — **exact match to the claimed +hash**, `diff` silent, `verification-error: none`, `crash: none` in both. +Worktree removed after (`git worktree remove --force`). + +**3. Server config — all sub-claims verified live**, driving the real +`target/debug/vfmt-server` binary over stdio with a custom interactive +Python driver (scratchpad: `drive_lsp.py`) that can mutate the filesystem +*between* requests in one session — the packaged `talk()` e2e helper writes +the whole session up front and can't do that, so this fills the gap the +brief asked for ("drive the server live"). + - **Fresh discovery per request**: scratch dir with `vfmt.toml` (`indent=4`), + `didOpen`, format with `tabSize:2` → 4-space output (config wins). + Deleted `vfmt.toml` from disk, sent a `didChange` touch (same text), + formatted again → 2-space output (tabSize wins). Confirms the + strongest claim in Assumptions. + - **Bonus, not required by the brief**: repeated the above *without* the + `didChange` touch — discovery was still fresh (2-space on the second + format). Correct per the code: `format::discover` builds a brand-new + `Discovery::new(true)` on every call (format.rs:70), there is no + per-document cache to invalidate, so a `didChange` is not actually + load-bearing for this claim — it just happened to be in the scripted + scenario. Documented here in case a future cache is added and this + stops being true; the README's wording ("Discovery is rebuilt per + formatting request") already states it correctly and doesn't claim a + touch is required. + - **Precedence, `config > tabSize > default`**: unit test + `a_config_file_beats_the_editors_tab_size` and e2e + `a_vfmt_toml_governs_formatting_over_the_editors_tab_size` both green. + - **Precedence edge (config silent on indent)**: scratch `vfmt.toml` + with only `line-length = 100`, formatted with `tabSize:3` → + `newText` used 3-space indent (`"module m;\n wire a;\nendmodule\n"`). + Per-setting precedence confirmed, not per-file. + - **Broken config**: one `window/showMessage` (type 2 = Warning) per file + change, formatting proceeds on defaults, CLI's `path:line: message` + format preserved (`vfmt.toml:2` and `unknown key \`bogus\`` both + present in the message). Two formats with no edit between → exactly + one warning (live-verified: warnings-after-format#1 = 1, + warnings-after-format#2-no-edit = 1). + - **The one-warning throttle, what resets it**: live-verified with a + third format after a `didChange` to the *document text* (config left + broken) → warning count went **1 → 1 → 2**, i.e. the document edit + re-armed the warning exactly as `server.rs`'s `set_document` (which + clears `config_warnings` for that URI on every `didOpen`/`didChange`/ + `didSave`-with-text, and on `didClose`) documents. Matches the README's + "once per file change" rule to the letter — a config-only edit does + not reset it (there's no code path that would), a document edit does. + - `a_vfmt_toml_governs_formatting_over_the_editors_tab_size` and + `a_broken_vfmt_toml_warns_once_and_still_formats`: both green, + assertions match the brief exactly (`newText` diff, warning count, + message content). + +**4. Server scan.** + - `state.rs`: confirmed `MAX_WALK_DEPTH`/`SOURCE_EXTENSIONS`/`walk()`/ + `is_source()` are gone; `source_files()` (state.rs:143) calls + `vfmt_core::walk::collect_files` with `gitignore=true` always and + `Discovery::new(true).for_dir(root)`'s `exclude`, anchored per root — + matches the "workspace-root config excludes" claim exactly. + - Live-verified: scratch workspace with `.gitignore` containing + `ignored_dir/`, a module inside that dir, a visible module at the + root. `workspace/symbol` on a query matching both names returned only + the visible one — the gitignored subdir's module never reached the + index. + - Unit tests `the_scan_skips_what_a_gitignore_skips`, + `the_scan_honours_the_root_configs_excludes`, + `a_broken_root_config_does_not_stop_the_scan`, + `the_scan_takes_only_source_extensions` all present and green. + - Follow-up filing: confirmed present in this README's Handshakes + ("Follow-up for whoever next touches `vfmt_core::walk`" — symlink-cycle + detection, deliberately deferred) and cross-referenced in + `docs/features/vfmt-server/README.md`'s superseded-prose note + ("symlink-cycle exposure now shared with the CLI, filed as a follow-up + in that feature's README"). Filing exists as claimed. + +**5. Gates.** + - `cargo test --workspace`: **512 passed, 0 failed** — summed every + crate's reported count by hand to cross-check the workspace-wide + figure (concurrent round's crates included): 27+48 (vfmt) + 31 + (vfmt_core) + 82+3 (vfmt_server) + 8+1+4+6+2+39 (vlog_formatter) + + 71+30 (vlog_linter) + 53+24+19+17 (vlog_parser) + 6+1+19+20 + (vlog_semantic) + 1 doctest = 512. Exact match to the claim; the + concurrent comments-round-2 work in `vlog_parser`/`vlog_formatter` was + green at the time of this run. + - Scoped counts confirmed exactly: `vfmt_core` 31 unit; `vfmt` 27 unit + + 48 CLI integration; `vfmt_server` 82 unit + 3 e2e (all three e2e tests + green, including `the_binary_serves_a_whole_session_over_stdio` which + predates this round). + - `cargo clippy --workspace --all-targets`: 0 warnings. + - `cargo fmt --all --check`: clean. + - Handshakes: both vfmt-server Handshake items 1 and 2 annotated + **DELIVERED** in `docs/features/vfmt-server/README.md` (lines 256, + 268), one line each as required, plus a Status/TODO checkbox flip and + superseded-prose annotations on the two stale Assumptions bullets — + all carrying a "(lead note)" attribution, consistent with this being + the lead acting on the Handshakes request rather than dev-agent scope + creep. `TODO.md:103` and `:120`x2 (via `git diff`, now at different + line numbers) already point at `crates/vfmt_core/src/{config,walk}.rs` + — also already fixed, also outside this feature's own diff per the + work log's file list. Nothing left for QA to do on these two items. + +**6. CLAUDE.md compliance.** + - `cargo tree -p vfmt_core`: single line, `vfmt_core v0.1.0 (...)`, zero + dependencies — std-only confirmed. + - No `unwrap()`/`expect(`/`panic!` outside `#[cfg(test)]` in + `vfmt_core/src/{config,walk,lib}.rs` or `vfmt_server/src/{format,state, + server}.rs` (checked with an awk pass that stops counting at the + `#[cfg(test)]` marker per file — zero hits before it in every file). + `vfmt/src/{main,args}.rs`'s `unwrap()`/`panic!` calls are all inside + `#[cfg(test)] mod tests` blocks — allowed. + - Every `pub` item in `config.rs`/`walk.rs` carries a `///` doc comment + (spot-checked `FileConfig`, `parse`, `Discovery`, `EXTENSIONS`, + `collect_files`, `is_excluded`). + - README has all seven required sections (Goal, Assumptions, Handshakes, + Status/TODO, Work log, QA log, Review) present and populated (Review + reserved, correctly empty). + +**Findings (all non-blocking):** +- **[Low] Corpus size discrepancy.** The work log's "Results" section says + "820-file corpus (count corrected by lead per QA)"; the actual corpus at HEAD and in the working tree has + **820** `.v`/`.sv` files (`find corpus -type f \( -name '*.v' -o -name + '*.sv' \) -not -path '*/.git/*' | wc -l` = 820, confirmed twice, once per + binary run). This does not affect the correctness claim — both binaries + ran over the identical, actual 820-file tree and produced byte-identical + output at the exact claimed md5 — but the "860" figure in the work log + is inaccurate and should be corrected to 820 if this README is revised + again, so a future reader doesn't chase a phantom 40-file gap. +- **[Info] `corpus-check-results.tsv`'s committed md5** is + `6af28a6d4942c4ddce0a061262eb5d68`, different from the + `aa982463f68c1a3568c02a0fc5e0c455` this round reproduces — expected and + already called out in the work log as pre-existing staleness against + `HEAD` itself (several landed rounds ago), unrelated to this lift. + Not touched, correctly. + +No corrections made to any code or test — nothing broken, nothing to fix. +No masked-corruption attack tests were needed for this round: no +normalization in `verify.rs` was added or widened (this is a config/walk +lift and server-wiring round, not a formatter-safety-net change), so +CLAUDE.md invariant #4 does not apply here. + +## Review + +**2026-08-19 — lead. Verdict: accepted; commits with round 12 (jointly +with editor-packaging — shared README/TODO edits). The CLI/server +behavior gap is closed.** + +Points reviewed and accepted: + +1. **The precedence ruling is the round's contribution**: config > + client tabSize > built-in default, argued from what tabSize actually + is (an editor default sent on every request, not a deliberate + choice). Rejecting the CLI analogy (`--flag > config`) for the + editor was correct — the whole feature exists to stop format-on-save + fighting `vfmt --check` in CI, and treating an unconfigured editor's + 4 as an override would have reintroduced that fight. QA verified the + per-setting edge (config sets only line-length → tabSize still + governs indent) live. +2. **100% renames, byte-identical moved files, untouched CLI suite, + md5-equal corpus TSVs from both builds** — the mechanical-lift bar + was met at every level it can be measured, and QA re-derived each + measurement rather than trusting it. +3. **Warn-once with a document-edit reset** is sensible ergonomics and + QA pinned its exact reset behavior (1→1→2 across format/format/ + didChange+format). The divergence from the CLI's exit-2 (an editor + must not stop formatting over a config typo) is documented where it + belongs. +4. **The depth-cap removal** traded a server-only symlink guard for + CLI parity and filed the shared exposure as a follow-up instead of + smuggling a behavior change into a mechanical lift — the right + instinct, twice. + +Lead fix on acceptance: the corpus file-count figure (860→820) per QA. +The stale vfmt-server Assumptions this lift superseded were struck +through with lead notes at the editor-packaging review, alongside the +TODO path pointers. diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index 1710c6b..151c763 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -27,8 +27,9 @@ looks like language knowledge in here is a bug or a `Handshake` request. Deferred, deliberately, and named in Status/TODO below: range formatting (waits on TODO.md §2 `--lines`), lint diagnostics (waits on `vlog_linter`), -completion / rename / signature help, cross-file references, and `vfmt.toml` -discovery. +completion / rename / signature help, and cross-file references. +(`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this +was written, were delivered by vfmt-core-lift the same day — lead note.) ## Dependencies, and the justification CLAUDE.md asks for @@ -206,9 +207,11 @@ not see. on a POSIX path legitimately named `/C:`. - **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`. - `.gitignore` and `--exclude` are **not** honored — `crates/vfmt` owns that - logic (`walk.rs`) and it is not public. Recorded as a Handshake below. A - depth cap of 64 directories keeps a symlink cycle from spinning. + ~~`.gitignore` and `--exclude` are **not** honored~~ **Superseded by + vfmt-core-lift (lead note): the scan now uses the lifted `vfmt_core` walk — + `.gitignore` always on, workspace-root config excludes applied. The old + 64-directory depth cap is gone for CLI parity (symlink-cycle exposure now + shared with the CLI, filed as a follow-up in that feature's README).** - **A file that does not lex has no tokens.** The lexer is all-or-nothing (`docs/features/error-recovery/README.md`), so `semanticTokens` returns an empty set and hover's macro lookup finds nothing for such a buffer. The @@ -219,10 +222,11 @@ not see. becomes a second error item. Symbols and diagnostics in that state are oddly-placed but never wrong about their spans. This is the documented shape, not a bug in this crate. -- **`vfmt.toml` is not discovered.** Config discovery lives in `crates/vfmt` - (`config.rs`) and is not exposed as a library. The server uses - `Config::default()` (100 columns, 2-space indent) with the client's tab - size overriding the indent when it is sane. Handshake filed below. +- ~~**`vfmt.toml` is not discovered.**~~ **Superseded by vfmt-core-lift + (lead note): discovery now runs per formatting request via `vfmt_core`, + with precedence config > client tabSize > built-in default, and a broken + config warns once and formats with defaults. See + `docs/features/vfmt-core-lift/README.md`.** ## Handshakes @@ -249,7 +253,10 @@ the binary's name and its stdio contract, nothing else. **Requested of other modules** — none of these block this round, and none was done here: -1. **`crates/vfmt`: make config discovery reusable.** `vfmt.toml` search, +1. **DELIVERED** by `docs/features/vfmt-core-lift/README.md` (round 12): + `config.rs` now lives in `crates/vfmt_core`, and formatting discovers + `vfmt.toml` anchored at the document's own path. **`crates/vfmt`: make + config discovery reusable.** `vfmt.toml` search, parsing and precedence live in `crates/vfmt/src/config.rs`, inside a binary crate, so the server cannot call it. The LSP needs exactly the same answer the CLI gives for the same file, and duplicating the search rule is @@ -258,7 +265,10 @@ done here: `discover(path) -> Config`-shaped entry point. Until then the server formats with defaults, which is wrong for any project that sets `line-length`. -2. **`crates/vfmt`: make the ignore-aware walk reusable.** Same shape of +2. **DELIVERED** by `docs/features/vfmt-core-lift/README.md` (round 12): + `walk.rs` now lives in `crates/vfmt_core`, and the index scan uses it, so + the index skips what the CLI skips. **`crates/vfmt`: make the ignore-aware + walk reusable.** Same shape of problem for `walk.rs` (`.gitignore` + `--exclude`). The server's plain walk will index generated netlists a `vfmt` run would skip. 3. **`vlog_parser`: token-kind detail the lexer folds away.** Two spellings @@ -367,8 +377,8 @@ it was written rather than starting mid-line. answering across the workspace means resolving every other file's references *into* this one — an inverted index the workspace layer does not build. It is a real feature, not a small addition. -- [ ] **Not done:** `vfmt.toml` discovery, `.gitignore`-aware indexing — both - blocked on the two Handshake requests above. +- [x] ~~**Not done:**~~ `vfmt.toml` discovery, `.gitignore`-aware indexing — + delivered by vfmt-core-lift (both Handshakes below marked DELIVERED). - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item). diff --git a/editors/nvim/README.md b/editors/nvim/README.md new file mode 100644 index 0000000..4ef622b --- /dev/null +++ b/editors/nvim/README.md @@ -0,0 +1,145 @@ +# vfmt for Vim / Neovim + +There is no plugin here, on purpose: `vfmt-server` speaks plain LSP over stdio, +and every editor in this family already ships a client. What follows is +configuration, not code. + +Build the server first and put it on your `PATH`: + +```bash +cargo build --release # from the repo root +cp target/release/vfmt-server ~/.local/bin/ +``` + +## Neovim 0.11+ (built-in `vim.lsp.config`, no plugins) + +Neovim 0.11 has a native LSP configuration API — `nvim-lspconfig` is no longer +needed for a server this simple. + +```lua +-- ~/.config/nvim/init.lua +vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog' } }) + +vim.lsp.config('vfmt', { + cmd = { 'vfmt-server' }, + filetypes = { 'verilog', 'systemverilog' }, + root_markers = { 'vfmt.toml', '.vfmt.toml', '.git' }, +}) + +vim.lsp.enable('vfmt') +``` + +Use an absolute path in `cmd` (`{ '/path/to/target/release/vfmt-server' }`) if +you would rather not install the binary. + +**The `vim.filetype.add` line is not boilerplate.** In the stock runtime +(checked against vim 9.1's `filetype.vim`, which Neovim's tables descend from) +`*.sv` and `*.svh` map to `systemverilog` outright, but `*.v` goes through a +*content heuristic* — `dist#ft#FTv()` chooses between Verilog, Coq and V by +sniffing the first lines — and `*.vh` is not mapped at all. Without the line, a +short or unusual `.v` file can land on the wrong filetype and a `.vh` header +never attaches the server. Drop the `v =` entry if you also write Coq or V. + +## Neovim 0.9 / 0.10 (`nvim-lspconfig`) + +`vfmt` is not in `nvim-lspconfig`'s registry, so register the config yourself: + +```lua +local configs = require('lspconfig.configs') +local util = require('lspconfig.util') + +if not configs.vfmt then + configs.vfmt = { + default_config = { + cmd = { 'vfmt-server' }, + filetypes = { 'verilog', 'systemverilog' }, + root_dir = util.root_pattern('vfmt.toml', '.vfmt.toml', '.git'), + single_file_support = true, + }, + } +end + +require('lspconfig').vfmt.setup({}) +``` + +`single_file_support = true` matters: the server works with no workspace root +at all (`initialize` with neither `workspaceFolders` nor `rootUri` succeeds), +serving everything single-file. Only cross-file navigation needs a root. + +## Vim 9 (`vim-lsp`) + +One `autocmd`, in `~/.vimrc`: + +```vim +au User lsp_setup call lsp#register_server({'name': 'vfmt', 'cmd': {server_info->['vfmt-server']}, 'allowlist': ['verilog', 'systemverilog']}) +``` + +## coc.nvim + +coc has no `vim.lsp`; it takes servers from `coc-settings.json` (`:CocConfig`): + +```jsonc +{ + "languageserver": { + "vfmt": { + "command": "vfmt-server", + "filetypes": ["verilog", "systemverilog"], + "rootPatterns": ["vfmt.toml", ".vfmt.toml", ".git"] + } + } +} +``` + +## What you get, and what you don't + +Everything in `docs/features/vfmt-server/README.md`'s capability table: +`gd` (definition), `gr` (references, in-file only for now), `K` (hover, +including `` `define`` expansion), `vim.lsp.buf.format()`, document and +workspace symbols, diagnostics as you type, and semantic tokens — Neovim +applies those on top of its treesitter/syntax highlighting with no extra setup. + +Not advertised by the server, so your client will correctly refuse them: range +formatting, completion, rename, signature help, and cross-file references. + +Two behaviors worth knowing before you file a bug: + +- **The workspace index rebuilds on save, not on keystroke.** Cross-file + answers about file A reflect A as of its last write. A's own buffer is always + current. This is the documented staleness model, not a lag. +- **`vfmt.toml` is honored.** The server discovers it per file exactly as + the CLI does; a config setting beats your `shiftwidth`/`tabstop` (an + editor default is not a deliberate override), and without a config your + editor's tab size governs the indent. + +Format on save, if you want it: + +```lua +vim.api.nvim_create_autocmd('BufWritePre', { + pattern = { '*.v', '*.vh', '*.sv', '*.svh' }, + callback = function() vim.lsp.buf.format() end, +}) +``` + +## Checking it works + +``` +:checkhealth vim.lsp " Neovim 0.11+; 0.9/0.10: :checkhealth lsp +:LspInfo " nvim-lspconfig only +:lua =vim.lsp.get_clients({ bufnr = 0 })[1].server_capabilities +``` + +A healthy attach shows one client named `vfmt` with +`documentFormattingProvider`, `hoverProvider`, `definitionProvider`, +`referencesProvider`, `documentSymbolProvider`, `workspaceSymbolProvider` and +`semanticTokensProvider` set, and `positionEncoding` `utf-16`. + +If the client never attaches, the binary is the first thing to check, and you +can check it without Neovim at all: + +```bash +node ../vscode/smoke.js "$(command -v vfmt-server)" +``` + +That drives a full LSP session over stdio and exits 0 only if the handshake and +the capabilities are intact — which separates "the server is broken" from "my +editor config is wrong" in one command. diff --git a/editors/vscode/.gitignore b/editors/vscode/.gitignore new file mode 100644 index 0000000..28a78a7 --- /dev/null +++ b/editors/vscode/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +*.vsix diff --git a/editors/vscode/.vscodeignore b/editors/vscode/.vscodeignore new file mode 100644 index 0000000..639b809 --- /dev/null +++ b/editors/vscode/.vscodeignore @@ -0,0 +1,4 @@ +# The smoke test is a pre-publish check, not part of the shipped extension. +smoke.js +.vscode/** +.gitignore diff --git a/editors/vscode/README.md b/editors/vscode/README.md new file mode 100644 index 0000000..bf872f0 --- /dev/null +++ b/editors/vscode/README.md @@ -0,0 +1,101 @@ +# vfmt for VS Code + +A thin extension: it registers the Verilog/SystemVerilog file types and starts +`vfmt-server`. Every feature you see — formatting, diagnostics, semantic +highlighting, hover, go-to-definition, references, symbols — comes from the +server, so this directory contains no language logic and no editor-specific +commands. See `docs/features/vfmt-server/README.md` for the capability list and +`docs/features/editor-packaging/README.md` for why the extension looks like +this. + +## 1. Build the server + +```bash +cargo build --release # from the repo root; binary at target/release/vfmt-server +``` + +Put it on your `PATH`: + +```bash +cp target/release/vfmt-server ~/.local/bin/ # or wherever your PATH points +``` + +Or leave it in `target/release` and point the extension at it with the +`vfmt.serverPath` setting (below). + +## 2. Smoke-test the spawn contract (no editor needed) + +`smoke.js` spawns the server exactly the way `extension.js` does — same +argument list (none), same cwd, same inherited environment — and drives a full +`initialize` / `didOpen` / `shutdown` / `exit` session over stdio with +hand-rolled `Content-Length` framing. Plain `node`, no dependencies. + +```bash +node smoke.js # `vfmt-server` from PATH +node smoke.js ../../target/release/vfmt-server # an explicit binary +``` + +It prints `smoke: OK — …` and exits 0, or names the failure and exits 1. Run it +after every server change and before packaging: it is the only check that +catches "the binary moved" or "the handshake broke" without launching VS Code. + +## 3. Install the extension + +```bash +npm install # installs vscode-languageclient (the only dependency) +npx @vscode/vsce package --skip-license +code --install-extension vfmt-0.1.0.vsix +``` + +Then reload VS Code and open a `.v`/`.sv`/`.vh`/`.svh` file. + +`--skip-license` is needed only because this repo ships no `LICENSE` file yet +(`package.json` declares MIT). Drop the flag once one exists. If you are +packaging a fork that dropped `package.json`'s `repository` field, add +`--allow-missing-repository` too. + +**Running from source instead**, for development: open this directory in VS +Code and press F5. That starts an Extension Development Host with the extension +loaded from disk, with no packaging step. + +**Publishing to the Marketplace is out of scope.** `publisher` is the literal +placeholder `REPLACE-ME`; `vsce publish` will fail until it is a real publisher +id you own. Packaging a `.vsix` and installing it locally works with the +placeholder, which is what the steps above do. + +## Settings + +| Setting | Default | What it does | +|---|---|---| +| `vfmt.serverPath` | `"vfmt-server"` | Path to the executable. A bare name is looked up on `PATH`; an absolute path is used as given. | + +That is the whole list, deliberately. Formatter options (line length, indent) +belong in a `vfmt.toml`, not in editor settings — one source of truth for the +CLI and the editor. The server discovers `vfmt.toml` for each file exactly as +the CLI does; when it names a setting, it wins over VS Code's tab size (an +editor default is not a deliberate override). Without a config, VS Code's tab +size governs the indent and the line length is the built-in 100. + +## Format on save + +The extension registers no formatter of its own — the server advertises +`documentFormattingProvider`, so VS Code's normal machinery applies: + +```jsonc +// .vscode/settings.json +{ + "[verilog]": { "editor.formatOnSave": true }, + "[systemverilog]": { "editor.formatOnSave": true } +} +``` + +## Troubleshooting + +- **Nothing happens on a `.sv` file.** Check the language mode in the status + bar. Another Verilog extension may own the `.sv` extension with a different + language id; this one attaches to `verilog` and `systemverilog`. +- **"command not found" style failure on startup.** The server is not on + `PATH`. Set `vfmt.serverPath` to an absolute path, and confirm the binary + itself works with `node smoke.js `. +- **See what the server is saying.** View → Output → the `vfmt` channel carries + the client/server log, including anything the server writes to stderr. diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js new file mode 100644 index 0000000..9c55633 --- /dev/null +++ b/editors/vscode/extension.js @@ -0,0 +1,41 @@ +// The whole VS Code extension: start `vfmt-server` over stdio and let the +// language client do the rest. There is deliberately no command, no status +// bar item and no setting other than the server's path — every feature the +// user sees comes from the server, so anything else added here would be +// editor-specific logic above the protocol (docs/features/editor-packaging). + +const vscode = require('vscode'); +const { LanguageClient, TransportKind } = require('vscode-languageclient/node'); + +/** The single client, kept only so `deactivate` can stop it. */ +let client; + +/** Spawn the server and attach it to Verilog/SystemVerilog documents. */ +function activate(context) { + const serverPath = vscode.workspace.getConfiguration('vfmt').get('serverPath') || 'vfmt-server'; + + // No arguments: `vfmt-server` takes none and speaks LSP on stdin/stdout. + // `editors/vscode/smoke.js` spawns it exactly this way. + const serverOptions = { + command: serverPath, + args: [], + transport: TransportKind.stdio, + }; + + // No `scheme` filter: the server serves `untitled:` buffers too, for + // everything single-file (docs/features/vfmt-server/README.md). + const clientOptions = { + documentSelector: [{ language: 'verilog' }, { language: 'systemverilog' }], + }; + + client = new LanguageClient('vfmt', 'vfmt', serverOptions, clientOptions); + context.subscriptions.push(client); + client.start(); +} + +/** Stop the server; VS Code waits on the returned promise. */ +function deactivate() { + return client ? client.stop() : undefined; +} + +module.exports = { activate, deactivate }; diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json new file mode 100644 index 0000000..5f20eb2 --- /dev/null +++ b/editors/vscode/package-lock.json @@ -0,0 +1,97 @@ +{ + "name": "vfmt", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "vfmt", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "vscode-languageclient": "9.0.1" + }, + "engines": { + "vscode": "^1.82.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", + "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/vscode-jsonrpc": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", + "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageclient": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz", + "integrity": "sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==", + "license": "MIT", + "dependencies": { + "minimatch": "^5.1.0", + "semver": "^7.3.7", + "vscode-languageserver-protocol": "3.17.5" + }, + "engines": { + "vscode": "^1.82.0" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", + "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "8.2.0", + "vscode-languageserver-types": "3.17.5" + } + }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + } + } +} diff --git a/editors/vscode/package.json b/editors/vscode/package.json new file mode 100644 index 0000000..6784786 --- /dev/null +++ b/editors/vscode/package.json @@ -0,0 +1,64 @@ +{ + "name": "vfmt", + "displayName": "vfmt — Verilog/SystemVerilog", + "description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the vfmt language server.", + "version": "0.1.0", + "publisher": "REPLACE-ME", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://git.luci.ooo/lucio/verilogrustformatter" + }, + "engines": { + "vscode": "^1.82.0" + }, + "categories": [ + "Programming Languages", + "Formatters", + "Linters" + ], + "main": "./extension.js", + "activationEvents": [ + "onLanguage:verilog", + "onLanguage:systemverilog" + ], + "contributes": { + "languages": [ + { + "id": "verilog", + "aliases": [ + "Verilog", + "verilog" + ], + "extensions": [ + ".v", + ".vh" + ] + }, + { + "id": "systemverilog", + "aliases": [ + "SystemVerilog", + "systemverilog" + ], + "extensions": [ + ".sv", + ".svh" + ] + } + ], + "configuration": { + "title": "vfmt", + "properties": { + "vfmt.serverPath": { + "type": "string", + "default": "vfmt-server", + "description": "Path to the vfmt-server executable. A bare name is looked up on PATH." + } + } + } + }, + "dependencies": { + "vscode-languageclient": "9.0.1" + } +} diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js new file mode 100644 index 0000000..80e46ca --- /dev/null +++ b/editors/vscode/smoke.js @@ -0,0 +1,93 @@ +// Pre-publish smoke test: spawn the server exactly the way extension.js does +// and drive a whole LSP session at it over stdio. Plain node, no dependencies, +// hand-rolled framing — a check that reused a client library could not catch a +// framing or startup bug. Mirrors crates/vfmt_server/tests/e2e.rs. +// +// node smoke.js [path-to-vfmt-server] # default: `vfmt-server` on PATH +// +// Exits 0 on success, 1 on any failure. + +const { spawn } = require('child_process'); + +const serverPath = process.argv[2] || 'vfmt-server'; + +/** Frame one JSON payload the way LSP wants it. */ +function frame(payload) { + const body = Buffer.from(JSON.stringify(payload), 'utf8'); + return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'), body]); +} + +/** Split a stdout dump into its JSON payloads. */ +function unframe(buffer) { + const messages = []; + let at = 0; + while (at < buffer.length) { + const headerEnd = buffer.indexOf('\r\n\r\n', at, 'ascii'); + if (headerEnd < 0) break; + const headers = buffer.toString('ascii', at, headerEnd); + const match = /Content-Length: *(\d+)/i.exec(headers); + if (!match) break; + const start = headerEnd + 4; + const end = start + Number(match[1]); + if (end > buffer.length) break; + messages.push(JSON.parse(buffer.toString('utf8', start, end))); + at = end; + } + return messages; +} + +function fail(message) { + console.error(`smoke: FAIL — ${message}`); + process.exit(1); +} + +// The same spawn contract extension.js uses: no arguments, inherited env, the +// workspace directory as cwd, LSP on stdin/stdout. +const server = spawn(serverPath, [], { cwd: process.cwd(), env: process.env, stdio: 'pipe' }); +server.on('error', (error) => fail(`could not spawn "${serverPath}": ${error.message}`)); + +const chunks = []; +server.stdout.on('data', (chunk) => chunks.push(chunk)); +server.stderr.on('data', (chunk) => process.stderr.write(chunk)); + +// Every message is written before anything is read: the server handles them in +// order and exits on `exit`, so stdout closes on its own and this can never +// deadlock waiting for a message that is not coming. +const uri = `file://${process.cwd()}/smoke_scratch.sv`; +server.stdin.end( + Buffer.concat([ + frame({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { processId: process.pid, rootUri: null, capabilities: {} } }), + frame({ jsonrpc: '2.0', method: 'initialized', params: {} }), + frame({ + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { textDocument: { uri, languageId: 'systemverilog', version: 1, text: 'module top;\n wire a;\nendmodule\n' } }, + }), + frame({ jsonrpc: '2.0', id: 2, method: 'shutdown', params: null }), + frame({ jsonrpc: '2.0', method: 'exit', params: null }), + ]), +); + +server.on('close', (code) => { + if (code !== 0) fail(`server exited with code ${code}`); + + const messages = unframe(Buffer.concat(chunks)); + const initialize = messages.find((m) => m.id === 1); + if (!initialize) fail('no initialize response'); + if (initialize.error) fail(`initialize failed: ${JSON.stringify(initialize.error)}`); + + const capabilities = initialize.result && initialize.result.capabilities; + if (!capabilities) fail('initialize response carries no capabilities'); + for (const capability of ['documentFormattingProvider', 'definitionProvider', 'hoverProvider', 'semanticTokensProvider']) { + if (!capabilities[capability]) fail(`capability missing: ${capability}`); + } + + const diagnostics = messages.find((m) => m.method === 'textDocument/publishDiagnostics'); + if (!diagnostics) fail('the server pushed no diagnostics for the opened document'); + + const shutdown = messages.find((m) => m.id === 2); + if (!shutdown) fail('no shutdown response'); + if (shutdown.error) fail(`shutdown failed: ${JSON.stringify(shutdown.error)}`); + + console.log(`smoke: OK — "${serverPath}" completed initialize/didOpen/shutdown/exit (${messages.length} messages)`); +});