//! `textDocument/formatting`. //! //! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and //! 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. 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, 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 })) } /// 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. /// /// 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` 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 } #[cfg(test)] 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"); let mut ws = Workspace::default(); ws.set_document(uri.clone(), text.to_string()); (ws, uri) } fn options(tab_size: u32, insert_spaces: bool) -> FormattingOptions { 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 = 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"); assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); } #[test] fn an_already_formatted_buffer_gets_no_edit() { let (ws, uri) = document("module m;\n wire a;\nendmodule\n"); 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 = 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() { 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() { 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 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 = 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); } }