From 80017a59f2b112c8b2643b6e77a766193c3e9656 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 19 Nov 2026 06:51:14 -0800 Subject: [PATCH] Release 0.65.5: named formatting styles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §71.5. One setting picks a house layout — [format] style in lucisv.toml, --style, the lucisv.format.style drop-down, the server and MCP: lucisv (default), google, lowrisc, ansi, microsoft, nxp, and auto. Seven layout rules (indent, width, begin placement, else placement, else after a labelled end, one-per-line lists, list indent, alignment), one row per style in one table in crates/vlog_formatter/src/style.rs. google and lowrisc follow those published guides; ansi, microsoft and nxp are lucisv's guesses and say so. auto formats with each preset and keeps the result that changes the fewest lines (crates/vlog_formatter/src/auto.rs); the language server remembers each document's preset (lucisv_server/src/auto_style.rs) so selection and on-type formatting do not repeat the search. The style is part of the format cache key. Proof: default output byte-identical to 0.65.4 on 4 921 files (corpus + OpenTitan hw) against an independently rebuilt 0.65.4; every style formatted three times over the same files with no verification error, crash, token or comment difference (independent lexer) or second-run change. verify.rs is untouched. Dev (three rounds), QA (two rounds, pass with findings) and lead review are in docs/features/format-styles/README.md. Three one-line calls were added to lucisv_server/src/server/notification.rs for the memory's invalidation. TODO.md files the pre-existing bugs QA met on the way. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.5) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree; vlog_formatter 376/0, lucisv_server 1996/0, corpus 814/6. Co-Authored-By: Claude Mythos 5.2 --- CHANGELOG.md | 53 + Cargo.lock | 18 +- Cargo.toml | 2 +- README.md | 64 +- TODO.md | 19 +- crates/lucisv/src/args.rs | 81 +- crates/lucisv/src/main.rs | 1 + crates/lucisv/tests/cli.rs | 5 +- crates/lucisv/tests/style_cli.rs | 171 ++++ crates/lucisv_core/src/cache.rs | 97 +- crates/lucisv_core/src/config.rs | 62 +- crates/lucisv_mcp/src/tools/diagnostics.rs | 4 +- crates/lucisv_mcp/src/tools/format.rs | 29 +- crates/lucisv_server/src/auto_style.rs | 404 ++++++++ crates/lucisv_server/src/format.rs | 103 +- crates/lucisv_server/src/main.rs | 1 + crates/lucisv_server/src/server/formatting.rs | 21 +- crates/lucisv_server/src/server/mod.rs | 5 + .../lucisv_server/src/server/notification.rs | 3 + crates/lucisv_server/src/server/startup.rs | 1 + .../src/server/tests/formatting.rs | 185 ++++ crates/lucisv_server/src/settings.rs | 39 + crates/vlog_formatter/examples/auto_sweep.rs | 129 +++ crates/vlog_formatter/src/align.rs | 58 +- crates/vlog_formatter/src/auto.rs | 169 ++++ crates/vlog_formatter/src/format/branch.rs | 134 +++ crates/vlog_formatter/src/format/instance.rs | 21 +- crates/vlog_formatter/src/format/item.rs | 53 +- crates/vlog_formatter/src/format/list.rs | 57 +- crates/vlog_formatter/src/format/mod.rs | 70 +- crates/vlog_formatter/src/format/module.rs | 10 +- crates/vlog_formatter/src/format/stmt.rs | 87 +- crates/vlog_formatter/src/lib.rs | 4 + crates/vlog_formatter/src/selection/mod.rs | 4 + crates/vlog_formatter/src/style.rs | 236 +++++ crates/vlog_formatter/tests/styles.rs | 686 +++++++++++++ docs/features/format-styles/README.md | 953 ++++++++++++++++++ editors/vscode/CHANGELOG.md | 11 + editors/vscode/README.md | 16 +- editors/vscode/package-lock.json | 4 +- editors/vscode/package.json | 25 +- tools/style_sweep.sh | 73 ++ 42 files changed, 3962 insertions(+), 206 deletions(-) create mode 100644 crates/lucisv/tests/style_cli.rs create mode 100644 crates/lucisv_server/src/auto_style.rs create mode 100644 crates/vlog_formatter/examples/auto_sweep.rs create mode 100644 crates/vlog_formatter/src/auto.rs create mode 100644 crates/vlog_formatter/src/format/branch.rs create mode 100644 crates/vlog_formatter/src/style.rs create mode 100644 crates/vlog_formatter/tests/styles.rs create mode 100644 docs/features/format-styles/README.md create mode 100755 tools/style_sweep.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 73294b2..f834421 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,59 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.65.5 — 2026-11-19 + +### Named formatting styles + +(`docs/features/format-styles`; TODO §71.5.) + +- **One setting picks a house layout.** `[format] style = ""` in + `lucisv.toml`, `--style ` on the command line, or the new + `lucisv.format.style` drop-down in VS Code. Seven layout rules, one row per + style, in one table in `crates/vlog_formatter/src/style.rs`: + + | style | indent / width | `begin` | `else` | lists | list indent | alignment | + |---|---|---|---|---|---|---| + | `lucisv` (default) | 2 / 100 | same line | same line | fit | 1 level | keep | + | `google` | 2 / 100 | same line | same line | one per line | 2 levels | keep | + | `lowrisc` | 2 / 100 | same line | same line | one per line | 1 level | always | + | `ansi` | 4 / 80 | own line | own line | fit | 1 level | keep | + | `microsoft` | 4 / 120 | own line | own line | one per line | 1 level | keep | + | `nxp` | 2 / 80 | same line | own line | one per line | 1 level | always | + +- **Where the styles come from.** `google` follows the Google Verilog Style + Guide and `lowrisc` the lowRISC (OpenTitan) guide, both read for this + release, including `else` on its own line after a labelled `end`. **`ansi`, + `microsoft` and `nxp` are lucisv's educated guesses** — Allman-style + `begin`/`else` after iStyle's and clang-format's styles of those names, and + a conservative aligned RTL style — not rules those organisations publish + for Verilog. +- **The default does not move a byte.** `lucisv` output is identical to + 0.65.4 on all 4 921 files of the corpus and OpenTitan's `hw` tree, checked + against an independently rebuilt 0.65.4. An explicit `indent` or + `line-length` still wins over a style's. +- **Every style goes through the same safety net.** Each was formatted three + times over those 4 921 files: no verification error, no crash, no token or + comment difference (checked with a lexer that is not the formatter's), and + no change on a second or third run. `verify.rs` is untouched. +- **`style = "auto"` keeps a file in the layout it is already closest to.** + It formats with each preset and keeps the result that changes the fewest + lines, so a file written the Google way stays that way. It picks a layout + for the configured indent and width and **never infers them** — set + `indent` to match the file first, or a 4-space file formatted at the + default 2 comes out in the default layout. Small edits do not flip a file: + over 500 files and ten kinds of edit, none rewrote more than 12 lines + outside the edit. `auto` costs a search — 2.4 s against 0.4 s on a + 42 000-line file for a whole-document format — so the language server + remembers each document's layout, and selection and on-type formatting stay + at 0.1 s after the first request. +- **Known limits.** A declaration with several instances in one statement + gets the older hanging layout under the one-per-line styles. The language + server's `line-length` lint still assumes 100 columns under `ansi`, + `microsoft` and `nxp` (the CLI's `check` follows the style). Switching from + one keep-alignment style to another and back is not always a round trip: + alignment a style added stays. + ## 0.65.4 — 2026-11-19 ### `` `ifdef `` blocks fold, and pin in sticky scroll diff --git a/Cargo.lock b/Cargo.lock index 7183329..1477ba9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.4" +version = "0.65.5" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.4" +version = "0.65.5" [[package]] name = "lucisv_mcp" -version = "0.65.4" +version = "0.65.5" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.4" +version = "0.65.5" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.4" +version = "0.65.5" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.4" +version = "0.65.5" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.4" +version = "0.65.5" [[package]] name = "vlog_refactor" -version = "0.65.4" +version = "0.65.5" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.4" +version = "0.65.5" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index e58b42f..9d22625 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.4" +version = "0.65.5" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/README.md b/README.md index ae9ac07..a73bf53 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,9 @@ indent = 2 # 1..8, same as --indent exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file +[format] +style = "google" # a named layout, same as --style (see Named styles) + [lint] select = ["no-tabs", "unused-signal"] # optional replacement for defaults ignore = ["module-filename"] # removed after selection @@ -173,11 +176,20 @@ error (exit 2) and nothing is processed. Details: **Precedence: CLI flag > config file > default**, per setting (`--indent 4` with a file that sets only `line-length` uses both). `exclude` is the exception: config patterns are *added* to `--exclude`, not replaced by it. +`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of +the [named styles](#named-styles). The style is resolved first and supplies +the starting indent and line length; an explicit `indent` or `line-length` — +from a flag or from the file — then wins over the preset's, so +`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An +unknown style name is the same hard error as an unknown key, and lists the +valid names. In the editor, `lucisv.toml` outranks the editor settings as for +every formatting key, and a chosen style (other than `lucisv` or `auto`) also +outranks the editor's tab size. `[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`), off by default, indents the `` `uvm_field_* `` macros written between -`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one -formatting choice lucisv leaves to the project, because it changes bytes -in existing UVM code (21 of the 860 corpus files). +`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`, +it is a formatting choice lucisv leaves to the project, because it changes +bytes in existing UVM code (21 of the 860 corpus files). An unknown key, a bad value, an out-of-range number, or any TOML beyond the supported subset (tables other than `[format]`, `[lint]` and `[lint.]`, multi-line @@ -512,7 +524,8 @@ Key ideas carried over from ruff/prettier: Defaults follow Verible: **2-space indent**, **100-column lines** (both configurable via `--indent` / `--line-length` or a `lucisv.toml`, see -[Configuration](#configuration)). +[Configuration](#configuration)). The list below is the default `lucisv` +style; the [named styles](#named-styles) change some of it. - One port / parameter / connection per line once a header doesn't fit - Cuddled `begin`/`end` (`end else begin`) @@ -521,6 +534,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see - `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed through verbatim +### Named styles + +`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down +pick one of a handful of house layouts. Every style moves whitespace only — +which line a token starts on and how many spaces precede it — so the same +token-equivalence check guards all of them, and each one is a fixed point of +itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for +every preset; `docs/features/format-styles/README.md`). + +| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns | +|---|---|---|---|---|---|---|---|---| +| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them | +| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them | +| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned | +| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them | +| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them | +| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned | +| `auto` | — | — | the preset the file is already closest to | | | | | | + +`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html) +and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md) +(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses** +at what those names suggest — C formatters' ANSI/Allman layout, clang-format's +`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house +style — not rules those organisations publish; none of them publishes a Verilog +style that we could find. A `case` item's and a `do`'s `begin` stays on its +own line's end in every style. "Header & connection lists" are module +headers' parameter and port lists and instances' *named* overrides and +connections — not `#(16)`, ordered connections or function ports. `lowrisc` +differs from its guide in two places: the widest aligned connection keeps one +space before its `(`, and a comment line ends an aligned table. + +`auto` formats the file once per preset, at the configured indent and width, +and keeps the output that changes the fewest lines (indentation included, so +a one-line edit does not flip a whole file to another preset); it never +guesses an indent or a width, and it is idempotent by construction. +**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under +`auto`, range and selection formatting use the style of the whole file, not +of the selected lines; the language server remembers each document's preset +from its last whole-file format, so a keystroke or a selection does not +search again, and a buffer with a parse error keeps its preset. One that has +never resolved — no memory, and it does not parse — gets the default layout. + ### Alignment is inferred, not imposed Hand-aligned columns are how RTL is read, so lucisv reads the spacing you diff --git a/TODO.md b/TODO.md index cb17ca1..ad0a938 100644 --- a/TODO.md +++ b/TODO.md @@ -7328,7 +7328,8 @@ subsection, plan and `docs/features//README.md` when its turn comes. database. - [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the sticky-scroll ("floating") bars. -- [ ] **71.5 The formatter adapts to the file's own style** — where lines +- [x] **71.5 The formatter adapts to the file's own style** (0.65.5, `docs/features/format-styles`: six named styles and `auto`) + — where lines break, what is grouped, how ports align. If inferring that is too ambiguous, a setting with a drop-down of named styles instead (ANSI, Google, Microsoft, NXP — educated guesses), with the rules easy to @@ -7387,3 +7388,19 @@ indexing, collide with each other and with §70's test files, and wait for styles) runs in `../lucisv-wt/71.5` from `d574969`. Owed once ssh is back, in this order: push master and the tags one at a time; re-run §70 on Linux (root twice, `--user`); add the `linux` job to `ci.yml`. + +- Wave 4 (lead, 2026-11-19): 71.5 shipped as 0.65.5 from `../lucisv-wt/71.5`, + rebased onto §70's commit. 71.1 (localized re-index) is with QA in + `../lucisv-wt/71.1`. Found on the way by 71.5's QA, all present in 0.65.4 + and filed here, not fixed: + - [ ] A comment between a generate `end` and `else` (also a trailing `// c` + after a labelled generate `end` before `else`) is a verification + error: the file is left unformatted. The safety net works; the + formatter should not need it. + - [ ] `` `ifdef `` between `end` and `else` is a parse error. + - [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error. + - [ ] The server's `line-length` lint falls back to 100 columns under the + `ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken + when 71.1 merges. + - [ ] One-per-line styles give multi-instance declarations + (`p1 u8 (...), u9 (...)`) the hanging layout. diff --git a/crates/lucisv/src/args.rs b/crates/lucisv/src/args.rs index e1d0f01..b443278 100644 --- a/crates/lucisv/src/args.rs +++ b/crates/lucisv/src/args.rs @@ -1,7 +1,7 @@ //! Hand-rolled command line parsing for the `lucisv` binary. use lucisv_core::cache; -use lucisv_core::config::FileConfig; +use lucisv_core::config::{self, FileConfig}; use vlog_formatter::{Config, LineRanges}; /// Which tool this invocation runs. @@ -58,6 +58,8 @@ pub struct Options { pub line_length: Option, /// `--indent`, if given; otherwise the config file decides. pub indent: Option, + /// `--style`, if given; otherwise the config file decides. + pub style: Option<&'static str>, /// `--lines`: format only the constructs meeting these lines. `None` is a /// whole-file run. pub lines: Option, @@ -98,8 +100,13 @@ impl Options { } /// Formatter settings for one file: CLI flag > config file > default. + /// + /// The style is resolved first and supplies the starting indent and line + /// length; an explicit `indent`/`line-length`, from the flag or the file, + /// is then written over the preset's, whichever rung named the style. pub fn config_with(&self, file: &FileConfig) -> Config { - let mut config = Config::default(); + let name = self.style.or(file.format_style); + let mut config = name.and_then(Config::named).unwrap_or_default(); if let Some(n) = self.line_length.or(file.line_length) { config.max_width = n; } @@ -196,6 +203,12 @@ OPTIONS: filelist, and neither reads nor writes the cache --line-length maximum line length (default 100) --indent indent width in spaces (default 2) + --style layout preset: lucisv (the default), google, + lowrisc, ansi, microsoft or nxp. It sets the indent + and line length too; --indent/--line-length (or the + config file's keys) still win over the preset's. + `auto` lays each file out in the preset it is + already closest to, at the default indent/width --no-config ignore lucisv.toml / .lucisv.toml files -h, --help show this help -V, --version show version @@ -275,7 +288,7 @@ FILELISTS: CACHE: A file whose exact content lucisv has already verified is formatted — under - the same line-length, indent and lucisv version — is skipped on the next run + the same line-length, indent, style and lucisv version — is skipped on the next run and reported as `N files from cache`. Only that \"already formatted\" verdict is ever cached: a file that would be reformatted, or that failed, is re-checked every run. The cache is one text file under `.lucisv_cache/`; @@ -288,10 +301,12 @@ CONFIGURATION: optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file, read by lucisv-server only — the CLI reads a filelist only when `-f` names - one, so `lucisv rtl/` always means the directory it was given). One table - is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names, - `--select`/`--ignore` semantics) and `waivers` (an array of waiver file - paths, resolved against the config file's own directory). A command line + one, so `lucisv rtl/` always means the directory it was given). The + `[format]` table takes `style` (a preset name, as `--style`) and + `uvm-utils-indent` (true/false). The `[lint]` table takes `select` and + `ignore` (arrays of rule names, `--select`/`--ignore` semantics) and + `waivers` (an array of waiver file paths, resolved against the config + file's own directory). A command line flag overrides the file's corresponding key; the other keys still apply — `--waiver-file` is the exception, and adds to `waivers` rather than replacing it. @@ -335,6 +350,7 @@ fn parse_from(args: impl Iterator) -> Result { exclude: Vec::new(), line_length: None, indent: None, + style: None, lines: None, output_format: OutputFormat::Text, fix: false, @@ -400,6 +416,10 @@ fn parse_from(args: impl Iterator) -> Result { let v = args.next().ok_or("--indent requires a value")?; opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?); } + "--style" => { + let v = args.next().ok_or("--style requires a value")?; + opts.style = Some(config::parse_style(&v)?); + } "--lines" => { let v = args.next().ok_or("--lines requires a value")?; line_specs.push(v); @@ -526,6 +546,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> { #[cfg(test)] mod tests { use super::*; + use vlog_formatter::style; fn parse(args: &[&str]) -> Result { parse_from(args.iter().map(|s| s.to_string())) @@ -568,6 +589,52 @@ mod tests { assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width); } + #[test] + fn a_style_sets_the_starting_values_and_explicit_ones_win() { + let none = FileConfig::default(); + let opts = parse(&["--style", "microsoft", "rtl"]).unwrap(); + let config = opts.config_with(&none); + assert_eq!(config.style, style::MICROSOFT); + assert_eq!((config.indent_width, config.max_width), (4, 120)); + // The file's explicit keys beat the flag's preset... + let file = FileConfig { indent: Some(3), ..Default::default() }; + assert_eq!(opts.config_with(&file).indent_width, 3); + assert_eq!(opts.config_with(&file).max_width, 120); + // ...and the flag beats the file's style. + let google = FileConfig { format_style: Some("google"), ..Default::default() }; + assert_eq!(opts.config_with(&google).style, style::MICROSOFT); + let opts = parse(&["--indent", "2", "rtl"]).unwrap(); + let config = opts.config_with(&google); + assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2)); + // No style anywhere is exactly the old default. + let config = parse(&["rtl"]).unwrap().config_with(&none); + assert_eq!(config.style, style::LUCISV); + } + + #[test] + fn an_unknown_style_names_the_styles() { + let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") }; + assert!(message.contains("unknown style `allman`"), "{message}"); + assert!( + message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"), + "{message}" + ); + assert!(parse(&["--style"]).is_err()); + } + + /// `lucisv_core` keeps its own copy of the names so it can reject a bad + /// `[format] style` without depending on the formatter; this is the test + /// that keeps the copy honest. + #[test] + fn the_core_style_names_are_the_formatter_presets() { + let mut names: Vec<&str> = style::names().collect(); + names.push("auto"); + assert_eq!(names, config::STYLE_NAMES); + for name in config::STYLE_NAMES { + assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name)); + } + } + #[test] fn config_excludes_are_appended_to_cli_excludes() { let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() }; diff --git a/crates/lucisv/src/main.rs b/crates/lucisv/src/main.rs index 5547e45..9818e97 100644 --- a/crates/lucisv/src/main.rs +++ b/crates/lucisv/src/main.rs @@ -338,6 +338,7 @@ fn entry_for(content: u64, config: &Config) -> Entry { line_length: config.max_width, indent: config.indent_width, uvm_utils_indent: config.uvm_utils_indent, + style: config.style_name(), } } diff --git a/crates/lucisv/tests/cli.rs b/crates/lucisv/tests/cli.rs index f59cb7a..45be690 100644 --- a/crates/lucisv/tests/cli.rs +++ b/crates/lucisv/tests/cli.rs @@ -1268,7 +1268,8 @@ impl TempDir { } /// One hand-written cache line, for the tests that forge entries. The -/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`. +/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`, +/// and the style is always the default, `lucisv`. fn cache_line( path: &str, content: &str, @@ -1278,7 +1279,7 @@ fn cache_line( version: &str, ) -> String { let hash = lucisv_core::cache::content_hash(content.as_bytes()); - format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n") + format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n") } #[test] diff --git a/crates/lucisv/tests/style_cli.rs b/crates/lucisv/tests/style_cli.rs new file mode 100644 index 0000000..ad9bd02 --- /dev/null +++ b/crates/lucisv/tests/style_cli.rs @@ -0,0 +1,171 @@ +//! `--style` and `[format] style` through the real `lucisv` binary: the +//! flag, the config key, their precedence over each other and under the +//! explicit `indent`/`line-length`, the error for a name that is not a +//! preset, and the format cache keyed on the style. + +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const LUCISV: &str = env!("CARGO_BIN_EXE_lucisv"); + +/// One `if`/`else` whose layout every switch of `ansi` changes. +const SOURCE: &str = + "module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n"; +const LUCISV_OUT: &str = "\ +module m; + initial + if (a) begin + x = 1; + end else begin + x = 2; + end +endmodule +"; +const ANSI_OUT: &str = "\ +module m; + initial + if (a) + begin + x = 1; + end + else + begin + x = 2; + end +endmodule +"; + +/// A throwaway directory under the system temp dir, removed on drop. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(tag: &str) -> TempDir { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("lucisv-style-{}-{tag}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + // Discovery stops at a `.git`, so no config above the temp dir leaks in. + std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git"); + TempDir { path } + } + + fn write(&self, rel: &str, contents: &str) -> String { + let path = self.path.join(rel); + std::fs::write(&path, contents).expect("write fixture"); + path.to_string_lossy().into_owned() + } + + fn read(&self, rel: &str) -> String { + std::fs::read_to_string(self.path.join(rel)).expect("read fixture") + } + + fn cache(&self) -> String { + self.path.join("cache").to_string_lossy().into_owned() + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +fn run(args: &[&str]) -> Output { + Command::new(LUCISV).args(args).output().expect("run lucisv") +} + +fn code(out: &Output) -> i32 { + out.status.code().expect("exit code") +} + +fn stdout(out: &Output) -> String { + String::from_utf8_lossy(&out.stdout).into_owned() +} + +fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() +} + +#[test] +fn the_flag_picks_a_preset() { + let dir = TempDir::new("flag"); + let path = dir.write("a.sv", SOURCE); + let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]); + assert_eq!(code(&out), 0, "{}", stderr(&out)); + assert_eq!(stdout(&out), ANSI_OUT); + let out = run(&["--no-cache", "--stdout", &path]); + assert_eq!(stdout(&out), LUCISV_OUT, "no style is the default layout"); + let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]); + assert_eq!(stdout(&out), LUCISV_OUT, "and `lucisv` is that same layout"); +} + +#[test] +fn the_config_key_picks_a_preset_and_the_flag_beats_it() { + let dir = TempDir::new("toml"); + dir.write("lucisv.toml", "[format]\nstyle = \"ansi\"\n"); + let path = dir.write("a.sv", SOURCE); + assert_eq!(code(&run(&["--no-cache", &path])), 0); + assert_eq!(dir.read("a.sv"), ANSI_OUT); + let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]); + assert_eq!(stdout(&out), LUCISV_OUT, "CLI flag > config file"); + let out = run(&["--no-cache", "--stdout", "--no-config", &path]); + assert_eq!(stdout(&out), LUCISV_OUT, "--no-config drops the style with the file"); +} + +#[test] +fn explicit_indent_wins_over_the_presets() { + let dir = TempDir::new("indent"); + let path = dir.write("a.sv", SOURCE); + let out = run(&["--no-cache", "--stdout", "--style", "ansi", "--indent", "2", &path]); + assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " ")); + // The file's `indent` beats the flag's preset too: an explicit value is + // explicit wherever it was written. + dir.write("lucisv.toml", "indent = 2\n"); + let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]); + assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " ")); +} + +#[test] +fn an_unknown_style_is_an_error_that_lists_the_presets() { + let dir = TempDir::new("unknown"); + let path = dir.write("a.sv", SOURCE); + let out = run(&["--no-cache", "--style", "allman", &path]); + assert_eq!(code(&out), 2); + assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out)); + assert!( + stderr(&out).contains("lucisv, google, lowrisc, ansi, microsoft, nxp"), + "{}", + stderr(&out) + ); + // The same in `lucisv.toml`, naming the file and the line; nothing written. + let config = dir.write("lucisv.toml", "indent = 2\n[format]\nstyle = \"allman\"\n"); + let out = run(&["--no-cache", &path]); + assert_eq!(code(&out), 2); + assert!(stderr(&out).contains(&format!("{config}:3:")), "{}", stderr(&out)); + assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out)); + assert_eq!(dir.read("a.sv"), SOURCE); +} + +#[test] +fn changing_the_style_invalidates_the_cache_entry() { + let dir = TempDir::new("cache"); + let path = dir.write("a.sv", LUCISV_OUT); + let cache = dir.cache(); + let out = run(&["--check", &path, "--cache-dir", &cache]); + assert_eq!(code(&out), 0, "{}", stderr(&out)); + let out = run(&["--check", &path, "--cache-dir", &cache]); + assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out)); + // The same bytes are not clean under another style, cache or no cache. + let out = run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache]); + assert_eq!(code(&out), 1, "the style is part of the key: {}", stderr(&out)); + // And a clean verdict under `ansi` is not one under the default. + dir.write("a.sv", ANSI_OUT); + assert_eq!(code(&run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache])), 0); + let out = run(&["--check", &path, "--cache-dir", &cache]); + assert_eq!(code(&out), 1, "{}", stderr(&out)); +} diff --git a/crates/lucisv_core/src/cache.rs b/crates/lucisv_core/src/cache.rs index 37fffb5..163fd0d 100644 --- a/crates/lucisv_core/src/cache.rs +++ b/crates/lucisv_core/src/cache.rs @@ -12,6 +12,8 @@ use std::collections::HashMap; use std::fmt::Write as _; use std::path::{Path, PathBuf}; +use crate::config::STYLE_NAMES; + /// The default cache directory, resolved against the current directory. pub const DEFAULT_DIR: &str = ".lucisv_cache"; @@ -35,6 +37,10 @@ pub struct Entry { /// The `[format] uvm-utils-indent` that verdict was reached under: it /// changes the output of a UVM class, so it is part of the key. pub uvm_utils_indent: bool, + /// The `[format] style` that verdict was reached under, one of + /// [`crate::config::STYLE_NAMES`]: every preset lays files out + /// differently, so it is part of the key. + pub style: &'static str, } /// The cache for one run: loaded once at startup, written once at exit. @@ -107,8 +113,8 @@ impl Cache { let entry = &self.entries[path]; let _ = writeln!( text, - "{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}", - entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent + "{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}", + entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style ); } text @@ -154,28 +160,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, fn parse(text: &str) -> Option> { let mut entries = HashMap::new(); for line in text.lines() { - let fields: Vec<&str> = line.splitn(6, '\t').collect(); + let fields: Vec<&str> = line.splitn(7, '\t').collect(); match fields[..] { - [content, line_length, indent, uvm, version, path] => { + [content, line_length, indent, uvm, style, version, path] => { let (content, line_length, indent) = prefix(content, line_length, indent)?; let uvm_utils_indent = uvm.parse().ok()?; if path.is_empty() { return None; } - if version == VERSION { + // A style this build does not know is another build's + // entry: stale, not corrupt. + let known = STYLE_NAMES.into_iter().find(|n| *n == style); + if let (Some(style), true) = (known, version == VERSION) { entries.insert( path.to_string(), - Entry { content, line_length, indent, uvm_utils_indent }, + Entry { content, line_length, indent, uvm_utils_indent, style }, ); } } - // A store written before `uvm-utils-indent` joined the key: a - // well-formed line of that older shape says nothing about the - // option, so it is dropped individually, exactly like another - // version's entry. (The version field alone already makes such - // a store miss; the codec stays self-describing anyway.) - // Anything else on five fields is corruption and discards the - // file like any other malformed line. + // A store written before `style` joined the key: a well-formed + // line of that older shape says nothing about the style, so it is + // dropped individually, exactly like another version's entry. + [content, line_length, indent, uvm, _version, path] => { + prefix(content, line_length, indent)?; + uvm.parse::().ok()?; + if path.is_empty() { + return None; + } + } + // And the same for the shape before `uvm-utils-indent` joined it. + // (The version field alone already makes such a store miss; the + // codec stays self-describing anyway.) Anything else on five or + // six fields is corruption and discards the file like any other + // malformed line. [content, line_length, indent, _version, path] => { prefix(content, line_length, indent)?; if path.is_empty() { @@ -228,7 +245,7 @@ mod tests { } fn entry(content: u64) -> Entry { - Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false } + Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" } } #[test] @@ -262,6 +279,7 @@ mod tests { assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) })); assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) })); assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) })); + assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) })); assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead))); } @@ -276,7 +294,7 @@ mod tests { let mut cache = Cache::load(&dir.path); cache.record(&file, on); cache.store(); - assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text()); + assert!(dir.cache_text().contains("\t100\t2\ttrue\tlucisv\t"), "{}", dir.cache_text()); let reloaded = Cache::load(&dir.path); assert!(reloaded.is_clean(&file, on)); @@ -291,7 +309,7 @@ mod tests { let old = dir.file("old.sv"); let mine = dir.file("mine.sv"); let text = format!( - "{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", + "{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n", 1, old.to_string_lossy(), 2, @@ -308,6 +326,37 @@ mod tests { assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text()); } + #[test] + fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() { + // The six-field shape lucisv wrote before `style` joined the key, and + // a style this build does not know: both stale, never corruption. + let dir = TempDir::new("nostyle"); + let old = dir.file("old.sv"); + let other = dir.file("other.sv"); + let mine = dir.file("mine.sv"); + let text = format!( + "{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\ + {:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\ + {:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n", + 1, + old.to_string_lossy(), + 2, + other.to_string_lossy(), + 3, + mine.to_string_lossy() + ); + std::fs::write(dir.path.join(FILE), text).unwrap(); + + let cache = Cache::load(&dir.path); + assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted"); + assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) })); + assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) })); + assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key"); + cache.store(); + assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text()); + assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text()); + } + #[test] fn the_file_is_sorted_and_carries_the_version() { let dir = TempDir::new("format"); @@ -325,7 +374,7 @@ mod tests { assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}"); assert_eq!( lines[0], - format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()), + format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()), "{text}" ); } @@ -350,13 +399,19 @@ mod tests { "0000000000000001\t100\t2\t0.2.0\t\n", "0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n", "0000000000000001\t100\t2\tfalse\t0.2.0\t\n", + "0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n", + "0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n", + "0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n", "\0\0\0\n", ] { let dir = TempDir::new("corrupt"); let file = dir.file("a.sv"); // A good line first: a bad one anywhere discards all of them. - let good = - format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy()); + let good = format!( + "{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n", + 1, + file.to_string_lossy() + ); std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap(); let cache = Cache::load(&dir.path); assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}"); @@ -369,8 +424,8 @@ mod tests { let old = dir.file("old.sv"); let mine = dir.file("mine.sv"); let text = format!( - "{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\ - {:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", + "{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\ + {:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n", 1, old.to_string_lossy(), 2, diff --git a/crates/lucisv_core/src/config.rs b/crates/lucisv_core/src/config.rs index 679e6d8..55258c7 100644 --- a/crates/lucisv_core/src/config.rs +++ b/crates/lucisv_core/src/config.rs @@ -11,7 +11,14 @@ use std::collections::HashMap; use std::path::{Component, Path, PathBuf}; /// Config file names, in the order a directory is probed. -const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"]; +pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"]; + +/// The names `[format] style` accepts: the formatter's presets, in its +/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so +/// does not depend on the formatter; the two lists are held equal by a test +/// in the `lucisv` crate, which sees both. +pub const STYLE_NAMES: [&str; 7] = + ["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"]; /// The settings one config file carries. Every key is optional; an unset /// key leaves the CLI flag (or the built-in default) in charge. @@ -34,6 +41,9 @@ pub struct FileConfig { /// statements written between `` `uvm_*_utils_begin `` and /// `` `uvm_*_utils_end ``. Off for the same reason. pub format_uvm_utils_indent: Option, + /// `[format] style`: the named layout preset, one of [`STYLE_NAMES`]. + /// Checked here, so a misspelt name fails the run like a misspelt key. + pub format_style: Option<&'static str>, /// `[lint] select`: run exactly these rules, replacing the default set. /// The names are **not** validated here — this crate does not know the /// rule registry; `lucisv check` validates them the moment it resolves the @@ -176,23 +186,30 @@ fn parse_entry( } _ => Err(format!( "unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \ - uvm-utils-indent under `[format]`; \ + style, uvm-utils-indent under `[format]`; \ select, ignore, waivers under `[lint]`; and a rule's own options \ under `[lint.]`)" )), } } -/// One key of the `[format]` table: a boolean that defaults to off, because -/// it changes how already-clean files are laid out and a project has to opt -/// in before anything of its moves. +/// One key of the `[format]` table: the named `style`, or a boolean that +/// defaults to off, because it changes how already-clean files are laid out +/// and a project has to opt in before anything of its moves. fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> { + if key == "style" { + if config.format_style.is_some() { + return Err(format!("duplicate key `{key}`")); + } + config.format_style = Some(parse_style(&parse_string(value)?)?); + return Ok(()); + } let slot = match key { "uvm-utils-indent" => &mut config.format_uvm_utils_indent, _ => { return Err(format!( "unknown key `{key}` under `[format]` \ - (the only key is uvm-utils-indent)" + (known keys: style, uvm-utils-indent)" )) } }; @@ -203,6 +220,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result Ok(()) } +/// One of [`STYLE_NAMES`], exactly as spelt there. +pub fn parse_style(name: &str) -> Result<&'static str, String> { + STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| { + format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", ")) + }) +} + /// `true` or `false`, and nothing else — a misspelling is a typo the user /// wants to hear about, not a silent `false`. fn parse_bool(key: &str, value: &str) -> Result { @@ -614,6 +638,32 @@ exclude = [ \"build\", \"*_gen.sv\", ] assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..])); } + /// `[format] style` names a preset; anything else is an error that lists + /// the presets, the way an unknown key lists the keys. + #[test] + fn the_format_table_carries_a_style() { + assert_eq!(ok("[format]\nstyle = \"google\"").format_style, Some("google")); + assert_eq!(ok("[format]\nstyle = \"lucisv\" # the default").format_style, Some("lucisv")); + assert_eq!(ok("indent = 4").format_style, None); + for name in STYLE_NAMES { + assert_eq!(ok(&format!("[format]\nstyle = \"{name}\"")).format_style, Some(name)); + } + let unknown = err("[format]\nstyle = \"gogle\""); + assert!(unknown.contains("unknown style `gogle`"), "{unknown}"); + assert!( + unknown.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"), + "{unknown}" + ); + assert!(err("[format]\nstyle = \"Google\"").contains("unknown style `Google`")); + assert!(err("[format]\nstyle = google").contains("expected a quoted string")); + assert!( + err("[format]\nstyle = \"ansi\"\nstyle = \"nxp\"").contains("duplicate key `style`") + ); + // Like `uvm-utils-indent`, it lives in `[format]` and nowhere else. + assert!(err("style = \"google\"").contains("unknown key `style`")); + assert!(err("[lint]\nstyle = \"google\"").contains("unknown key `style` under `[lint]`")); + } + /// Everything about the table's shape, the way the `[lint]` table's is /// pinned: an unknown key is named, a non-boolean value is refused, and a /// repeated key is an error rather than a last-one-wins. diff --git a/crates/lucisv_mcp/src/tools/diagnostics.rs b/crates/lucisv_mcp/src/tools/diagnostics.rs index 960c528..0801e16 100644 --- a/crates/lucisv_mcp/src/tools/diagnostics.rs +++ b/crates/lucisv_mcp/src/tools/diagnostics.rs @@ -161,7 +161,9 @@ impl Runs { } waivers.absorb(file); } - let format = vlog_formatter::Config::default(); + // The width and indent the file would be formatted with, its style's + // included, so the linter and the formatter cannot disagree. + let format = super::format::formatter_config(config); Ok(Run { rules, options, diff --git a/crates/lucisv_mcp/src/tools/format.rs b/crates/lucisv_mcp/src/tools/format.rs index 0243654..d32a109 100644 --- a/crates/lucisv_mcp/src/tools/format.rs +++ b/crates/lucisv_mcp/src/tools/format.rs @@ -119,9 +119,10 @@ fn fixed_and_formatted( } /// The formatter settings a file's `lucisv.toml` resolves to — the CLI's -/// `Options::config_with` with no command-line flags. -fn formatter_config(file: &FileConfig) -> Config { - let mut config = Config::default(); +/// `Options::config_with` with no command-line flags: the style first, then +/// the explicit keys over the preset's indent and width. +pub(super) fn formatter_config(file: &FileConfig) -> Config { + let mut config = file.format_style.and_then(Config::named).unwrap_or_default(); if let Some(width) = file.line_length { config.max_width = width; } @@ -195,3 +196,25 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool { .iter() .any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize)) } + +#[cfg(test)] +mod tests { + use super::*; + use vlog_formatter::style; + + /// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no + /// flags does: the style first, the explicit keys over its numbers. + #[test] + fn the_style_comes_first_and_explicit_keys_win() { + let none = formatter_config(&FileConfig::default()); + assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100)); + let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() }; + let config = formatter_config(&ansi); + assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80)); + let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi }; + let config = formatter_config(&narrowed); + assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90)); + let auto = FileConfig { format_style: Some("auto"), ..Default::default() }; + assert!(formatter_config(&auto).auto_style); + } +} diff --git a/crates/lucisv_server/src/auto_style.rs b/crates/lucisv_server/src/auto_style.rs new file mode 100644 index 0000000..4f13e10 --- /dev/null +++ b/crates/lucisv_server/src/auto_style.rs @@ -0,0 +1,404 @@ +//! The preset `style = "auto"` last settled on, per document. +//! +//! Under `auto`, every formatting request needs a concrete preset, and +//! finding one means formatting the whole buffer once per preset. That is +//! fine for a whole-document format, which formats the whole buffer anyway, +//! but not for an on-type `;` or a selection, which would pay it on every +//! keystroke — and on a buffer that does not parse (exactly when on-type +//! runs), no preset can be found at all. +//! +//! So a whole-document format remembers the preset it used, and the range, +//! selection and on-type requests reuse it. Without a memory they resolve +//! once from the buffer — when it parses — and remember that. Without a +//! memory and without a parse they lay out in the default preset's layout, +//! as the formatter itself does. The memory is a small most-recent list. +//! +//! A remembered preset is only right while the buffer is still the text it +//! was resolved from, edited by hand. So it is **forgotten** whenever that +//! may no longer be true: the document is opened, closed, renamed or deleted; +//! it is formatted or laid out under a named style; and — for every document +//! — whenever the settings change or a `lucisv.toml` change is seen. +//! Forgetting costs one search on the next request; remembering wrongly would +//! lay the file out in a preset it no longer uses. +//! +//! A change that replaces the **whole** buffer (a reload from disk, an +//! external formatter, or every change of a full-sync client) marks the +//! entry *replaced* rather than dropping it: the next request resolves +//! afresh from the new text, and only if that text does not parse — so there +//! is nothing to resolve from — does it fall back to the old preset, which is +//! still a better guess than the default layout. A full-sync client's every +//! keystroke is such a change, and a half-typed buffer is exactly when +//! on-type runs; dropping the entry there would lose the file's preset at the +//! moment the memory exists for. +//! See `docs/features/format-styles/README.md`. + +use std::collections::VecDeque; + +use lsp_server::Notification; +use lsp_types::notification::{ + DidChangeWatchedFiles, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, + DidRenameFiles, Notification as _, +}; +use lsp_types::{ + DeleteFilesParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, + DidOpenTextDocumentParams, RenameFilesParams, TextDocumentContentChangeEvent, TextEdit, Uri, +}; +use vlog_formatter::{format_auto, style, Config, Style}; + +use crate::format; +use crate::state::Document; + +/// How many documents' presets are remembered. +const CAPACITY: usize = 64; + +/// The presets of the most recently formatted documents, newest last. +#[derive(Default)] +pub struct AutoStyles { + recent: VecDeque, +} + +/// One remembered document. +struct Entry { + uri: Uri, + preset: Style, + /// A change replaced the whole buffer since `preset` was resolved, so it + /// is only a fallback: resolve again when the buffer parses. + replaced: bool, +} + +impl AutoStyles { + /// Format a whole buffer. Under `auto` this resolves afresh and + /// remembers the preset it used; under a named style it is + /// [`format::formatting`]. + pub fn format_document( + &mut self, + uri: &Uri, + doc: &Document, + config: &Config, + ) -> Result, String> { + if !config.auto_style { + // Formatted under a named style, the buffer may now be in it. + self.forget(uri); + return format::formatting(doc, config); + } + let (formatted, preset) = format_auto(&doc.text, config).map_err(|e| e.to_string())?; + self.remember(uri, preset); + Ok(format::whole_document_edit(doc, formatted)) + } + + /// `config` made concrete for a range, selection or on-type request on + /// `doc`: unchanged under a named style; under `auto`, the remembered + /// preset, else the one the buffer resolves to (then remembered), else — + /// the buffer does not parse — the default preset's layout. + pub fn concrete(&mut self, uri: &Uri, doc: &Document, config: Config) -> Config { + if !config.auto_style { + self.forget(uri); + return config; + } + let held = self.recall(uri); + let preset = match held { + Some((preset, false)) => preset, + // Nothing trustworthy held: resolve from the buffer when it + // parses; otherwise the old preset if there is one, else the + // default layout. A fallback is never stored as fresh. + _ => match format_auto(&doc.text, &config) { + Ok((_, preset)) => { + self.remember(uri, preset); + preset + } + Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset), + }, + }; + Config { style: preset, auto_style: false, ..config } + } + + /// Whether nothing is remembered yet. + #[cfg(test)] + pub fn is_empty(&self) -> bool { + self.recent.is_empty() + } + + /// Forget what a notification may have made stale: the document a + /// `didOpen`/`didClose` names, the old and new names of a renamed file, + /// a deleted file, and every document when a watched-file event names a + /// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored. + pub fn notice(&mut self, notification: &Notification) { + let params = || notification.params.clone(); + match notification.method.as_str() { + DidOpenTextDocument::METHOD => { + if let Ok(p) = serde_json::from_value::(params()) { + self.forget(&p.text_document.uri); + } + } + DidCloseTextDocument::METHOD => { + if let Ok(p) = serde_json::from_value::(params()) { + self.forget(&p.text_document.uri); + } + } + DidRenameFiles::METHOD => { + if let Ok(p) = serde_json::from_value::(params()) { + self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri])); + } + } + DidDeleteFiles::METHOD => { + if let Ok(p) = serde_json::from_value::(params()) { + self.forget_named(p.files.iter().map(|f| &f.uri)); + } + } + DidChangeWatchedFiles::METHOD => { + if let Ok(p) = serde_json::from_value::(params()) { + if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) { + self.forget_all(); + } + } + } + _ => {} + } + } + + /// Mark `uri`'s entry replaced when a `didChange` replaced its whole + /// text: a change with no range (full sync), or one that starts at the + /// top and leaves nothing of the old text after it — `result` is exactly + /// its text. + pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) { + let rangeless = changes.iter().any(|c| c.range.is_none()); + let from_the_top = changes.last().is_some_and(|c| { + c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result + }); + if rangeless || from_the_top { + if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) { + entry.replaced = true; + } + } + } + + /// Forget every document: the settings, or a `lucisv.toml`, changed. + pub fn forget_all(&mut self) { + self.recent.clear(); + } + + fn forget(&mut self, uri: &Uri) { + self.recent.retain(|e| e.uri != *uri); + } + + fn forget_named<'a>(&mut self, uris: impl Iterator) { + for uri in uris { + self.recent.retain(|e| e.uri.as_str() != uri); + } + } + + /// The remembered preset, and whether it has been marked replaced. + fn recall(&self, uri: &Uri) -> Option<(Style, bool)> { + self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced)) + } + + fn remember(&mut self, uri: &Uri, preset: Style) { + self.forget(uri); + if self.recent.len() == CAPACITY { + self.recent.pop_front(); + } + self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false }); + } +} + +/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`. +fn names_a_config(uri: &str) -> bool { + let name = uri.rsplit('/').next().unwrap_or(uri); + lucisv_core::config::NAMES.contains(&name) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Workspace; + use std::str::FromStr; + + /// A google-formatted module: one port per line at a 4-space list indent. + const GOOGLE: &str = "\ +module m ( + input logic a, + output logic b +); + sub u_sub ( + .a(a), + .b(b) + ); +endmodule +"; + + fn open(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 auto() -> Config { + Config::named("auto").expect("auto") + } + + #[test] + fn a_whole_document_format_remembers_the_preset_it_used() { + let (ws, uri) = open(GOOGLE); + let mut styles = AutoStyles::default(); + let doc = ws.document(&uri).expect("open"); + assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted"); + assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false))); + let concrete = styles.concrete(&uri, doc, auto()); + assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false)); + } + + #[test] + fn a_named_style_is_left_alone_and_nothing_is_remembered() { + let (ws, uri) = open(GOOGLE); + let mut styles = AutoStyles::default(); + let doc = ws.document(&uri).expect("open"); + let ansi = Config::styled(style::ANSI); + assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI); + assert!(styles.format_document(&uri, doc, &ansi).is_ok()); + assert_eq!(styles.recall(&uri), None); + } + + /// The memory is what lets a half-typed buffer keep its file's preset: + /// without it, a buffer that does not parse gets the default's layout. + #[test] + fn a_buffer_that_does_not_parse_uses_the_remembered_preset() { + let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule"); + let (ws, uri) = open(&broken); + let doc = ws.document(&uri).expect("open"); + let mut styles = AutoStyles::default(); + assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse"); + assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered"); + styles.remember(&uri, style::GOOGLE); + assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE); + } + + #[test] + fn without_a_memory_a_buffer_that_parses_resolves_once() { + let (ws, uri) = open(GOOGLE); + let doc = ws.document(&uri).expect("open"); + let mut styles = AutoStyles::default(); + assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE); + assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered"); + } + + #[test] + fn the_memory_is_bounded_and_keeps_the_most_recent() { + let mut styles = AutoStyles::default(); + let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri"); + for n in 0..CAPACITY + 10 { + styles.remember(&uri(n), style::NXP); + } + assert_eq!(styles.recent.len(), CAPACITY); + assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten"); + assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false))); + // Remembering again moves a document to the back and replaces its preset. + styles.remember(&uri(10), style::ANSI); + styles.remember(&uri(10), style::GOOGLE); + assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false))); + assert_eq!(styles.recent.len(), CAPACITY); + } + + fn notification(method: &str, params: serde_json::Value) -> Notification { + Notification { method: method.to_string(), params } + } + + #[test] + fn open_close_rename_and_delete_forget_the_document() { + let mut styles = AutoStyles::default(); + let (a, b) = ( + Uri::from_str("file:///rtl/a.sv").expect("uri"), + Uri::from_str("file:///rtl/b.sv").expect("uri"), + ); + let doc = |uri: &Uri| { + serde_json::json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } }) + }; + for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] { + styles.remember(&a, style::GOOGLE); + styles.notice(¬ification(method, doc(&a))); + assert_eq!(styles.recall(&a), None, "{method}"); + } + styles.remember(&a, style::GOOGLE); + styles.remember(&b, style::NXP); + styles.notice(¬ification( + DidRenameFiles::METHOD, + serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }), + )); + assert!(styles.is_empty(), "both names of a renamed file are forgotten"); + styles.remember(&a, style::GOOGLE); + styles.notice(¬ification( + DidDeleteFiles::METHOD, + serde_json::json!({ "files": [{ "uri": a.as_str() }] }), + )); + assert_eq!(styles.recall(&a), None); + } + + #[test] + fn a_config_file_change_or_a_settings_change_forgets_everything() { + let mut styles = AutoStyles::default(); + let a = Uri::from_str("file:///rtl/a.sv").expect("uri"); + let watched = |name: &str| { + notification( + DidChangeWatchedFiles::METHOD, + serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }), + ) + }; + styles.remember(&a, style::GOOGLE); + styles.notice(&watched("other.sv")); + assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets"); + for name in ["lucisv.toml", ".lucisv.toml"] { + styles.remember(&a, style::GOOGLE); + styles.notice(&watched(name)); + assert!(styles.is_empty(), "{name}"); + } + styles.remember(&a, style::GOOGLE); + styles.forget_all(); + assert!(styles.is_empty()); + } + + /// A whole-buffer change makes the entry a fallback: the next request + /// resolves from the new text if it parses, and keeps the old preset + /// only if it does not. A partial edit leaves the entry alone. + #[test] + fn a_whole_buffer_replacement_resolves_again_when_it_can() { + let lucisv = + "module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n"; + let (ws, uri) = open(lucisv); + let doc = ws.document(&uri).expect("open"); + let mut styles = AutoStyles::default(); + styles.remember(&uri, style::GOOGLE); + let edit: TextDocumentContentChangeEvent = + serde_json::from_value(serde_json::json!({ + "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } }, + "text": " " })).expect("change"); + styles.changed(&uri, &[edit], lucisv); + assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit"); + let whole: TextDocumentContentChangeEvent = + serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change"); + styles.changed(&uri, std::slice::from_ref(&whole), lucisv); + assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true))); + assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh"); + assert_eq!(styles.recall(&uri), Some((style::LUCISV, false))); + // A full range from the top counts as a whole replacement too. + let ranged: TextDocumentContentChangeEvent = + serde_json::from_value(serde_json::json!({ + "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } }, + "text": lucisv })).expect("change"); + styles.changed(&uri, &[ranged], lucisv); + assert_eq!(styles.recall(&uri), Some((style::LUCISV, true))); + } + + #[test] + fn a_named_style_request_forgets_the_document() { + let (ws, uri) = open(GOOGLE); + let doc = ws.document(&uri).expect("open"); + let mut styles = AutoStyles::default(); + styles.remember(&uri, style::GOOGLE); + styles.concrete(&uri, doc, Config::styled(style::LUCISV)); + assert_eq!(styles.recall(&uri), None, "a range under a named style"); + styles.remember(&uri, style::GOOGLE); + let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV)); + assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style"); + } +} diff --git a/crates/lucisv_server/src/format.rs b/crates/lucisv_server/src/format.rs index dd10fa3..ea65635 100644 --- a/crates/lucisv_server/src/format.rs +++ b/crates/lucisv_server/src/format.rs @@ -15,7 +15,7 @@ use std::path::Path; use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit}; use lucisv_core::config::{Discovery, FileConfig}; -use vlog_formatter::{format_selection, format_source, Config, LineRanges}; +use vlog_formatter::{format_selection, format_source, style, Config, LineRanges, Style}; use crate::settings::ClientSettings; use crate::state::Document; @@ -55,6 +55,16 @@ pub struct Settings { /// Each rung applies only where every rung above it is silent, so a project /// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did /// before either existed. +/// +/// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2 +/// and 4 first, and supplies the indent and width the other keys then +/// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3: +/// `tabSize` is sent whether or not anyone chose it, and the editor's own +/// default of 4 silently undoing `google`'s 2 is not what choosing a style +/// asked for. With no style chosen — or `lucisv`, which is what VS Code sends +/// when nobody touched the drop-down, and which means exactly "what lucisv +/// always did", or `auto`, which chooses a layout but no size — rung 3 +/// behaves exactly as it always has. pub fn settings_for( doc: &Document, client: &ClientSettings, @@ -86,10 +96,16 @@ pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) /// 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())?; + Ok(whole_document_edit(doc, formatted)) +} + +/// The one edit that turns `doc` into `formatted`, or none when they are +/// already the same text. +pub fn whole_document_edit(doc: &Document, formatted: String) -> Option { if formatted == doc.text { - return Ok(None); + return None; } - Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })) + Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }) } /// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request. @@ -184,7 +200,16 @@ fn lines_of(range: Range) -> (u32, u32) { /// lightbulb the editor requests on every cursor move would be noise. pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize { let (file, _problem) = discover(path); - file.indent.or(client.indent).unwrap_or(Config::default().indent_width) + file.indent + .or(client.indent) + .unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent) +} + +/// The preset a project or a user picked for this buffer, `lucisv.toml` +/// first; `None` when neither did, or when the pick is `auto`, which names +/// no preset and so no indent. +fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option