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 <[email protected]>
This commit is contained in:
1 parent
7408face90
commit
80017a59f2
42 files changed
+3962
-206
No files matched your search
@@ -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
|
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||||
(see `README.md`) are the only frozen contract.
|
(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 = "<name>"` in
|
||||||
|
`lucisv.toml`, `--style <name>` 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
|
## 0.65.4 — 2026-11-19
|
||||||
|
|
||||||
### `` `ifdef `` blocks fold, and pin in sticky scroll
|
### `` `ifdef `` blocks fold, and pin in sticky scroll
|
||||||
|
|||||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lucisv"
|
name = "lucisv"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lucisv_core",
|
"lucisv_core",
|
||||||
"rayon",
|
"rayon",
|
||||||
@@ -108,11 +108,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lucisv_core"
|
name = "lucisv_core"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lucisv_mcp"
|
name = "lucisv_mcp"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lucisv_core",
|
"lucisv_core",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -126,7 +126,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lucisv_server"
|
name = "lucisv_server"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lsp-server",
|
"lsp-server",
|
||||||
"lsp-types",
|
"lsp-types",
|
||||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vlog_formatter"
|
name = "vlog_formatter"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"vlog_parser",
|
"vlog_parser",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vlog_linter"
|
name = "vlog_linter"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"lucisv_core",
|
"lucisv_core",
|
||||||
"vlog_formatter",
|
"vlog_formatter",
|
||||||
@@ -279,11 +279,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vlog_parser"
|
name = "vlog_parser"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vlog_refactor"
|
name = "vlog_refactor"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"vlog_formatter",
|
"vlog_formatter",
|
||||||
"vlog_parser",
|
"vlog_parser",
|
||||||
@@ -292,7 +292,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vlog_semantic"
|
name = "vlog_semantic"
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"vlog_parser",
|
"vlog_parser",
|
||||||
]
|
]
|
||||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.65.4"
|
version = "0.65.5"
|
||||||
authors = ["Guoliang Chen"]
|
authors = ["Guoliang Chen"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|||||||
@@ -144,6 +144,9 @@ indent = 2 # 1..8, same as --indent
|
|||||||
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
||||||
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
|
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]
|
[lint]
|
||||||
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
||||||
ignore = ["module-filename"] # removed after selection
|
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`
|
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
|
||||||
with a file that sets only `line-length` uses both). `exclude` is the
|
with a file that sets only `line-length` uses both). `exclude` is the
|
||||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
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`),
|
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
|
||||||
off by default, indents the `` `uvm_field_* `` macros written between
|
off by default, indents the `` `uvm_field_* `` macros written between
|
||||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
|
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
|
||||||
formatting choice lucisv leaves to the project, because it changes bytes
|
it is a formatting choice lucisv leaves to the project, because it changes
|
||||||
in existing UVM code (21 of the 860 corpus files).
|
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
|
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.<rule>]`, multi-line
|
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||||
@@ -512,7 +524,8 @@ Key ideas carried over from ruff/prettier:
|
|||||||
|
|
||||||
Defaults follow Verible: **2-space indent**, **100-column lines** (both
|
Defaults follow Verible: **2-space indent**, **100-column lines** (both
|
||||||
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
|
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
|
- One port / parameter / connection per line once a header doesn't fit
|
||||||
- Cuddled `begin`/`end` (`end else begin`)
|
- 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
|
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
|
||||||
through verbatim
|
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
|
### Alignment is inferred, not imposed
|
||||||
|
|
||||||
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
|
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
|
||||||
|
|||||||
@@ -7328,7 +7328,8 @@ subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
|||||||
database.
|
database.
|
||||||
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
|
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
|
||||||
sticky-scroll ("floating") bars.
|
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
|
break, what is grouped, how ports align. If inferring that is too
|
||||||
ambiguous, a setting with a drop-down of named styles instead (ANSI,
|
ambiguous, a setting with a drop-down of named styles instead (ANSI,
|
||||||
Google, Microsoft, NXP — educated guesses), with the rules easy to
|
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,
|
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
|
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`.
|
(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.
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
//! Hand-rolled command line parsing for the `lucisv` binary.
|
//! Hand-rolled command line parsing for the `lucisv` binary.
|
||||||
|
|
||||||
use lucisv_core::cache;
|
use lucisv_core::cache;
|
||||||
use lucisv_core::config::FileConfig;
|
use lucisv_core::config::{self, FileConfig};
|
||||||
use vlog_formatter::{Config, LineRanges};
|
use vlog_formatter::{Config, LineRanges};
|
||||||
|
|
||||||
/// Which tool this invocation runs.
|
/// Which tool this invocation runs.
|
||||||
@@ -58,6 +58,8 @@ pub struct Options {
|
|||||||
pub line_length: Option<usize>,
|
pub line_length: Option<usize>,
|
||||||
/// `--indent`, if given; otherwise the config file decides.
|
/// `--indent`, if given; otherwise the config file decides.
|
||||||
pub indent: Option<usize>,
|
pub indent: Option<usize>,
|
||||||
|
/// `--style`, if given; otherwise the config file decides.
|
||||||
|
pub style: Option<&'static str>,
|
||||||
/// `--lines`: format only the constructs meeting these lines. `None` is a
|
/// `--lines`: format only the constructs meeting these lines. `None` is a
|
||||||
/// whole-file run.
|
/// whole-file run.
|
||||||
pub lines: Option<LineRanges>,
|
pub lines: Option<LineRanges>,
|
||||||
@@ -98,8 +100,13 @@ impl Options {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Formatter settings for one file: CLI flag > config file > default.
|
/// 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 {
|
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) {
|
if let Some(n) = self.line_length.or(file.line_length) {
|
||||||
config.max_width = n;
|
config.max_width = n;
|
||||||
}
|
}
|
||||||
@@ -196,6 +203,12 @@ OPTIONS:
|
|||||||
filelist, and neither reads nor writes the cache
|
filelist, and neither reads nor writes the cache
|
||||||
--line-length <N> maximum line length (default 100)
|
--line-length <N> maximum line length (default 100)
|
||||||
--indent <N> indent width in spaces (default 2)
|
--indent <N> indent width in spaces (default 2)
|
||||||
|
--style <NAME> 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
|
--no-config ignore lucisv.toml / .lucisv.toml files
|
||||||
-h, --help show this help
|
-h, --help show this help
|
||||||
-V, --version show version
|
-V, --version show version
|
||||||
@@ -275,7 +288,7 @@ FILELISTS:
|
|||||||
|
|
||||||
CACHE:
|
CACHE:
|
||||||
A file whose exact content lucisv has already verified is formatted — under
|
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\"
|
and reported as `N files from cache`. Only that \"already formatted\"
|
||||||
verdict is ever cached: a file that would be reformatted, or that failed,
|
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/`;
|
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
|
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
||||||
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
|
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
|
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
|
one, so `lucisv rtl/` always means the directory it was given). The
|
||||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
`[format]` table takes `style` (a preset name, as `--style`) and
|
||||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
`uvm-utils-indent` (true/false). The `[lint]` table takes `select` and
|
||||||
paths, resolved against the config file's own directory). A command line
|
`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 —
|
flag overrides the file's corresponding key; the other keys still apply —
|
||||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||||
replacing it.
|
replacing it.
|
||||||
@@ -335,6 +350,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
|||||||
exclude: Vec::new(),
|
exclude: Vec::new(),
|
||||||
line_length: None,
|
line_length: None,
|
||||||
indent: None,
|
indent: None,
|
||||||
|
style: None,
|
||||||
lines: None,
|
lines: None,
|
||||||
output_format: OutputFormat::Text,
|
output_format: OutputFormat::Text,
|
||||||
fix: false,
|
fix: false,
|
||||||
@@ -400,6 +416,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
|||||||
let v = args.next().ok_or("--indent requires a value")?;
|
let v = args.next().ok_or("--indent requires a value")?;
|
||||||
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
|
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" => {
|
"--lines" => {
|
||||||
let v = args.next().ok_or("--lines requires a value")?;
|
let v = args.next().ok_or("--lines requires a value")?;
|
||||||
line_specs.push(v);
|
line_specs.push(v);
|
||||||
@@ -526,6 +546,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use vlog_formatter::style;
|
||||||
|
|
||||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||||
parse_from(args.iter().map(|s| s.to_string()))
|
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);
|
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]
|
#[test]
|
||||||
fn config_excludes_are_appended_to_cli_excludes() {
|
fn config_excludes_are_appended_to_cli_excludes() {
|
||||||
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
|
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
|
||||||
|
|||||||
@@ -338,6 +338,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
|
|||||||
line_length: config.max_width,
|
line_length: config.max_width,
|
||||||
indent: config.indent_width,
|
indent: config.indent_width,
|
||||||
uvm_utils_indent: config.uvm_utils_indent,
|
uvm_utils_indent: config.uvm_utils_indent,
|
||||||
|
style: config.style_name(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1268,7 +1268,8 @@ impl TempDir {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// One hand-written cache line, for the tests that forge entries. The
|
/// 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(
|
fn cache_line(
|
||||||
path: &str,
|
path: &str,
|
||||||
content: &str,
|
content: &str,
|
||||||
@@ -1278,7 +1279,7 @@ fn cache_line(
|
|||||||
version: &str,
|
version: &str,
|
||||||
) -> String {
|
) -> String {
|
||||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
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]
|
#[test]
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ use std::collections::HashMap;
|
|||||||
use std::fmt::Write as _;
|
use std::fmt::Write as _;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::config::STYLE_NAMES;
|
||||||
|
|
||||||
/// The default cache directory, resolved against the current directory.
|
/// The default cache directory, resolved against the current directory.
|
||||||
pub const DEFAULT_DIR: &str = ".lucisv_cache";
|
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
|
/// 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.
|
/// changes the output of a UVM class, so it is part of the key.
|
||||||
pub uvm_utils_indent: bool,
|
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.
|
/// 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 entry = &self.entries[path];
|
||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
text,
|
text,
|
||||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
text
|
text
|
||||||
@@ -154,28 +160,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
|
|||||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||||
let mut entries = HashMap::new();
|
let mut entries = HashMap::new();
|
||||||
for line in text.lines() {
|
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[..] {
|
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 (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||||
let uvm_utils_indent = uvm.parse().ok()?;
|
let uvm_utils_indent = uvm.parse().ok()?;
|
||||||
if path.is_empty() {
|
if path.is_empty() {
|
||||||
return None;
|
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(
|
entries.insert(
|
||||||
path.to_string(),
|
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
|
// A store written before `style` joined the key: a well-formed
|
||||||
// well-formed line of that older shape says nothing about the
|
// line of that older shape says nothing about the style, so it is
|
||||||
// option, so it is dropped individually, exactly like another
|
// dropped individually, exactly like another version's entry.
|
||||||
// version's entry. (The version field alone already makes such
|
[content, line_length, indent, uvm, _version, path] => {
|
||||||
// a store miss; the codec stays self-describing anyway.)
|
prefix(content, line_length, indent)?;
|
||||||
// Anything else on five fields is corruption and discards the
|
uvm.parse::<bool>().ok()?;
|
||||||
// file like any other malformed line.
|
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] => {
|
[content, line_length, indent, _version, path] => {
|
||||||
prefix(content, line_length, indent)?;
|
prefix(content, line_length, indent)?;
|
||||||
if path.is_empty() {
|
if path.is_empty() {
|
||||||
@@ -228,7 +245,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn entry(content: u64) -> Entry {
|
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]
|
#[test]
|
||||||
@@ -262,6 +279,7 @@ mod tests {
|
|||||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
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 { indent: 4, ..entry(0xdead) }));
|
||||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..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)));
|
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,7 +294,7 @@ mod tests {
|
|||||||
let mut cache = Cache::load(&dir.path);
|
let mut cache = Cache::load(&dir.path);
|
||||||
cache.record(&file, on);
|
cache.record(&file, on);
|
||||||
cache.store();
|
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);
|
let reloaded = Cache::load(&dir.path);
|
||||||
assert!(reloaded.is_clean(&file, on));
|
assert!(reloaded.is_clean(&file, on));
|
||||||
@@ -291,7 +309,7 @@ mod tests {
|
|||||||
let old = dir.file("old.sv");
|
let old = dir.file("old.sv");
|
||||||
let mine = dir.file("mine.sv");
|
let mine = dir.file("mine.sv");
|
||||||
let text = format!(
|
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,
|
1,
|
||||||
old.to_string_lossy(),
|
old.to_string_lossy(),
|
||||||
2,
|
2,
|
||||||
@@ -308,6 +326,37 @@ mod tests {
|
|||||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
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]
|
#[test]
|
||||||
fn the_file_is_sorted_and_carries_the_version() {
|
fn the_file_is_sorted_and_carries_the_version() {
|
||||||
let dir = TempDir::new("format");
|
let dir = TempDir::new("format");
|
||||||
@@ -325,7 +374,7 @@ mod tests {
|
|||||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
lines[0],
|
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}"
|
"{text}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -350,13 +399,19 @@ mod tests {
|
|||||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\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",
|
"\0\0\0\n",
|
||||||
] {
|
] {
|
||||||
let dir = TempDir::new("corrupt");
|
let dir = TempDir::new("corrupt");
|
||||||
let file = dir.file("a.sv");
|
let file = dir.file("a.sv");
|
||||||
// A good line first: a bad one anywhere discards all of them.
|
// A good line first: a bad one anywhere discards all of them.
|
||||||
let good =
|
let good = format!(
|
||||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
"{: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();
|
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||||
let cache = Cache::load(&dir.path);
|
let cache = Cache::load(&dir.path);
|
||||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
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 old = dir.file("old.sv");
|
||||||
let mine = dir.file("mine.sv");
|
let mine = dir.file("mine.sv");
|
||||||
let text = format!(
|
let text = format!(
|
||||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
|
||||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||||
1,
|
1,
|
||||||
old.to_string_lossy(),
|
old.to_string_lossy(),
|
||||||
2,
|
2,
|
||||||
|
|||||||
@@ -11,7 +11,14 @@ use std::collections::HashMap;
|
|||||||
use std::path::{Component, Path, PathBuf};
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
|
||||||
/// Config file names, in the order a directory is probed.
|
/// 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
|
/// The settings one config file carries. Every key is optional; an unset
|
||||||
/// key leaves the CLI flag (or the built-in default) in charge.
|
/// 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
|
/// statements written between `` `uvm_*_utils_begin `` and
|
||||||
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
||||||
pub format_uvm_utils_indent: Option<bool>,
|
pub format_uvm_utils_indent: Option<bool>,
|
||||||
|
/// `[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.
|
/// `[lint] select`: run exactly these rules, replacing the default set.
|
||||||
/// The names are **not** validated here — this crate does not know the
|
/// The names are **not** validated here — this crate does not know the
|
||||||
/// rule registry; `lucisv check` validates them the moment it resolves the
|
/// rule registry; `lucisv check` validates them the moment it resolves the
|
||||||
@@ -176,23 +186,30 @@ fn parse_entry(
|
|||||||
}
|
}
|
||||||
_ => Err(format!(
|
_ => Err(format!(
|
||||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
"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 \
|
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||||
under `[lint.<rule-name>]`)"
|
under `[lint.<rule-name>]`)"
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One key of the `[format]` table: a boolean that defaults to off, because
|
/// One key of the `[format]` table: the named `style`, or a boolean that
|
||||||
/// it changes how already-clean files are laid out and a project has to opt
|
/// defaults to off, because it changes how already-clean files are laid out
|
||||||
/// in before anything of its moves.
|
/// 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> {
|
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 {
|
let slot = match key {
|
||||||
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
||||||
_ => {
|
_ => {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"unknown key `{key}` under `[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(())
|
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
|
/// `true` or `false`, and nothing else — a misspelling is a typo the user
|
||||||
/// wants to hear about, not a silent `false`.
|
/// wants to hear about, not a silent `false`.
|
||||||
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
||||||
@@ -614,6 +638,32 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
|||||||
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
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
|
/// 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
|
/// 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.
|
/// repeated key is an error rather than a last-one-wins.
|
||||||
|
|||||||
@@ -161,7 +161,9 @@ impl Runs {
|
|||||||
}
|
}
|
||||||
waivers.absorb(file);
|
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 {
|
Ok(Run {
|
||||||
rules,
|
rules,
|
||||||
options,
|
options,
|
||||||
|
|||||||
@@ -119,9 +119,10 @@ fn fixed_and_formatted(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||||
/// `Options::config_with` with no command-line flags.
|
/// `Options::config_with` with no command-line flags: the style first, then
|
||||||
fn formatter_config(file: &FileConfig) -> Config {
|
/// the explicit keys over the preset's indent and width.
|
||||||
let mut config = Config::default();
|
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 {
|
if let Some(width) = file.line_length {
|
||||||
config.max_width = width;
|
config.max_width = width;
|
||||||
}
|
}
|
||||||
@@ -195,3 +196,25 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
.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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Entry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Option<TextEdit>, 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::<DidOpenTextDocumentParams>(params()) {
|
||||||
|
self.forget(&p.text_document.uri);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DidCloseTextDocument::METHOD => {
|
||||||
|
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
|
||||||
|
self.forget(&p.text_document.uri);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DidRenameFiles::METHOD => {
|
||||||
|
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(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::<DeleteFilesParams>(params()) {
|
||||||
|
self.forget_named(p.files.iter().map(|f| &f.uri));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DidChangeWatchedFiles::METHOD => {
|
||||||
|
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(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<Item = &'a String>) {
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||||
use lucisv_core::config::{Discovery, FileConfig};
|
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::settings::ClientSettings;
|
||||||
use crate::state::Document;
|
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
|
/// 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
|
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
|
||||||
/// before either existed.
|
/// 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(
|
pub fn settings_for(
|
||||||
doc: &Document,
|
doc: &Document,
|
||||||
client: &ClientSettings,
|
client: &ClientSettings,
|
||||||
@@ -86,10 +96,16 @@ pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings)
|
|||||||
/// invent an edit from it.
|
/// invent an edit from it.
|
||||||
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
|
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
|
||||||
let formatted = format_source(&doc.text, config).map_err(|e| e.to_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<TextEdit> {
|
||||||
if formatted == doc.text {
|
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.
|
/// `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.
|
/// lightbulb the editor requests on every cursor move would be noise.
|
||||||
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
|
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
|
||||||
let (file, _problem) = discover(path);
|
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<Style> {
|
||||||
|
file.format_style.or(client.style).and_then(style::preset)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The config file governing `path`, by the CLI's own discovery rule, or the
|
/// The config file governing `path`, by the CLI's own discovery rule, or the
|
||||||
@@ -213,8 +238,12 @@ fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
|
|||||||
/// protocol carries no line-length option — so before it existed there was no
|
/// protocol carries no line-length option — so before it existed there was no
|
||||||
/// way to set a width from an editor without a `lucisv.toml`.
|
/// way to set a width from an editor without a `lucisv.toml`.
|
||||||
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
|
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
|
||||||
let mut config = Config::default();
|
let named = file.format_style.or(client.style).and_then(Config::named);
|
||||||
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
// `auto` picks a layout and no size, so it leaves the editor's rung alone
|
||||||
|
// exactly as "no style" and `lucisv` do.
|
||||||
|
let editor_rung = chosen_style(file, client).is_none_or(|s| s == style::LUCISV);
|
||||||
|
let mut config = named.unwrap_or_default();
|
||||||
|
if editor_rung && options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
||||||
config.indent_width = options.tab_size as usize;
|
config.indent_width = options.tab_size as usize;
|
||||||
}
|
}
|
||||||
if let Some(indent) = client.indent {
|
if let Some(indent) = client.indent {
|
||||||
@@ -554,6 +583,68 @@ mod tests {
|
|||||||
assert!(settings.config.uvm_utils_indent);
|
assert!(settings.config.uvm_utils_indent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The style climbs rungs 1, 2 and 4, supplies the starting indent and
|
||||||
|
/// width, and — once someone actually chose one — outranks `tabSize`.
|
||||||
|
#[test]
|
||||||
|
fn a_style_sets_the_starting_values_and_outranks_tab_size() {
|
||||||
|
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
|
||||||
|
let (ws, uri) = document("module m;\nendmodule\n");
|
||||||
|
let config = |client: &ClientSettings, tab| {
|
||||||
|
settings_with(&ws, &uri, client, &options(tab, true)).config
|
||||||
|
};
|
||||||
|
// No style, and `lucisv` — what VS Code sends by default — are the
|
||||||
|
// same thing: `tabSize` is the indent, exactly as before styles.
|
||||||
|
assert_eq!((config(&none(), 4).indent_width, config(&none(), 4).style), (4, style::LUCISV));
|
||||||
|
assert_eq!(config(&styled("lucisv"), 4).indent_width, 4);
|
||||||
|
// A chosen style outranks `tabSize`...
|
||||||
|
let google = config(&styled("google"), 4);
|
||||||
|
assert_eq!((google.style, google.indent_width, google.max_width), (style::GOOGLE, 2, 100));
|
||||||
|
// ...but not an explicit `lucisv.indent`, and the width stays the style's.
|
||||||
|
let both =
|
||||||
|
ClientSettings { style: Some("microsoft"), indent: Some(2), ..Default::default() };
|
||||||
|
let microsoft = config(&both, 8);
|
||||||
|
assert_eq!((microsoft.indent_width, microsoft.max_width), (2, 120));
|
||||||
|
// A misspelt editor value never got this far: it is dropped on arrival.
|
||||||
|
assert_eq!(
|
||||||
|
crate::settings::from_payload(&serde_json::json!({
|
||||||
|
"lucisv": { "format": { "style": "gogle" } }
|
||||||
|
}))
|
||||||
|
.style,
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lucisv_toml_names_the_style_over_the_editor() {
|
||||||
|
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
|
||||||
|
let nxp = Tree::new("[format]\nstyle = \"nxp\"\n");
|
||||||
|
let (ws, uri) = nxp.document("module m;\nendmodule\n");
|
||||||
|
let settings = settings_with(&ws, &uri, &styled("microsoft"), &options(4, true));
|
||||||
|
assert_eq!(settings.problem, None);
|
||||||
|
let c = settings.config;
|
||||||
|
assert_eq!((c.style, c.indent_width, c.max_width), (style::NXP, 2, 80));
|
||||||
|
// The project's `lucisv` beats the editor's `google`, and with it the
|
||||||
|
// editor's `tabSize` is back in play.
|
||||||
|
let plain = Tree::new("[format]\nstyle = \"lucisv\"\n");
|
||||||
|
let (ws, uri) = plain.document("module m;\nendmodule\n");
|
||||||
|
let c = settings_with(&ws, &uri, &styled("google"), &options(4, true)).config;
|
||||||
|
assert_eq!((c.style, c.indent_width), (style::LUCISV, 4));
|
||||||
|
// The lint-fix width follows the style too, below the explicit keys.
|
||||||
|
let ansi = Tree::new("[format]\nstyle = \"ansi\"\n");
|
||||||
|
let path = ansi.path.join("m.sv");
|
||||||
|
assert_eq!(indent_width(Some(&path), &none()), 4);
|
||||||
|
assert_eq!(indent_width(None, &styled("microsoft")), 4);
|
||||||
|
let pushed = ClientSettings { indent: Some(3), ..styled("microsoft") };
|
||||||
|
assert_eq!(indent_width(Some(&path), &pushed), 3);
|
||||||
|
// A bad name in `lucisv.toml` is the config problem every bad key is.
|
||||||
|
let bad = Tree::new("[format]\nstyle = \"gogle\"\n");
|
||||||
|
let (ws, uri) = bad.document("module m;\nendmodule\n");
|
||||||
|
let settings = settings_with(&ws, &uri, &none(), &options(2, true));
|
||||||
|
let problem = settings.problem.expect("a problem");
|
||||||
|
assert!(problem.contains("unknown style `gogle`"), "{problem}");
|
||||||
|
assert_eq!(settings.config.style, style::LUCISV);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn each_key_climbs_the_ladder_independently() {
|
fn each_key_climbs_the_ladder_independently() {
|
||||||
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
|
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
|
||||||
//! `docs/features/lucisv-server/README.md`.
|
//! `docs/features/lucisv-server/README.md`.
|
||||||
|
|
||||||
|
mod auto_style;
|
||||||
mod candidates;
|
mod candidates;
|
||||||
mod code_action;
|
mod code_action;
|
||||||
mod completion;
|
mod completion;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ impl Server {
|
|||||||
let uri = params.text_document.uri;
|
let uri = params.text_document.uri;
|
||||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||||
let result = format::formatting(doc, &settings.config);
|
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
|
||||||
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
|
// A broken `lucisv.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
|
// 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
|
// config file is an editor the user turns off. The buffer is formatted
|
||||||
@@ -45,7 +45,8 @@ impl Server {
|
|||||||
let uri = params.text_document.uri;
|
let uri = params.text_document.uri;
|
||||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||||
let result = format::range_formatting(doc, &settings.config, params.range);
|
let config = self.auto_styles.concrete(&uri, doc, settings.config);
|
||||||
|
let result = format::range_formatting(doc, &config, params.range);
|
||||||
self.warn_about_config(&uri, settings.problem);
|
self.warn_about_config(&uri, settings.problem);
|
||||||
self.edits(result)
|
self.edits(result)
|
||||||
}
|
}
|
||||||
@@ -65,7 +66,8 @@ impl Server {
|
|||||||
let uri = params.text_document.uri;
|
let uri = params.text_document.uri;
|
||||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||||
let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges);
|
let config = self.auto_styles.concrete(&uri, doc, settings.config);
|
||||||
|
let result = format::ranges_formatting(doc, &config, ¶ms.ranges);
|
||||||
self.warn_about_config(&uri, settings.problem);
|
self.warn_about_config(&uri, settings.problem);
|
||||||
self.edits(result)
|
self.edits(result)
|
||||||
}
|
}
|
||||||
@@ -98,9 +100,16 @@ impl Server {
|
|||||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||||
};
|
};
|
||||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||||
|
// Only a `;` lays anything out; a newline needs no preset, so it must
|
||||||
|
// not pay for finding one.
|
||||||
|
let config = match params.ch.as_str() {
|
||||||
|
on_type::SEMICOLON => {
|
||||||
|
self.auto_styles.concrete(&at.text_document.uri, doc, settings.config)
|
||||||
|
}
|
||||||
|
_ => settings.config,
|
||||||
|
};
|
||||||
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
||||||
let edits =
|
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &config, auto_end);
|
||||||
on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config, auto_end);
|
|
||||||
to_value(edits)
|
to_value(edits)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +142,7 @@ impl Server {
|
|||||||
// so the ladder runs without its `tabSize` rung.
|
// so the ladder runs without its `tabSize` rung.
|
||||||
let settings =
|
let settings =
|
||||||
format::settings_without_editor_options(doc, self.workspace.client_settings());
|
format::settings_without_editor_options(doc, self.workspace.client_settings());
|
||||||
let result = format::formatting(doc, &settings.config);
|
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
|
||||||
self.warn_about_config(&uri, settings.problem);
|
self.warn_about_config(&uri, settings.problem);
|
||||||
self.edits(result)
|
self.edits(result)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -135,6 +135,11 @@ pub struct Server {
|
|||||||
/// for a document whenever its text changes, so the warning is said once
|
/// for a document whenever its text changes, so the warning is said once
|
||||||
/// per file change rather than once per format-on-save.
|
/// per file change rather than once per format-on-save.
|
||||||
config_warnings: HashSet<Uri>,
|
config_warnings: HashSet<Uri>,
|
||||||
|
/// The preset `style = "auto"` last settled on for each recently
|
||||||
|
/// formatted document, so range, selection and on-type requests neither
|
||||||
|
/// search every preset again nor lose the file's preset while the buffer
|
||||||
|
/// does not parse (`auto_style.rs`).
|
||||||
|
auto_styles: crate::auto_style::AutoStyles,
|
||||||
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
||||||
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
||||||
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ impl Server {
|
|||||||
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
|
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
|
||||||
// flush, so the flush below already publishes everything.
|
// flush, so the flush below already publishes everything.
|
||||||
let released = self.forget_port_entry(&method, ¬ification);
|
let released = self.forget_port_entry(&method, ¬ification);
|
||||||
|
self.auto_styles.notice(¬ification);
|
||||||
// Everything but a `didChange` needs the buffers' analyses current —
|
// Everything but a `didChange` needs the buffers' analyses current —
|
||||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||||
// request gets happens here, with the one exception that *is* the
|
// request gets happens here, with the one exception that *is* the
|
||||||
@@ -125,6 +126,7 @@ impl Server {
|
|||||||
.unwrap_or("");
|
.unwrap_or("");
|
||||||
sync::apply_changes_at(base, &p.content_changes)
|
sync::apply_changes_at(base, &p.content_changes)
|
||||||
};
|
};
|
||||||
|
self.auto_styles.changed(&uri, &p.content_changes, &text);
|
||||||
// Where the edit ended is where someone is typing: the
|
// Where the edit ended is where someone is typing: the
|
||||||
// flush looks it up for a connection entry to hold back.
|
// flush looks it up for a connection entry to hold back.
|
||||||
let now = std::time::Instant::now();
|
let now = std::time::Instant::now();
|
||||||
@@ -259,6 +261,7 @@ impl Server {
|
|||||||
/// about what a setting *does* any more than `settings::from_payload` and
|
/// about what a setting *does* any more than `settings::from_payload` and
|
||||||
/// `from_section` can disagree about what it says.
|
/// `from_section` can disagree about what it says.
|
||||||
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
||||||
|
self.auto_styles.forget_all();
|
||||||
let watched = self.workspace.filelist_path();
|
let watched = self.workspace.filelist_path();
|
||||||
let linted = self.lint_selection();
|
let linted = self.lint_selection();
|
||||||
// A `lucisv.lint.options` entry the registry refused is dropped, not
|
// A `lucisv.lint.options` entry the registry refused is dropped, not
|
||||||
|
|||||||
@@ -146,6 +146,7 @@ impl Server {
|
|||||||
connection,
|
connection,
|
||||||
workspace: Workspace::default(),
|
workspace: Workspace::default(),
|
||||||
config_warnings: HashSet::new(),
|
config_warnings: HashSet::new(),
|
||||||
|
auto_styles: Default::default(),
|
||||||
lint_config_problems: std::cell::RefCell::default(),
|
lint_config_problems: std::cell::RefCell::default(),
|
||||||
said_lint_names: Vec::new(),
|
said_lint_names: Vec::new(),
|
||||||
abilities,
|
abilities,
|
||||||
|
|||||||
@@ -649,3 +649,188 @@ fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save()
|
|||||||
assert_eq!(third, serde_json::json!([]));
|
assert_eq!(third, serde_json::json!([]));
|
||||||
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// `lucisv.format.style = "auto"`: the preset the server remembers
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// A google-formatted buffer: one connection per line at a 4-space indent.
|
||||||
|
const GOOGLE_BUFFER: &str = "\
|
||||||
|
module m (
|
||||||
|
input logic a,
|
||||||
|
output logic b
|
||||||
|
);
|
||||||
|
sub u_sub (
|
||||||
|
.a(a),
|
||||||
|
.b(b)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
fn push_auto(session: &mut Session) {
|
||||||
|
session.notify(
|
||||||
|
DidChangeConfiguration::METHOD,
|
||||||
|
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "auto" } } } }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_whole(session: &mut Session, uri: &Uri) -> Value {
|
||||||
|
session.result(
|
||||||
|
Formatting::METHOD,
|
||||||
|
serde_json::json!({
|
||||||
|
"textDocument": { "uri": uri },
|
||||||
|
"options": { "tabSize": 2, "insertSpaces": true },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a whole-document format under `auto`, a range in the same buffer
|
||||||
|
/// keeps the buffer's preset even once a half-typed line elsewhere stops it
|
||||||
|
/// from parsing — which a fresh search could not do.
|
||||||
|
#[test]
|
||||||
|
fn auto_ranges_keep_the_remembered_preset_while_the_buffer_does_not_parse() {
|
||||||
|
let tree = Tree::new("autorange");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||||
|
assert_eq!(format_whole(&mut session, &uri), serde_json::json!([]), "already google");
|
||||||
|
|
||||||
|
let edited = GOOGLE_BUFFER
|
||||||
|
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
|
||||||
|
change(&mut session, &uri, 2, serde_json::json!([{ "text": edited }]));
|
||||||
|
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||||
|
let text = ranged[0]["newText"].as_str().expect("an edit");
|
||||||
|
assert!(text.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{text}");
|
||||||
|
// And the `;` path agrees with it, byte for byte.
|
||||||
|
let typed = on_type(&mut session, &uri, ";", 8, 27);
|
||||||
|
assert_eq!(typed, ranged);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With no memory and a buffer that does not parse there is nothing to
|
||||||
|
/// resolve from, so the default preset's layout answers — the documented
|
||||||
|
/// fallback — and nothing is remembered.
|
||||||
|
#[test]
|
||||||
|
fn auto_without_a_memory_and_without_a_parse_uses_the_default_layout() {
|
||||||
|
let tree = Tree::new("autofallback");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let text = GOOGLE_BUFFER
|
||||||
|
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), &text);
|
||||||
|
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||||
|
assert_eq!(ranged, serde_json::json!([]), "the default layout already holds that line");
|
||||||
|
assert!(session.server.auto_styles.is_empty(), "a fallback is not remembered");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With no memory and a buffer that parses, the first range request
|
||||||
|
/// resolves the preset once and remembers it for the next.
|
||||||
|
#[test]
|
||||||
|
fn auto_without_a_memory_resolves_from_a_buffer_that_parses() {
|
||||||
|
let tree = Tree::new("autoresolve");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let text = GOOGLE_BUFFER.replace("endmodule", " sub u_two (.a(a), .b(b));\nendmodule");
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), &text);
|
||||||
|
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||||
|
let out = ranged[0]["newText"].as_str().expect("an edit");
|
||||||
|
assert!(out.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{out}");
|
||||||
|
assert!(!session.server.auto_styles.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The google buffer re-laid out lucisv-style, with one unformatted
|
||||||
|
/// instance on line 3 that the two presets lay out differently.
|
||||||
|
const LUCISV_BUFFER: &str = "\
|
||||||
|
module m (input logic a, output logic b);
|
||||||
|
sub u_sub (.a(a), .b(b));
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
fn lucisv_with_instance() -> String {
|
||||||
|
LUCISV_BUFFER.replace("endmodule", "sub u_two (.a(a), .b(b));\nendmodule")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The range answer for line 2 (0-based) of the lucisv buffer. A selection
|
||||||
|
/// keeps the indentation its line was written at, so lucisv's layout of the
|
||||||
|
/// one-line instance is the line itself — no edit — where google's would
|
||||||
|
/// break it into four (`auto_without_a_memory_resolves_from_a_buffer_that_parses`).
|
||||||
|
fn assert_lucisv_layout(session: &mut Session, uri: &Uri) {
|
||||||
|
let ranged = range_result(session, uri, json_range(2, 0, 2, 0));
|
||||||
|
assert_eq!(ranged, serde_json::json!([]), "laid out lucisv-style, not google-style");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// R2-1 (a): the buffer replaced wholesale by text in another preset — a
|
||||||
|
/// reload from disk — is resolved again, not served the old preset.
|
||||||
|
#[test]
|
||||||
|
fn auto_a_replaced_buffer_is_resolved_again() {
|
||||||
|
let tree = Tree::new("autoreplaced");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||||
|
format_whole(&mut session, &uri);
|
||||||
|
assert!(!session.server.auto_styles.is_empty(), "google remembered");
|
||||||
|
change(&mut session, &uri, 2, serde_json::json!([{ "text": lucisv_with_instance() }]));
|
||||||
|
assert_lucisv_layout(&mut session, &uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// R2-1 (b): auto → a whole-document format under a named style → auto.
|
||||||
|
#[test]
|
||||||
|
fn auto_after_a_named_style_format_does_not_reuse_the_old_preset() {
|
||||||
|
let tree = Tree::new("autonamed");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||||
|
format_whole(&mut session, &uri);
|
||||||
|
session.notify(
|
||||||
|
DidChangeConfiguration::METHOD,
|
||||||
|
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "lucisv" } } } }),
|
||||||
|
);
|
||||||
|
assert!(session.server.auto_styles.is_empty(), "a settings change forgets everything");
|
||||||
|
format_whole(&mut session, &uri);
|
||||||
|
push_auto(&mut session);
|
||||||
|
// An incremental edit, so only the settings change and the named format
|
||||||
|
// can be what made the memory forget.
|
||||||
|
let text = lucisv_with_instance();
|
||||||
|
change(
|
||||||
|
&mut session,
|
||||||
|
&uri,
|
||||||
|
2,
|
||||||
|
serde_json::json!([{ "range": { "start": { "line": 0, "character": 0 },
|
||||||
|
"end": { "line": 9, "character": 0 } },
|
||||||
|
"text": text }]),
|
||||||
|
);
|
||||||
|
assert_lucisv_layout(&mut session, &uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// R2-1 (c): close, then reopen the same URI with other content.
|
||||||
|
#[test]
|
||||||
|
fn auto_a_reopened_document_starts_with_no_memory() {
|
||||||
|
let tree = Tree::new("autoreopen");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let path = tree.path.join("m.sv");
|
||||||
|
let uri = session.open(&path, GOOGLE_BUFFER);
|
||||||
|
format_whole(&mut session, &uri);
|
||||||
|
session.notify(
|
||||||
|
DidCloseTextDocument::METHOD,
|
||||||
|
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||||
|
);
|
||||||
|
assert!(session.server.auto_styles.is_empty(), "closing forgets");
|
||||||
|
let uri = session.open(&path, &lucisv_with_instance());
|
||||||
|
assert_lucisv_layout(&mut session, &uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// R2-1 (d): a renamed file's old name is forgotten with it.
|
||||||
|
#[test]
|
||||||
|
fn auto_a_rename_forgets_both_names() {
|
||||||
|
let tree = Tree::new("autorename");
|
||||||
|
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||||
|
push_auto(&mut session);
|
||||||
|
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||||
|
format_whole(&mut session, &uri);
|
||||||
|
let new = crate::uri::path_to_uri(&tree.path.join("n.sv")).expect("uri");
|
||||||
|
session.notify(
|
||||||
|
DidRenameFiles::METHOD,
|
||||||
|
serde_json::json!({ "files": [{ "oldUri": uri.as_str(), "newUri": new.as_str() }] }),
|
||||||
|
);
|
||||||
|
assert!(session.server.auto_styles.is_empty());
|
||||||
|
}
|
||||||
@@ -112,6 +112,11 @@ pub struct ClientSettings {
|
|||||||
/// declares — the key changes bytes in files that already format cleanly,
|
/// declares — the key changes bytes in files that already format cleanly,
|
||||||
/// so nothing turns it on for a user who did not ask.
|
/// so nothing turns it on for a user who did not ask.
|
||||||
pub uvm_utils_indent: Option<bool>,
|
pub uvm_utils_indent: Option<bool>,
|
||||||
|
/// `lucisv.format.style`: the named layout preset, one of
|
||||||
|
/// `lucisv_core::config::STYLE_NAMES`. Unset — and any name that is not
|
||||||
|
/// one of them — means "no opinion", so a `lucisv.toml` or the built-in
|
||||||
|
/// default decides.
|
||||||
|
pub style: Option<&'static str>,
|
||||||
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
|
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
|
||||||
/// Unset means on, which is what the VS Code default declares — see
|
/// Unset means on, which is what the VS Code default declares — see
|
||||||
/// `docs/features/inline-templates/README.md`.
|
/// `docs/features/inline-templates/README.md`.
|
||||||
@@ -252,6 +257,7 @@ impl Default for ClientSettings {
|
|||||||
exclude: Vec::new(),
|
exclude: Vec::new(),
|
||||||
filelist: None,
|
filelist: None,
|
||||||
uvm_utils_indent: None,
|
uvm_utils_indent: None,
|
||||||
|
style: None,
|
||||||
inline_templates: None,
|
inline_templates: None,
|
||||||
inline_instantiation: None,
|
inline_instantiation: None,
|
||||||
inline_keywords: None,
|
inline_keywords: None,
|
||||||
@@ -353,6 +359,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
|||||||
exclude: strings(lucisv.get("exclude")),
|
exclude: strings(lucisv.get("exclude")),
|
||||||
filelist: path(lucisv.get("filelist")),
|
filelist: path(lucisv.get("filelist")),
|
||||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||||
|
style: style(lucisv.get("format").and_then(|f| f.get("style"))),
|
||||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||||
inline_keywords: flag(lucisv.get("inlineKeywords")),
|
inline_keywords: flag(lucisv.get("inlineKeywords")),
|
||||||
@@ -581,6 +588,13 @@ fn path(value: Option<&Value>) -> Option<String> {
|
|||||||
(!text.is_empty()).then(|| text.to_string())
|
(!text.is_empty()).then(|| text.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A preset name `lucisv.toml`'s `[format] style` would accept, or nothing.
|
||||||
|
/// VS Code's drop-down cannot send anything else; another editor's
|
||||||
|
/// hand-written misspelling is dropped like every wrong-typed value here.
|
||||||
|
fn style(value: Option<&Value>) -> Option<&'static str> {
|
||||||
|
lucisv_core::config::parse_style(value?.as_str()?).ok()
|
||||||
|
}
|
||||||
|
|
||||||
/// A JSON integer inside `range`, or nothing.
|
/// A JSON integer inside `range`, or nothing.
|
||||||
///
|
///
|
||||||
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
|
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
|
||||||
@@ -828,6 +842,31 @@ mod tests {
|
|||||||
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
|
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The style drop-down offers exactly the names `[format] style` takes,
|
||||||
|
/// one description each, defaulting to the default style; and each one
|
||||||
|
/// arrives here as itself, while a name that is not one is dropped.
|
||||||
|
#[test]
|
||||||
|
fn the_style_drop_down_is_the_style_names() {
|
||||||
|
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("../../editors/vscode/package.json");
|
||||||
|
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||||
|
let manifest: Value = serde_json::from_str(&text).expect("valid json");
|
||||||
|
let style = &manifest["contributes"]["configuration"]["properties"]["lucisv.format.style"];
|
||||||
|
assert_eq!(style["enum"], json!(lucisv_core::config::STYLE_NAMES));
|
||||||
|
let descriptions = style["enumDescriptions"].as_array().expect("descriptions");
|
||||||
|
assert_eq!(descriptions.len(), lucisv_core::config::STYLE_NAMES.len());
|
||||||
|
assert_eq!(style["default"], json!("lucisv"));
|
||||||
|
for name in lucisv_core::config::STYLE_NAMES {
|
||||||
|
let pushed = settings(json!({ "lucisv": { "format": { "style": name } } }));
|
||||||
|
assert_eq!(pushed.style, Some(name));
|
||||||
|
}
|
||||||
|
for junk in [json!("Google"), json!(""), json!(4), json!(null)] {
|
||||||
|
let pushed = settings(json!({ "lucisv": { "format": { "style": junk } } }));
|
||||||
|
assert_eq!(pushed.style, None, "{junk}");
|
||||||
|
}
|
||||||
|
assert_eq!(settings(json!({ "lucisv": {} })).style, None);
|
||||||
|
}
|
||||||
|
|
||||||
/// [`vscode_payload`] above is a hand-written copy of what the extension
|
/// [`vscode_payload`] above is a hand-written copy of what the extension
|
||||||
/// declares, and a copy that drifts proves nothing. The extension's own
|
/// declares, and a copy that drifts proves nothing. The extension's own
|
||||||
/// `package.json` is the thing a user's settings UI reads, so the two
|
/// `package.json` is the thing a user's settings UI reads, so the two
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
//! The `style = "auto"` proof sweep: for every source file under the given
|
||||||
|
//! directories, format it with auto, then ask auto again about the output.
|
||||||
|
//! Counts the files where the second or third format changed a byte (an
|
||||||
|
//! idempotency violation) and where the second or third run *named* a
|
||||||
|
//! different preset, and
|
||||||
|
//! prints which preset auto picked how often.
|
||||||
|
//!
|
||||||
|
//! Run it through the runaway guard, in release:
|
||||||
|
//! `tools/guard.sh -- cargo run --release -p vlog_formatter --example auto_sweep -- <dir>...`
|
||||||
|
//! See docs/features/format-styles/README.md.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use vlog_formatter::{format_source, resolve_style, Config};
|
||||||
|
|
||||||
|
/// What one file came to.
|
||||||
|
enum Outcome {
|
||||||
|
/// Auto could not format it (a parse error, as under every preset).
|
||||||
|
Refused,
|
||||||
|
/// Formatted; the preset picked first and second, and whether the
|
||||||
|
/// second format wrote the same bytes.
|
||||||
|
Formatted { first: &'static str, second: &'static str, stable: bool },
|
||||||
|
/// The formatter panicked.
|
||||||
|
Crashed,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let dirs: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for dir in &dirs {
|
||||||
|
collect(dir, &mut files);
|
||||||
|
}
|
||||||
|
files.sort();
|
||||||
|
let results = Mutex::new(Vec::new());
|
||||||
|
let next = Mutex::new(0usize);
|
||||||
|
let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
|
||||||
|
std::thread::scope(|scope| {
|
||||||
|
for _ in 0..workers {
|
||||||
|
let builder = std::thread::Builder::new().stack_size(vlog_parser::PARSE_STACK_SIZE);
|
||||||
|
let spawned = builder.spawn_scoped(scope, || loop {
|
||||||
|
let i = {
|
||||||
|
let mut n = next.lock().expect("lock");
|
||||||
|
*n += 1;
|
||||||
|
*n - 1
|
||||||
|
};
|
||||||
|
let Some(path) = files.get(i) else { break };
|
||||||
|
let outcome = sweep_one(path);
|
||||||
|
results.lock().expect("lock").push((path.clone(), outcome));
|
||||||
|
});
|
||||||
|
spawned.expect("spawn a worker");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
report(results.into_inner().expect("results"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sweep_one(path: &Path) -> Outcome {
|
||||||
|
let Ok(bytes) = std::fs::read(path) else { return Outcome::Refused };
|
||||||
|
let source = String::from_utf8_lossy(&bytes).into_owned();
|
||||||
|
let run = std::panic::catch_unwind(|| {
|
||||||
|
let auto = Config::named("auto").expect("auto is a style");
|
||||||
|
let Ok(once) = format_source(&source, &auto) else { return Outcome::Refused };
|
||||||
|
let Ok(twice) = format_source(&once, &auto) else {
|
||||||
|
return Outcome::Formatted { first: "", second: "?", stable: false };
|
||||||
|
};
|
||||||
|
let thrice = format_source(&twice, &auto).ok();
|
||||||
|
let first = resolve_style(&source, &auto).style.name;
|
||||||
|
let second = resolve_style(&once, &auto).style.name;
|
||||||
|
let third = resolve_style(&twice, &auto).style.name;
|
||||||
|
let stable = twice == once && thrice.as_ref() == Some(&once);
|
||||||
|
// A third run naming another preset counts as a rename too.
|
||||||
|
let second = if third == second { second } else { third };
|
||||||
|
Outcome::Formatted { first, second, stable }
|
||||||
|
});
|
||||||
|
run.unwrap_or(Outcome::Crashed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report(results: Vec<(PathBuf, Outcome)>) {
|
||||||
|
let (mut refused, mut crashed, mut unstable, mut renamed) = (0, 0, 0, 0);
|
||||||
|
let mut picked: BTreeMap<&str, usize> = BTreeMap::new();
|
||||||
|
for (path, outcome) in &results {
|
||||||
|
match outcome {
|
||||||
|
Outcome::Refused => refused += 1,
|
||||||
|
Outcome::Crashed => {
|
||||||
|
crashed += 1;
|
||||||
|
println!("crash\t{}", path.display());
|
||||||
|
}
|
||||||
|
Outcome::Formatted { first, second, stable } => {
|
||||||
|
*picked.entry(first).or_default() += 1;
|
||||||
|
if !stable {
|
||||||
|
unstable += 1;
|
||||||
|
println!("not-idempotent\t{}", path.display());
|
||||||
|
}
|
||||||
|
if first != second {
|
||||||
|
renamed += 1;
|
||||||
|
println!("renamed\t{first}->{second}\t{}", path.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("files\t{}", results.len());
|
||||||
|
println!("refused (parse errors)\t{refused}");
|
||||||
|
println!("crashes\t{crashed}");
|
||||||
|
println!("not idempotent\t{unstable}");
|
||||||
|
println!("second run named another preset\t{renamed}");
|
||||||
|
for (name, n) in picked {
|
||||||
|
println!("picked {name}\t{n}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every `.v`/`.sv`/`.vh`/`.svh` under `dir`, recursively.
|
||||||
|
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
if path.file_name().is_some_and(|n| n != ".git") {
|
||||||
|
collect(&path, out);
|
||||||
|
}
|
||||||
|
} else if path
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.is_some_and(|e| ["v", "sv", "vh", "svh"].contains(&e))
|
||||||
|
{
|
||||||
|
out.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
//! would disagree.
|
//! would disagree.
|
||||||
|
|
||||||
use crate::doc::{concat, text, Doc};
|
use crate::doc::{concat, text, Doc};
|
||||||
|
use crate::style::Alignment;
|
||||||
|
|
||||||
/// Excess spaces before a column's token that read as "the author aligned
|
/// Excess spaces before a column's token that read as "the author aligned
|
||||||
/// this". Verible's threshold, and the one number this module hard-codes.
|
/// this". Verible's threshold, and the one number this module hard-codes.
|
||||||
@@ -67,7 +68,18 @@ pub struct Align {
|
|||||||
/// `None` means flush-left — today's layout — and is also the answer for
|
/// `None` means flush-left — today's layout — and is also the answer for
|
||||||
/// anything the rule is not sure about: a group of one, a group with nothing
|
/// anything the rule is not sure about: a group of one, a group with nothing
|
||||||
/// to pad, a row whose column token starts its own line.
|
/// to pad, a row whose column token starts its own line.
|
||||||
pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Option<Align> {
|
///
|
||||||
|
/// `mode` is the style's choice: [`Alignment::Infer`] asks the source,
|
||||||
|
/// [`Alignment::Always`] skips that one question and aligns every group the
|
||||||
|
/// rest of the rule allows — a decision made from the AST alone, so the next
|
||||||
|
/// pass makes it again.
|
||||||
|
pub fn plan(
|
||||||
|
src: &str,
|
||||||
|
rows: &[&Row],
|
||||||
|
specs: &[ColSpec],
|
||||||
|
budget: usize,
|
||||||
|
mode: Alignment,
|
||||||
|
) -> Option<Align> {
|
||||||
if rows.len() < 2 {
|
if rows.len() < 2 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -86,7 +98,7 @@ pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Optio
|
|||||||
if (0..cols).all(|k| rows.iter().all(|r| r.widths[k] == rows[0].widths[k])) {
|
if (0..cols).all(|k| rows.iter().all(|r| r.widths[k] == rows[0].widths[k])) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if !wants_alignment(src, rows, specs) {
|
if mode == Alignment::Infer && !wants_alignment(src, rows, specs) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +230,7 @@ mod tests {
|
|||||||
// Five spaces where flush writes one: four excess, the threshold.
|
// Five spaces where flush writes one: four excess, the threshold.
|
||||||
let src = "aa x\nbbbb y\n";
|
let src = "aa x\nbbbb y\n";
|
||||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||||
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE).expect("aligned");
|
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).expect("aligned");
|
||||||
assert_eq!(plan.targets, vec![5]);
|
assert_eq!(plan.targets, vec![5]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,35 +238,35 @@ mod tests {
|
|||||||
fn three_excess_spaces_are_not_a_hint() {
|
fn three_excess_spaces_are_not_a_hint() {
|
||||||
let src = "aa x\nbbbb y\n";
|
let src = "aa x\nbbbb y\n";
|
||||||
let rows = [row(&[2, 1], &[6], 0), row(&[4, 1], &[13], 0)];
|
let rows = [row(&[2, 1], &[6], 0), row(&[4, 1], &[13], 0)];
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn single_spaces_stay_flush() {
|
fn single_spaces_stay_flush() {
|
||||||
let src = "aa x\nbbbb y\n";
|
let src = "aa x\nbbbb y\n";
|
||||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn one_common_column_stays_aligned() {
|
fn one_common_column_stays_aligned() {
|
||||||
let src = "aa x\nbbbb x\n";
|
let src = "aa x\nbbbb x\n";
|
||||||
let rows = [row(&[2, 1], &[5], 0), row(&[4, 1], &[12], 0)];
|
let rows = [row(&[2, 1], &[5], 0), row(&[4, 1], &[12], 0)];
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_some());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn equal_widths_have_nothing_to_align() {
|
fn equal_widths_have_nothing_to_align() {
|
||||||
let src = "aa x\naa y\n";
|
let src = "aa x\naa y\n";
|
||||||
let rows = [row(&[2, 1], &[6], 0), row(&[2, 1], &[14], 0)];
|
let rows = [row(&[2, 1], &[6], 0), row(&[2, 1], &[14], 0)];
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_group_of_one_is_never_aligned() {
|
fn a_group_of_one_is_never_aligned() {
|
||||||
let src = "aa x\n";
|
let src = "aa x\n";
|
||||||
let rows = [row(&[2, 1], &[6], 0)];
|
let rows = [row(&[2, 1], &[6], 0)];
|
||||||
assert!(plan(src, &[&rows[0]], NAME, WIDE).is_none());
|
assert!(plan(src, &[&rows[0]], NAME, WIDE, Alignment::Infer).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -262,8 +274,34 @@ mod tests {
|
|||||||
let src = "aa x\nbbbb y\n";
|
let src = "aa x\nbbbb y\n";
|
||||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||||
// Widest aligned line is 5 + 1 = 6 columns.
|
// Widest aligned line is 5 + 1 = 6 columns.
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6).is_some());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6, Alignment::Infer).is_some());
|
||||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5).is_none());
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5, Alignment::Infer).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn always_aligns_what_the_source_never_padded() {
|
||||||
|
let src = "aa x\nbbbb y\n";
|
||||||
|
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||||
|
let aligned = plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Always);
|
||||||
|
assert_eq!(aligned.expect("aligned").targets, vec![5]);
|
||||||
|
// Even a row whose column token starts its own line: `Always` never
|
||||||
|
// looks at the source at all.
|
||||||
|
let src = "aa\nx\nbbbb y\n";
|
||||||
|
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||||
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Always).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn always_keeps_every_other_refusal() {
|
||||||
|
let src = "aa x\nbbbb y\n";
|
||||||
|
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||||
|
let same = [row(&[2, 1], &[3], 0), row(&[2, 1], &[10], 0)];
|
||||||
|
let always = Alignment::Always;
|
||||||
|
assert!(plan(src, &[&rows[0]], NAME, WIDE, always).is_none(), "a group of one");
|
||||||
|
assert!(plan(src, &[&same[0], &same[1]], NAME, WIDE, always).is_none(), "nothing to pad");
|
||||||
|
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5, always).is_none(), "too wide");
|
||||||
|
let empty = [row(&[0, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||||
|
assert!(plan(src, &[&empty[0], &empty[1]], NAME, WIDE, always).is_none(), "no prefix");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
//! `style = "auto"`: lay a file out in the preset it is already closest to.
|
||||||
|
//!
|
||||||
|
//! Rather than guess each layout switch from clues in the text, auto formats
|
||||||
|
//! the file once per preset — every preset at the config's own indent and
|
||||||
|
//! width, so only the layout switches compete — and keeps the output that
|
||||||
|
//! changes the fewest lines, counting every line whose bytes change,
|
||||||
|
//! indentation included (`distance`). Ties go to the earlier preset in
|
||||||
|
//! [`PRESETS`], so a file the presets all agree on gets the default.
|
||||||
|
//!
|
||||||
|
//! Counting indentation is what keeps an edit local: a file already written
|
||||||
|
//! in one preset keeps it when a line written in another preset's shape is
|
||||||
|
//! added, because switching would re-indent every list the file already has.
|
||||||
|
//!
|
||||||
|
//! **Idempotent by construction.** Say the first run picked preset `s` and
|
||||||
|
//! wrote `y`. Formatting under `s` succeeded, so its convergence check
|
||||||
|
//! proved `s` leaves `y` exactly as it is: on the second run `s` is at
|
||||||
|
//! distance zero, the smallest there is. Whichever preset the second run
|
||||||
|
//! picks is therefore one that also leaves `y` exactly as it is, so the
|
||||||
|
//! second run writes `y` again.
|
||||||
|
//!
|
||||||
|
//! **And it names the same preset twice** — when asked to name one
|
||||||
|
//! ([`resolve_style`]). The second run picks the *earliest* preset that
|
||||||
|
//! leaves `y` as it is, which need not be `s` — on `lowrisc`'s output,
|
||||||
|
//! `lucisv` (which keeps alignment it finds) often agrees. So the name
|
||||||
|
//! reported is that earliest preset (`canonical`). Formatting never needs
|
||||||
|
//! the name, so only [`resolve_style`] pays for it.
|
||||||
|
//! `docs/features/format-styles/README.md` has the sweep that checks both.
|
||||||
|
|
||||||
|
use crate::format::{format_styled, Config, FormatError};
|
||||||
|
use crate::style::{Style, PRESETS};
|
||||||
|
|
||||||
|
/// The name the setting spells auto with.
|
||||||
|
pub(crate) const NAME: &str = "auto";
|
||||||
|
|
||||||
|
/// The output of the preset closest to `source`, or — when no preset can
|
||||||
|
/// format it — the first preset's error.
|
||||||
|
pub(crate) fn format_closest(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||||
|
closest(source, config).map(|(_, output)| output)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`crate::format_source`] under auto, also handing back the preset whose
|
||||||
|
/// output it is — so a caller can lay later ranges of the same buffer out in
|
||||||
|
/// it without searching again (the language server does). The preset is the
|
||||||
|
/// one that won, not [`resolve_style`]'s canonical name; both leave the
|
||||||
|
/// output exactly as it is.
|
||||||
|
pub fn format_auto(source: &str, config: &Config) -> Result<(String, Style), FormatError> {
|
||||||
|
closest(source, config).map(|(index, output)| (output, PRESETS[index]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `config` made concrete for the range and selection formatters: unchanged
|
||||||
|
/// unless it asks for auto, and then the closest preset of the *whole* file.
|
||||||
|
/// A file no preset can format — one with a parse error — gets the default's
|
||||||
|
/// layout. No naming pass: the output does not depend on the name.
|
||||||
|
pub(crate) fn concrete(source: &str, config: &Config) -> Config {
|
||||||
|
if !config.auto_style {
|
||||||
|
return config.clone();
|
||||||
|
}
|
||||||
|
match closest(source, config) {
|
||||||
|
Ok((index, _)) => fixed(config, PRESETS[index]),
|
||||||
|
Err(_) => fixed(config, PRESETS[0]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The preset auto *names* for this file, as a concrete config: the
|
||||||
|
/// earliest preset that leaves auto's output exactly as it is, which is the
|
||||||
|
/// one a second run names too. Unchanged when `config` does not ask for auto;
|
||||||
|
/// the default's when no preset can format the file.
|
||||||
|
pub fn resolve_style(source: &str, config: &Config) -> Config {
|
||||||
|
if !config.auto_style {
|
||||||
|
return config.clone();
|
||||||
|
}
|
||||||
|
match closest(source, config) {
|
||||||
|
Ok((index, output)) => fixed(config, PRESETS[canonical(&output, config, index)]),
|
||||||
|
Err(_) => fixed(config, PRESETS[0]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The index of the closest preset and its output. Stops at the first
|
||||||
|
/// preset that leaves `source` exactly as it is: nothing can be closer.
|
||||||
|
fn closest(source: &str, config: &Config) -> Result<(usize, String), FormatError> {
|
||||||
|
let mut best: Option<((usize, usize), usize, String)> = None;
|
||||||
|
let mut first_error = None;
|
||||||
|
for (index, preset) in PRESETS.into_iter().enumerate() {
|
||||||
|
match format_styled(source, &fixed(config, preset)) {
|
||||||
|
Ok(output) => {
|
||||||
|
let d = distance(source, &output);
|
||||||
|
if best.as_ref().is_none_or(|(least, _, _)| d < *least) {
|
||||||
|
best = Some((d, index, output));
|
||||||
|
}
|
||||||
|
if d == (0, 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
first_error.get_or_insert(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match (best, first_error) {
|
||||||
|
(Some((_, index, output)), _) => Ok((index, output)),
|
||||||
|
(None, Some(e)) => Err(e),
|
||||||
|
// Only reachable with no presets at all; there is always one.
|
||||||
|
(None, None) => format_styled(source, &fixed(config, PRESETS[0])).map(|out| (0, out)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest preset, up to `chosen`, that leaves `output` exactly as it
|
||||||
|
/// is — the one a second run over `output` picks. `chosen` itself always
|
||||||
|
/// qualifies: its output is a fixed point of it by the convergence check.
|
||||||
|
fn canonical(output: &str, config: &Config, chosen: usize) -> usize {
|
||||||
|
(0..chosen)
|
||||||
|
.find(|&i| {
|
||||||
|
format_styled(output, &fixed(config, PRESETS[i])).is_ok_and(|again| again == output)
|
||||||
|
})
|
||||||
|
.unwrap_or(chosen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `config` under `preset`'s layout switches, keeping its indent and width.
|
||||||
|
fn fixed(config: &Config, preset: Style) -> Config {
|
||||||
|
Config { style: preset, auto_style: false, ..config.clone() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far `output` is from `source`: the number of lines whose bytes
|
||||||
|
/// change — lines either text has that the other lacks, indentation
|
||||||
|
/// included — then, to break a tie, whether the texts differ at all. The
|
||||||
|
/// pair is `(0, 0)` exactly when the two are equal, which is the whole of the
|
||||||
|
/// idempotency argument above.
|
||||||
|
fn distance(source: &str, output: &str) -> (usize, usize) {
|
||||||
|
if source == output {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
(lines_apart(source.lines(), output.lines()), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The size of the multiset difference between two runs of lines: a line
|
||||||
|
/// moved elsewhere costs nothing.
|
||||||
|
fn lines_apart<'a>(a: impl Iterator<Item = &'a str>, b: impl Iterator<Item = &'a str>) -> usize {
|
||||||
|
let mut counts: std::collections::HashMap<&str, isize> = std::collections::HashMap::new();
|
||||||
|
for line in a {
|
||||||
|
*counts.entry(line).or_default() += 1;
|
||||||
|
}
|
||||||
|
for line in b {
|
||||||
|
*counts.entry(line).or_default() -= 1;
|
||||||
|
}
|
||||||
|
counts.values().map(|n| n.unsigned_abs()).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn distance_is_zero_only_for_equal_texts() {
|
||||||
|
assert_eq!(distance("a\nb\n", "a\nb\n"), (0, 0));
|
||||||
|
assert_eq!(distance("a\nb\n", "b\na\n"), (0, 1), "reordered: still apart");
|
||||||
|
assert_eq!(distance("a\nb\n", "a\nc\n"), (2, 1));
|
||||||
|
assert_eq!(distance("a\n", "a"), (0, 1), "a final newline is a difference too");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-indenting a line is a changed line like any other — the property
|
||||||
|
/// that keeps a one-line edit from flipping a whole file's preset.
|
||||||
|
#[test]
|
||||||
|
fn indentation_counts_in_full() {
|
||||||
|
assert_eq!(distance(" a\n", " a\n"), (2, 1));
|
||||||
|
let reindented = distance(" a\n b\n c\n", " a\n b\n c\n");
|
||||||
|
let one_line_rebroken = distance(" a\n b\n c\n", " a\n b c\n");
|
||||||
|
assert!(one_line_rebroken < reindented);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
//! `if`/`else` chains — procedural and generate — and the two style
|
||||||
|
//! switches that decide where their keywords go: a body's `begin`
|
||||||
|
//! (`Style::begin`) and the `else` after an `end` (`Style::else_keyword`).
|
||||||
|
//!
|
||||||
|
//! Both switches only choose between a space and a line break in front of a
|
||||||
|
//! keyword, so every style prints the same tokens in the same order.
|
||||||
|
|
||||||
|
use crate::doc::*;
|
||||||
|
use crate::style::Placement;
|
||||||
|
use vlog_parser::ast::*;
|
||||||
|
use vlog_parser::token::Comment;
|
||||||
|
|
||||||
|
use super::comment::trailing_ends_line;
|
||||||
|
use super::Fmt;
|
||||||
|
|
||||||
|
/// What goes in front of a keyword the style places: one space, or a line
|
||||||
|
/// break to the enclosing indentation.
|
||||||
|
pub(super) fn before_keyword(placement: Placement) -> Doc {
|
||||||
|
match placement {
|
||||||
|
Placement::SameLine => text(" "),
|
||||||
|
Placement::OwnLine => Doc::HardLine,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Fmt<'a> {
|
||||||
|
/// Whether an `else` may follow an `end` on the same line — an `end`
|
||||||
|
/// with a `: label` after it asks `else_after_label` instead.
|
||||||
|
fn else_cuddles(&self, labelled: bool) -> bool {
|
||||||
|
let style = &self.cfg.style;
|
||||||
|
let placement = if labelled { style.else_after_label } else { style.else_keyword };
|
||||||
|
style.else_keyword == Placement::SameLine && placement == Placement::SameLine
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn if_stmt(
|
||||||
|
&self,
|
||||||
|
qualifier: &Option<String>,
|
||||||
|
after_kw: &[Comment],
|
||||||
|
cond: &Expr,
|
||||||
|
then: &Stmt,
|
||||||
|
else_comments: &[Comment],
|
||||||
|
els: &Option<Box<Stmt>>,
|
||||||
|
) -> Doc {
|
||||||
|
let mut head = Vec::new();
|
||||||
|
if let Some(q) = qualifier {
|
||||||
|
head.push(text(format!("{q} ")));
|
||||||
|
}
|
||||||
|
self.word_then("if", after_kw, &mut head);
|
||||||
|
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||||
|
head.push(parens);
|
||||||
|
let prefix = concat(head);
|
||||||
|
// A line comment trailing the then-branch runs to end of line, so a
|
||||||
|
// cuddled `else` would be swallowed into its text.
|
||||||
|
let then_is_block =
|
||||||
|
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||||
|
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||||
|
if let Some(els) = els {
|
||||||
|
// A comment written before `else` prints before it, each on its
|
||||||
|
// own line: it is where the source put it, and after the keyword
|
||||||
|
// it would have crossed a token.
|
||||||
|
if !else_comments.is_empty() {
|
||||||
|
docs.push(Doc::HardLine);
|
||||||
|
for c in else_comments {
|
||||||
|
docs.push(self.comment(c));
|
||||||
|
docs.push(Doc::HardLine);
|
||||||
|
}
|
||||||
|
docs.push(text("else"));
|
||||||
|
} else if then_is_block && self.else_cuddles(ends_labelled(then)) {
|
||||||
|
docs.push(text(" else"));
|
||||||
|
} else {
|
||||||
|
docs.push(Doc::HardLine);
|
||||||
|
docs.push(text("else"));
|
||||||
|
}
|
||||||
|
// `else if` chains stay flat.
|
||||||
|
if let StmtKind::If {
|
||||||
|
qualifier: eq,
|
||||||
|
after_kw: ea,
|
||||||
|
cond: ec,
|
||||||
|
then: et,
|
||||||
|
else_comments: ecm,
|
||||||
|
els: ee,
|
||||||
|
} = &els.kind
|
||||||
|
{
|
||||||
|
docs.push(text(" "));
|
||||||
|
let mut meta_docs = self.leading(&els.meta);
|
||||||
|
docs.append(&mut meta_docs);
|
||||||
|
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
|
||||||
|
docs.extend(self.trailing(&els.meta));
|
||||||
|
} else {
|
||||||
|
docs.push(self.stmt_as_body(text(""), els));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
concat(docs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
||||||
|
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
||||||
|
let begin = self.cfg.style.begin;
|
||||||
|
let mut cuddle = self.gen_block(&mut docs, &g.then, depth, begin)
|
||||||
|
&& self.else_cuddles(g.then.end_label.is_some());
|
||||||
|
let mut els = &g.els;
|
||||||
|
while let Some(e) = els {
|
||||||
|
match e.as_ref() {
|
||||||
|
GenElse::If(_meta, gi) => {
|
||||||
|
if cuddle {
|
||||||
|
docs.push(text(" else if "));
|
||||||
|
} else {
|
||||||
|
docs.push(Doc::HardLine);
|
||||||
|
docs.push(text("else if "));
|
||||||
|
}
|
||||||
|
docs.push(self.parens(&gi.cond));
|
||||||
|
cuddle = self.gen_block(&mut docs, &gi.then, depth, begin)
|
||||||
|
&& self.else_cuddles(gi.then.end_label.is_some());
|
||||||
|
els = &gi.els;
|
||||||
|
}
|
||||||
|
GenElse::Block(b) => {
|
||||||
|
if cuddle {
|
||||||
|
docs.push(text(" else"));
|
||||||
|
} else {
|
||||||
|
docs.push(Doc::HardLine);
|
||||||
|
docs.push(text("else"));
|
||||||
|
}
|
||||||
|
self.gen_block(&mut docs, b, depth, begin);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
concat(docs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a statement is a block closed by `end : label`.
|
||||||
|
fn ends_labelled(s: &Stmt) -> bool {
|
||||||
|
matches!(&s.kind, StmtKind::Block { end_label: Some(_), .. })
|
||||||
|
}
|
||||||
@@ -35,10 +35,12 @@ impl<'a> Fmt<'a> {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let items = self.list_entries(items, &inst.param_directives);
|
let items = self.list_entries(items, &inst.param_directives);
|
||||||
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
|
let broken = !inst.param_directives.is_empty()
|
||||||
|
|| holds_verbatim_value(params)
|
||||||
|
|| self.style_breaks(params.iter().any(is_named));
|
||||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||||
self.slot_comments(&inst.after_hash, &mut docs);
|
self.slot_comments(&inst.after_hash, &mut docs);
|
||||||
docs.push(self.delimited("(", items, ")", broken));
|
docs.push(self.header_list("(", items, &[], ")", broken));
|
||||||
on_fresh_line = false;
|
on_fresh_line = false;
|
||||||
}
|
}
|
||||||
if let [only] = &inst.instances[..] {
|
if let [only] = &inst.instances[..] {
|
||||||
@@ -108,8 +110,10 @@ impl<'a> Fmt<'a> {
|
|||||||
let mut broken = !directives.is_empty();
|
let mut broken = !directives.is_empty();
|
||||||
let items: Vec<ListItem> = match conns {
|
let items: Vec<ListItem> = match conns {
|
||||||
Connections::Named(list) => {
|
Connections::Named(list) => {
|
||||||
let aligns = self.connection_aligns(list, directives, depth);
|
let aligns = self.connection_aligns(list, directives, self.list_depth(depth));
|
||||||
broken |= aligns.iter().any(Option::is_some) || holds_verbatim_value(list);
|
broken |= aligns.iter().any(Option::is_some)
|
||||||
|
|| holds_verbatim_value(list)
|
||||||
|
|| self.style_breaks(!list.is_empty());
|
||||||
list.iter()
|
list.iter()
|
||||||
.zip(&aligns)
|
.zip(&aligns)
|
||||||
.map(|(c, a)| {
|
.map(|(c, a)| {
|
||||||
@@ -134,7 +138,7 @@ impl<'a> Fmt<'a> {
|
|||||||
.collect(),
|
.collect(),
|
||||||
};
|
};
|
||||||
let items = self.list_entries(items, directives);
|
let items = self.list_entries(items, directives);
|
||||||
self.delimited("(", items, ")", broken)
|
self.header_list("(", items, &[], ")", broken)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The alignment plan for an instance's named connection list.
|
/// The alignment plan for an instance's named connection list.
|
||||||
@@ -439,6 +443,13 @@ fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a parameter override names what it sets (`.Width(8)`) rather
|
||||||
|
/// than giving it by position (`#(8)`): only a named list is one the style's
|
||||||
|
/// `OnePerLine` breaks.
|
||||||
|
fn is_named(c: &ListElem<Connection>) -> bool {
|
||||||
|
c.ok().is_some_and(|c| !c.name_span.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write —
|
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write —
|
||||||
/// with the comments written in any of its five gaps back where they stood.
|
/// with the comments written in any of its five gaps back where they stood.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -11,9 +11,11 @@
|
|||||||
use crate::align::Align;
|
use crate::align::Align;
|
||||||
use crate::doc::*;
|
use crate::doc::*;
|
||||||
use crate::range::Split;
|
use crate::range::Split;
|
||||||
|
use crate::style::Placement;
|
||||||
use vlog_parser::ast::*;
|
use vlog_parser::ast::*;
|
||||||
use vlog_parser::token::Comment;
|
use vlog_parser::token::Comment;
|
||||||
|
|
||||||
|
use super::branch::before_keyword;
|
||||||
use super::instance::drive_strength;
|
use super::instance::drive_strength;
|
||||||
use super::list::ListItem;
|
use super::list::ListItem;
|
||||||
use super::verbatim::Slot;
|
use super::verbatim::Slot;
|
||||||
@@ -485,44 +487,18 @@ impl<'a> Fmt<'a> {
|
|||||||
group(head)
|
group(head)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
/// Append a generate block, its `begin` placed as `begin` says; returns
|
||||||
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
/// true if it ended with `end` (so `else` can cuddle).
|
||||||
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
|
pub(super) fn gen_block(
|
||||||
let mut els = &g.els;
|
&self,
|
||||||
while let Some(e) = els {
|
docs: &mut Vec<Doc>,
|
||||||
match e.as_ref() {
|
b: &GenBlock,
|
||||||
GenElse::If(_meta, gi) => {
|
depth: usize,
|
||||||
if cuddle {
|
begin: Placement,
|
||||||
docs.push(text(" else if "));
|
) -> bool {
|
||||||
} else {
|
|
||||||
docs.push(Doc::HardLine);
|
|
||||||
docs.push(text("else if "));
|
|
||||||
}
|
|
||||||
docs.push(self.parens(&gi.cond));
|
|
||||||
cuddle = self.gen_block(&mut docs, &gi.then, depth);
|
|
||||||
els = &gi.els;
|
|
||||||
}
|
|
||||||
GenElse::Block(b) => {
|
|
||||||
if cuddle {
|
|
||||||
docs.push(text(" else"));
|
|
||||||
} else {
|
|
||||||
docs.push(Doc::HardLine);
|
|
||||||
docs.push(text("else"));
|
|
||||||
}
|
|
||||||
self.gen_block(&mut docs, b, depth);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
concat(docs)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append a generate block; returns true if it ended with `end` (so
|
|
||||||
/// `else` can cuddle).
|
|
||||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
|
|
||||||
if b.is_block {
|
if b.is_block {
|
||||||
if b.before_kw.is_empty() {
|
if b.before_kw.is_empty() {
|
||||||
docs.push(text(" "));
|
docs.push(before_keyword(begin));
|
||||||
} else {
|
} else {
|
||||||
self.inline_comments_spaced(&b.before_kw, docs);
|
self.inline_comments_spaced(&b.before_kw, docs);
|
||||||
}
|
}
|
||||||
@@ -581,7 +557,7 @@ impl<'a> Fmt<'a> {
|
|||||||
self.slot_comments(&g.comments.before_close, &mut header);
|
self.slot_comments(&g.comments.before_close, &mut header);
|
||||||
header.push(text(")"));
|
header.push(text(")"));
|
||||||
let mut docs = vec![concat(header)];
|
let mut docs = vec![concat(header)];
|
||||||
self.gen_block(&mut docs, &g.body, depth);
|
self.gen_block(&mut docs, &g.body, depth, self.cfg.style.begin);
|
||||||
concat(docs)
|
concat(docs)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -592,7 +568,8 @@ impl<'a> Fmt<'a> {
|
|||||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||||
body.extend(self.leading(&item.meta));
|
body.extend(self.leading(&item.meta));
|
||||||
let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)];
|
let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)];
|
||||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
// A case item's `begin` stays on the label's line in every style.
|
||||||
|
self.gen_block(&mut item_docs, &item.body, depth + 1, Placement::SameLine);
|
||||||
body.push(concat(item_docs));
|
body.push(concat(item_docs));
|
||||||
body.extend(self.trailing(&item.meta));
|
body.extend(self.trailing(&item.meta));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
|
|
||||||
use crate::align::{self, Align, ColSpec, Row};
|
use crate::align::{self, Align, ColSpec, Row};
|
||||||
use crate::doc::*;
|
use crate::doc::*;
|
||||||
|
use crate::style::{ListIndent, PortLists};
|
||||||
use vlog_parser::ast::*;
|
use vlog_parser::ast::*;
|
||||||
use vlog_parser::token::Comment;
|
use vlog_parser::token::Comment;
|
||||||
|
|
||||||
@@ -125,6 +126,53 @@ impl<'a> Fmt<'a> {
|
|||||||
dangling: &[Comment],
|
dangling: &[Comment],
|
||||||
close: &str,
|
close: &str,
|
||||||
force_break: bool,
|
force_break: bool,
|
||||||
|
) -> Doc {
|
||||||
|
self.delimited_at(open, items, dangling, close, force_break, ListIndent::Block)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Fmt::delimited_dangling`] for a module header's lists and an
|
||||||
|
/// instance's: the entries at the style's [`ListIndent`]. Whether the
|
||||||
|
/// style also breaks the list regardless of width is the caller's
|
||||||
|
/// question — [`Fmt::style_breaks`] — because only the caller knows
|
||||||
|
/// whether the list is one the style governs.
|
||||||
|
pub(super) fn header_list(
|
||||||
|
&self,
|
||||||
|
open: &str,
|
||||||
|
items: Vec<ListItem>,
|
||||||
|
dangling: &[Comment],
|
||||||
|
close: &str,
|
||||||
|
force_break: bool,
|
||||||
|
) -> Doc {
|
||||||
|
let indent = self.cfg.style.list_indent;
|
||||||
|
self.delimited_at(open, items, dangling, close, force_break, indent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the style lays a header or named-connection list out one
|
||||||
|
/// entry per line whatever its width: `PortLists::OnePerLine`, and the
|
||||||
|
/// list holds something.
|
||||||
|
pub(super) fn style_breaks(&self, has_entries: bool) -> bool {
|
||||||
|
has_entries && self.cfg.style.port_lists == PortLists::OnePerLine
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The nesting depth a header list's entries print at when the list
|
||||||
|
/// itself opens at `depth` — one more under `ListIndent::Wrap`. The
|
||||||
|
/// alignment budget is measured from it.
|
||||||
|
pub(super) fn list_depth(&self, depth: usize) -> usize {
|
||||||
|
match self.cfg.style.list_indent {
|
||||||
|
ListIndent::Block => depth,
|
||||||
|
ListIndent::Wrap => depth + 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bracketed layout behind both, entries `levels` deep.
|
||||||
|
fn delimited_at(
|
||||||
|
&self,
|
||||||
|
open: &str,
|
||||||
|
items: Vec<ListItem>,
|
||||||
|
dangling: &[Comment],
|
||||||
|
close: &str,
|
||||||
|
force_break: bool,
|
||||||
|
levels: ListIndent,
|
||||||
) -> Doc {
|
) -> Doc {
|
||||||
if items.is_empty() && dangling.is_empty() {
|
if items.is_empty() && dangling.is_empty() {
|
||||||
return text(format!("{open}{close}"));
|
return text(format!("{open}{close}"));
|
||||||
@@ -136,7 +184,11 @@ impl<'a> Fmt<'a> {
|
|||||||
let close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break;
|
let close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break;
|
||||||
// Peek at blank_before flags is handled by leading comments already;
|
// Peek at blank_before flags is handled by leading comments already;
|
||||||
// blank lines inside bracketed lists are dropped deliberately.
|
// blank lines inside bracketed lists are dropped deliberately.
|
||||||
let mut docs = vec![text(open), indent(inner)];
|
let entries = match levels {
|
||||||
|
ListIndent::Block => indent(inner),
|
||||||
|
ListIndent::Wrap => indent(vec![indent(inner)]),
|
||||||
|
};
|
||||||
|
let mut docs = vec![text(open), entries];
|
||||||
docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine });
|
docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine });
|
||||||
docs.push(text(close));
|
docs.push(text(close));
|
||||||
group(docs)
|
group(docs)
|
||||||
@@ -326,7 +378,8 @@ impl<'a> Fmt<'a> {
|
|||||||
j += 1;
|
j += 1;
|
||||||
}
|
}
|
||||||
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
|
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
|
||||||
if let Some(plan) = align::plan(self.src, &run, specs, budget) {
|
if let Some(plan) = align::plan(self.src, &run, specs, budget, self.cfg.style.alignment)
|
||||||
|
{
|
||||||
for slot in &mut out[i..j] {
|
for slot in &mut out[i..j] {
|
||||||
*slot = Some(plan.clone());
|
*slot = Some(plan.clone());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
//! Formatting rules: AST → Doc.
|
//! Formatting rules: AST → Doc.
|
||||||
//!
|
//!
|
||||||
//! Style follows Verible's defaults: 2-space indent, 100-column lines,
|
//! The default style follows Verible's defaults: 2-space indent,
|
||||||
//! one-element-per-line port/connection lists when a construct does not fit
|
//! 100-column lines, one-element-per-line port/connection lists when a
|
||||||
//! on a single line, cuddled `begin`/`end`.
|
//! construct does not fit on a single line, cuddled `begin`/`end`. The other
|
||||||
|
//! named styles (`crate::style`) move the same tokens to other lines.
|
||||||
//!
|
//!
|
||||||
//! The rules are one `Fmt` whose methods are spread over the sibling
|
//! The rules are one `Fmt` whose methods are spread over the sibling
|
||||||
//! modules by grammar domain — `item`, `module`, `instance`, `decl`,
|
//! modules by grammar domain — `item`, `module`, `instance`, `decl`,
|
||||||
//! `routine`, `class`, `cover`, `sva`, `stmt`, `expr` — on top of the
|
//! `routine`, `class`, `cover`, `sva`, `stmt`, `branch`, `expr` — on top of the
|
||||||
//! shared machinery they all print through — `comment`, `verbatim`,
|
//! shared machinery they all print through — `comment`, `verbatim`,
|
||||||
//! `phrase`, `list`. This file holds what the crate exports (`Config`,
|
//! `phrase`, `list`. This file holds what the crate exports (`Config`,
|
||||||
//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and
|
//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and
|
||||||
//! the name helpers every module writes an identifier through.
|
//! the name helpers every module writes an identifier through.
|
||||||
|
|
||||||
|
mod branch;
|
||||||
mod class;
|
mod class;
|
||||||
mod comment;
|
mod comment;
|
||||||
mod cover;
|
mod cover;
|
||||||
@@ -32,12 +34,16 @@ use crate::doc::{concat, text, Doc};
|
|||||||
use crate::fence::{self, Region};
|
use crate::fence::{self, Region};
|
||||||
use crate::printer::Printer;
|
use crate::printer::Printer;
|
||||||
use crate::range::{self, Split};
|
use crate::range::{self, Split};
|
||||||
|
use crate::style::{Style, LUCISV};
|
||||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||||
use vlog_parser::ast::*;
|
use vlog_parser::ast::*;
|
||||||
|
|
||||||
|
/// Everything a formatting run is configured with.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
|
/// The line limit the printer breaks at.
|
||||||
pub max_width: usize,
|
pub max_width: usize,
|
||||||
|
/// Spaces per indentation level.
|
||||||
pub indent_width: usize,
|
pub indent_width: usize,
|
||||||
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
|
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
|
||||||
/// / `` `uvm_component_utils_begin `` and their `_end`, which are plain
|
/// / `` `uvm_component_utils_begin `` and their `_end`, which are plain
|
||||||
@@ -47,11 +53,53 @@ pub struct Config {
|
|||||||
/// cleanly, so a project opts in through `[format] uvm-utils-indent` and
|
/// cleanly, so a project opts in through `[format] uvm-utils-indent` and
|
||||||
/// nobody else moves a byte.
|
/// nobody else moves a byte.
|
||||||
pub uvm_utils_indent: bool,
|
pub uvm_utils_indent: bool,
|
||||||
|
/// The named style's layout switches. Its own `indent` and `line_length`
|
||||||
|
/// are only the starting values [`Config::styled`] copies into the two
|
||||||
|
/// fields above; the layout rules never read them.
|
||||||
|
pub style: Style,
|
||||||
|
/// `style = "auto"`: ignore `style` and lay the file out in the preset
|
||||||
|
/// whose layout it is already closest to, at this config's own indent
|
||||||
|
/// and width (`crate::auto`).
|
||||||
|
pub auto_style: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// The settings `style` asks for: its indent and line length, its layout.
|
||||||
|
/// An explicit `indent` or `line-length` is written over the result.
|
||||||
|
pub fn styled(style: Style) -> Config {
|
||||||
|
Config {
|
||||||
|
max_width: style.line_length,
|
||||||
|
indent_width: style.indent,
|
||||||
|
uvm_utils_indent: false,
|
||||||
|
style,
|
||||||
|
auto_style: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The settings a style *name* asks for: a preset, or `auto` — which
|
||||||
|
/// starts from the default's indent and width, since it picks a layout,
|
||||||
|
/// not a size. `None` for any other name.
|
||||||
|
pub fn named(name: &str) -> Option<Config> {
|
||||||
|
if name == crate::auto::NAME {
|
||||||
|
return Some(Config { auto_style: true, ..Config::default() });
|
||||||
|
}
|
||||||
|
crate::style::preset(name).map(Config::styled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name the setting spells this config's style with: `auto`, or the
|
||||||
|
/// preset's.
|
||||||
|
pub fn style_name(&self) -> &'static str {
|
||||||
|
if self.auto_style {
|
||||||
|
crate::auto::NAME
|
||||||
|
} else {
|
||||||
|
self.style.name
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Config {
|
impl Default for Config {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Config { max_width: 100, indent_width: 2, uvm_utils_indent: false }
|
Config::styled(LUCISV)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,6 +151,14 @@ impl From<VerificationError> for FormatError {
|
|||||||
/// lets sufficiently nested input abort the process instead of returning
|
/// lets sufficiently nested input abort the process instead of returning
|
||||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||||
|
if config.auto_style {
|
||||||
|
return crate::auto::format_closest(source, config);
|
||||||
|
}
|
||||||
|
format_styled(source, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`format_source`] under exactly `config`'s style, `auto_style` ignored.
|
||||||
|
pub(crate) fn format_styled(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||||
verify_equivalence(source, &output)?;
|
verify_equivalence(source, &output)?;
|
||||||
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
|
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
|
||||||
@@ -119,6 +175,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
|||||||
/// replaying the same per-item decisions against the output — see
|
/// replaying the same per-item decisions against the output — see
|
||||||
/// `docs/features/range-formatting/README.md`.
|
/// `docs/features/range-formatting/README.md`.
|
||||||
///
|
///
|
||||||
|
/// Under `style = "auto"` the style is the one the *whole* file is closest
|
||||||
|
/// to, never the selected lines' alone.
|
||||||
|
///
|
||||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||||
pub fn format_range(
|
pub fn format_range(
|
||||||
@@ -126,6 +185,7 @@ pub fn format_range(
|
|||||||
config: &Config,
|
config: &Config,
|
||||||
lines: &range::LineRanges,
|
lines: &range::LineRanges,
|
||||||
) -> Result<String, FormatError> {
|
) -> Result<String, FormatError> {
|
||||||
|
let config = &crate::auto::concrete(source, config);
|
||||||
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
|
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
|
||||||
let selection = range::select(source, &file, lines);
|
let selection = range::select(source, &file, lines);
|
||||||
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
|
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
|
||||||
|
|||||||
@@ -74,10 +74,10 @@ impl<'a> Fmt<'a> {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let items = self.list_entries(items, &m.param_directives);
|
let items = self.list_entries(items, &m.param_directives);
|
||||||
let broken = !m.param_directives.is_empty();
|
let broken = !m.param_directives.is_empty() || self.style_breaks(!items.is_empty());
|
||||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||||
self.slot_comments(&m.param_after_hash, &mut docs);
|
self.slot_comments(&m.param_after_hash, &mut docs);
|
||||||
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken));
|
docs.push(self.header_list("(", items, &m.param_dangling, ")", broken));
|
||||||
on_fresh_line = false;
|
on_fresh_line = false;
|
||||||
}
|
}
|
||||||
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
|
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
|
||||||
@@ -92,7 +92,8 @@ impl<'a> Fmt<'a> {
|
|||||||
PortList::Ansi(ports) => {
|
PortList::Ansi(ports) => {
|
||||||
// An aligned list is a broken list: alignment only
|
// An aligned list is a broken list: alignment only
|
||||||
// means anything one element per line.
|
// means anything one element per line.
|
||||||
let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1);
|
let at = self.list_depth(depth + 1);
|
||||||
|
let aligns = self.ansi_port_aligns(ports, &m.port_directives, at);
|
||||||
broken |= aligns.iter().any(Option::is_some);
|
broken |= aligns.iter().any(Option::is_some);
|
||||||
ports
|
ports
|
||||||
.iter()
|
.iter()
|
||||||
@@ -116,10 +117,11 @@ impl<'a> Fmt<'a> {
|
|||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
let items = self.list_entries(items, &m.port_directives);
|
let items = self.list_entries(items, &m.port_directives);
|
||||||
|
broken |= self.style_breaks(!items.is_empty());
|
||||||
if !on_fresh_line {
|
if !on_fresh_line {
|
||||||
docs.push(text(" "));
|
docs.push(text(" "));
|
||||||
}
|
}
|
||||||
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken));
|
docs.push(self.header_list("(", items, &m.port_dangling, ")", broken));
|
||||||
docs.push(self.semi(&m.before_semi));
|
docs.push(self.semi(&m.before_semi));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
//! Statements: the `begin … end` block, a statement as the body of a
|
//! Statements: the `begin … end` block, a statement as the body of a
|
||||||
//! header (a cuddled block or an indented line), the dispatch from
|
//! header (a cuddled block or an indented line), the dispatch from
|
||||||
//! `StmtKind` to its layout, `if`/`else` chains, `case` items, and the
|
//! `StmtKind` to its layout, `case` items, and the
|
||||||
//! timing controls and sensitivity lists that head an `always` block or
|
//! timing controls and sensitivity lists that head an `always` block or
|
||||||
//! a clocking event.
|
//! a clocking event.
|
||||||
//!
|
//!
|
||||||
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
|
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
|
||||||
//! statement form — and stays whole; the forms with a layout of their own
|
//! statement form — and stays whole; `case` has a layout of its own in the
|
||||||
//! (`if`, `case`) are the functions after it.
|
//! functions after it, `if` in `branch.rs`.
|
||||||
|
|
||||||
use crate::doc::*;
|
use crate::doc::*;
|
||||||
use vlog_parser::ast::*;
|
use vlog_parser::ast::*;
|
||||||
use vlog_parser::span::TextRange;
|
use vlog_parser::span::TextRange;
|
||||||
use vlog_parser::token::Comment;
|
use vlog_parser::token::Comment;
|
||||||
|
|
||||||
use super::comment::{is_line_comment, trailing_ends_line};
|
use super::branch::before_keyword;
|
||||||
|
use super::comment::is_line_comment;
|
||||||
use super::{join_paths, named, skip_trivia, Fmt};
|
use super::{join_paths, named, skip_trivia, Fmt};
|
||||||
|
use crate::style::Placement;
|
||||||
|
|
||||||
/// The pieces of a `begin … end` block a printer needs, gathered so the
|
/// The pieces of a `begin … end` block a printer needs, gathered so the
|
||||||
/// two spellings (a statement, and a body cuddled onto a header) pass one
|
/// two spellings (a statement, and a body cuddled onto a header) pass one
|
||||||
@@ -86,7 +88,14 @@ impl<'a> Fmt<'a> {
|
|||||||
/// The same, skipping the body's first `skip` leading comments because
|
/// The same, skipping the body's first `skip` leading comments because
|
||||||
/// `prefix` already printed them inside its parentheses. See
|
/// `prefix` already printed them inside its parentheses. See
|
||||||
/// [`Fmt::header_parens`].
|
/// [`Fmt::header_parens`].
|
||||||
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
pub(super) fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||||
|
self.body_after(prefix, s, skip, self.cfg.style.begin)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The layout behind both: a block's `begin` goes where `begin` says —
|
||||||
|
/// the style's choice for a statement header, always the label's line
|
||||||
|
/// for a `case` item.
|
||||||
|
fn body_after(&self, prefix: Doc, s: &Stmt, skip: usize, begin: Placement) -> Doc {
|
||||||
match &s.kind {
|
match &s.kind {
|
||||||
StmtKind::Block {
|
StmtKind::Block {
|
||||||
label_comments,
|
label_comments,
|
||||||
@@ -97,7 +106,7 @@ impl<'a> Fmt<'a> {
|
|||||||
end_label,
|
end_label,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
let mut docs = vec![prefix, text(" ")];
|
let mut docs = vec![prefix, before_keyword(begin)];
|
||||||
docs.extend(self.leading_from(&s.meta, skip));
|
docs.extend(self.leading_from(&s.meta, skip));
|
||||||
docs.push(self.block_doc(BlockDoc {
|
docs.push(self.block_doc(BlockDoc {
|
||||||
label_comments,
|
label_comments,
|
||||||
@@ -115,7 +124,7 @@ impl<'a> Fmt<'a> {
|
|||||||
let mut docs = vec![prefix, text(" ")];
|
let mut docs = vec![prefix, text(" ")];
|
||||||
docs.extend(self.leading_from(&s.meta, skip));
|
docs.extend(self.leading_from(&s.meta, skip));
|
||||||
let control_doc = self.timing_control(control);
|
let control_doc = self.timing_control(control);
|
||||||
docs.push(self.stmt_as_body(control_doc, inner));
|
docs.push(self.body_after(control_doc, inner, 0, begin));
|
||||||
docs.extend(self.trailing(&s.meta));
|
docs.extend(self.trailing(&s.meta));
|
||||||
concat(docs)
|
concat(docs)
|
||||||
}
|
}
|
||||||
@@ -539,67 +548,6 @@ impl<'a> Fmt<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn if_stmt(
|
|
||||||
&self,
|
|
||||||
qualifier: &Option<String>,
|
|
||||||
after_kw: &[Comment],
|
|
||||||
cond: &Expr,
|
|
||||||
then: &Stmt,
|
|
||||||
else_comments: &[Comment],
|
|
||||||
els: &Option<Box<Stmt>>,
|
|
||||||
) -> Doc {
|
|
||||||
let mut head = Vec::new();
|
|
||||||
if let Some(q) = qualifier {
|
|
||||||
head.push(text(format!("{q} ")));
|
|
||||||
}
|
|
||||||
self.word_then("if", after_kw, &mut head);
|
|
||||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
|
||||||
head.push(parens);
|
|
||||||
let prefix = concat(head);
|
|
||||||
// A line comment trailing the then-branch runs to end of line, so a
|
|
||||||
// cuddled `else` would be swallowed into its text.
|
|
||||||
let then_is_block =
|
|
||||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
|
||||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
|
||||||
if let Some(els) = els {
|
|
||||||
// A comment written before `else` prints before it, each on its
|
|
||||||
// own line: it is where the source put it, and after the keyword
|
|
||||||
// it would have crossed a token.
|
|
||||||
if !else_comments.is_empty() {
|
|
||||||
docs.push(Doc::HardLine);
|
|
||||||
for c in else_comments {
|
|
||||||
docs.push(self.comment(c));
|
|
||||||
docs.push(Doc::HardLine);
|
|
||||||
}
|
|
||||||
docs.push(text("else"));
|
|
||||||
} else if then_is_block {
|
|
||||||
docs.push(text(" else"));
|
|
||||||
} else {
|
|
||||||
docs.push(Doc::HardLine);
|
|
||||||
docs.push(text("else"));
|
|
||||||
}
|
|
||||||
// `else if` chains stay flat.
|
|
||||||
if let StmtKind::If {
|
|
||||||
qualifier: eq,
|
|
||||||
after_kw: ea,
|
|
||||||
cond: ec,
|
|
||||||
then: et,
|
|
||||||
else_comments: ecm,
|
|
||||||
els: ee,
|
|
||||||
} = &els.kind
|
|
||||||
{
|
|
||||||
docs.push(text(" "));
|
|
||||||
let mut meta_docs = self.leading(&els.meta);
|
|
||||||
docs.append(&mut meta_docs);
|
|
||||||
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
|
|
||||||
docs.extend(self.trailing(&els.meta));
|
|
||||||
} else {
|
|
||||||
docs.push(self.stmt_as_body(text(""), els));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
concat(docs)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `A, B:` head of a case item — `default:` when the list is empty.
|
/// The `A, B:` head of a case item — `default:` when the list is empty.
|
||||||
/// Labels normally share one line; as soon as any of them carries a
|
/// Labels normally share one line; as soon as any of them carries a
|
||||||
/// comment they go one per line, so a comment written between two labels
|
/// comment they go one per line, so a comment written between two labels
|
||||||
@@ -669,7 +617,8 @@ impl<'a> Fmt<'a> {
|
|||||||
{
|
{
|
||||||
return text("default;");
|
return text("default;");
|
||||||
}
|
}
|
||||||
self.stmt_as_body(self.case_labels(&item.labels, &item.before_colon, item.span), &item.stmt)
|
let labels = self.case_labels(&item.labels, &item.before_colon, item.span);
|
||||||
|
self.body_after(labels, &item.stmt, 0, Placement::SameLine)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
//! Formatter engine: document IR + printer + formatting rules.
|
//! Formatter engine: document IR + printer + formatting rules.
|
||||||
|
|
||||||
pub mod align;
|
pub mod align;
|
||||||
|
mod auto;
|
||||||
pub mod doc;
|
pub mod doc;
|
||||||
pub mod fence;
|
pub mod fence;
|
||||||
pub mod format;
|
pub mod format;
|
||||||
pub mod printer;
|
pub mod printer;
|
||||||
pub mod range;
|
pub mod range;
|
||||||
mod selection;
|
mod selection;
|
||||||
|
pub mod style;
|
||||||
pub mod verify;
|
pub mod verify;
|
||||||
|
|
||||||
|
pub use auto::{format_auto, resolve_style};
|
||||||
pub use format::{format_range, format_source, Config, FormatError};
|
pub use format::{format_range, format_source, Config, FormatError};
|
||||||
pub use range::LineRanges;
|
pub use range::LineRanges;
|
||||||
pub use selection::format_selection;
|
pub use selection::format_selection;
|
||||||
|
pub use style::Style;
|
||||||
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||||
@@ -36,12 +36,16 @@ use vlog_parser::ParseDiagnostic;
|
|||||||
/// where the selection is clear of every parse error; otherwise, as on any
|
/// where the selection is clear of every parse error; otherwise, as on any
|
||||||
/// failed check, the caller gets an error and must keep the original text.
|
/// failed check, the caller gets an error and must keep the original text.
|
||||||
///
|
///
|
||||||
|
/// Under `style = "auto"` the style is the one the *whole* file is closest
|
||||||
|
/// to, so a selection lays out exactly as a whole-file format would.
|
||||||
|
///
|
||||||
/// Same stack requirement as [`crate::format_source`].
|
/// Same stack requirement as [`crate::format_source`].
|
||||||
pub fn format_selection(
|
pub fn format_selection(
|
||||||
source: &str,
|
source: &str,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
lines: &LineRanges,
|
lines: &LineRanges,
|
||||||
) -> Result<String, FormatError> {
|
) -> Result<String, FormatError> {
|
||||||
|
let config = &crate::auto::concrete(source, config);
|
||||||
let tree = Tree::parse(source).map_err(FormatError::Source)?;
|
let tree = Tree::parse(source).map_err(FormatError::Source)?;
|
||||||
let Some(root) = Scope::root(&tree.file) else {
|
let Some(root) = Scope::root(&tree.file) else {
|
||||||
return format_range(source, config, lines);
|
return format_range(source, config, lines);
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
//! Named formatting styles: the house layouts a project picks with
|
||||||
|
//! `[format] style = "<name>"`, `--style <name>` or `lucisv.format.style`.
|
||||||
|
//!
|
||||||
|
//! A style is one plain [`Style`] value — numbers and two-way switches, no
|
||||||
|
//! code — and every preset is one row of the [`PRESETS`] table in this file,
|
||||||
|
//! so the presets can be compared by reading them side by side. Each switch only ever moves
|
||||||
|
//! whitespace: which line a token starts on, and how many spaces precede
|
||||||
|
//! it. The token stream is the same under every style, which is why the
|
||||||
|
//! safety net in `verify.rs` needs no knowledge of styles at all.
|
||||||
|
//!
|
||||||
|
//! `lucisv` is the default and is exactly the layout lucisv has always
|
||||||
|
//! produced. Only `google` and `lowrisc` follow a published guide; `ansi`,
|
||||||
|
//! `microsoft` and `nxp` are lucisv's educated guesses at what those names
|
||||||
|
//! suggest, **not** rules published by those organisations. Each preset's
|
||||||
|
//! comment says what it is modelled on and how sure that is.
|
||||||
|
//!
|
||||||
|
//! The full rationale, the sources and the per-preset safety sweeps are in
|
||||||
|
//! `docs/features/format-styles/README.md`.
|
||||||
|
|
||||||
|
/// Where a keyword goes relative to the code before it.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Placement {
|
||||||
|
/// On the same line, one space after it.
|
||||||
|
SameLine,
|
||||||
|
/// At the start of a line of its own, at the enclosing indentation.
|
||||||
|
OwnLine,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When a module header's lists and a named connection list are broken.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum PortLists {
|
||||||
|
/// On one line if the whole construct fits, one entry per line if not.
|
||||||
|
Fit,
|
||||||
|
/// One entry per line whenever the list holds anything.
|
||||||
|
OnePerLine,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How deep the entries of a broken header or connection list are indented.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ListIndent {
|
||||||
|
/// One indentation level past the line that opens the list.
|
||||||
|
Block,
|
||||||
|
/// Two levels — a continuation indent, Verible's `wrap`.
|
||||||
|
Wrap,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether runs of ports, connections and `parameter` declarations are
|
||||||
|
/// padded into columns.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Alignment {
|
||||||
|
/// Keep the columns the author already lined up, add none
|
||||||
|
/// (`docs/features/alignment/README.md`).
|
||||||
|
Infer,
|
||||||
|
/// Pad every run into columns, whatever the source did.
|
||||||
|
Always,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One house style: every layout choice that differs between presets.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Style {
|
||||||
|
/// The name the setting spells it with.
|
||||||
|
pub name: &'static str,
|
||||||
|
/// Spaces per indentation level; an explicit `indent` overrides it.
|
||||||
|
pub indent: usize,
|
||||||
|
/// Line limit; an explicit `line-length` overrides it.
|
||||||
|
pub line_length: usize,
|
||||||
|
/// `begin` of a statement body: `if (a) begin` (`SameLine`) or
|
||||||
|
/// `if (a)` / `begin` (`OwnLine`). Every header that owns a body moves
|
||||||
|
/// with it — `always_comb`, `always_ff @(…)`, `initial`, `final`, `if`,
|
||||||
|
/// `else`, `for`, `foreach`, `while`, `repeat`, `forever`, `wait`, and
|
||||||
|
/// generate `if`/`for`. A `case` item and `do` keep theirs on the label's
|
||||||
|
/// line either way.
|
||||||
|
pub begin: Placement,
|
||||||
|
/// `else` after a block's `end`: `end else begin` (`SameLine`) or `end` /
|
||||||
|
/// `else begin` (`OwnLine`). Procedural and generate `if` only.
|
||||||
|
pub else_keyword: Placement,
|
||||||
|
/// `else` after a *labelled* `end`, when `else_keyword` is `SameLine`:
|
||||||
|
/// `end : l1 else begin` (`SameLine`) or `end : l1` / `else begin`
|
||||||
|
/// (`OwnLine`), the exception both Google's and lowRISC's guides make.
|
||||||
|
pub else_after_label: Placement,
|
||||||
|
/// `module m (input a, input b);` when it fits (`Fit`), or `module m (` /
|
||||||
|
/// ` input a,` / ` input b` / `);` always (`OnePerLine`). Governs a
|
||||||
|
/// module/interface/program header's parameter and port lists, and an
|
||||||
|
/// instance's *named* parameter overrides and connections. Not positional
|
||||||
|
/// overrides (`#(16)`), not ordered connections (`(a, b)`), not
|
||||||
|
/// function/task ports, not expression lists.
|
||||||
|
pub port_lists: PortLists,
|
||||||
|
/// The entries of a header or instance list once broken: ` .clk(clk),`
|
||||||
|
/// (`Block`) or ` .clk(clk),` (`Wrap`). The closing `)` stays at the
|
||||||
|
/// opening line's column — except in a declaration of several instances
|
||||||
|
/// (`sub u0 (…), u1 (…);`), whose instances hang one level in and close
|
||||||
|
/// there.
|
||||||
|
pub list_indent: ListIndent,
|
||||||
|
/// `input a,` / `input [7:0] b` kept as written (`Infer`), or always
|
||||||
|
/// `input a,` / `input [7:0] b` (`Always`). One switch for all three
|
||||||
|
/// tables lucisv aligns: ANSI ports, named connections, and runs of
|
||||||
|
/// `parameter`/`localparam` declarations.
|
||||||
|
pub alignment: Alignment,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row of [`PRESETS`], in its column order.
|
||||||
|
#[allow(clippy::too_many_arguments)] // a table row: the arguments *are* the columns
|
||||||
|
const fn row(
|
||||||
|
name: &'static str,
|
||||||
|
indent: usize,
|
||||||
|
line_length: usize,
|
||||||
|
begin: Placement,
|
||||||
|
else_keyword: Placement,
|
||||||
|
else_after_label: Placement,
|
||||||
|
port_lists: PortLists,
|
||||||
|
list_indent: ListIndent,
|
||||||
|
alignment: Alignment,
|
||||||
|
) -> Style {
|
||||||
|
Style {
|
||||||
|
name,
|
||||||
|
indent,
|
||||||
|
line_length,
|
||||||
|
begin,
|
||||||
|
else_keyword,
|
||||||
|
else_after_label,
|
||||||
|
port_lists,
|
||||||
|
list_indent,
|
||||||
|
alignment,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use Alignment::{Always, Infer};
|
||||||
|
use ListIndent::{Block, Wrap};
|
||||||
|
use Placement::{OwnLine, SameLine};
|
||||||
|
use PortLists::{Fit, OnePerLine};
|
||||||
|
|
||||||
|
/// Every preset, the default first — one row each, so the six can be read
|
||||||
|
/// side by side. What each is modelled on, and how sure that is, is on its
|
||||||
|
/// named constant below.
|
||||||
|
///
|
||||||
|
/// Kept by hand on one line per row with the columns lined up: rustfmt would
|
||||||
|
/// break every row into eleven lines and the table would stop being one.
|
||||||
|
#[rustfmt::skip]
|
||||||
|
pub const PRESETS: [Style; 6] = [
|
||||||
|
// name indent width begin else else after `end : l` lists list indent alignment
|
||||||
|
row("lucisv", 2, 100, SameLine, SameLine, SameLine, Fit, Block, Infer),
|
||||||
|
row("google", 2, 100, SameLine, SameLine, OwnLine, OnePerLine, Wrap, Infer),
|
||||||
|
row("lowrisc", 2, 100, SameLine, SameLine, OwnLine, OnePerLine, Block, Always),
|
||||||
|
row("ansi", 4, 80, OwnLine, OwnLine, OwnLine, Fit, Block, Infer),
|
||||||
|
row("microsoft", 4, 120, OwnLine, OwnLine, OwnLine, OnePerLine, Block, Infer),
|
||||||
|
row("nxp", 2, 80, SameLine, OwnLine, OwnLine, OnePerLine, Block, Always),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// lucisv's own layout, and the default: byte-for-byte what every release
|
||||||
|
/// before styles existed produced. Verible-like — 2 spaces, 100 columns,
|
||||||
|
/// cuddled `begin`/`end`, alignment read from the source.
|
||||||
|
pub const LUCISV: Style = PRESETS[0];
|
||||||
|
|
||||||
|
/// The Google Verilog Style Guide (google.github.io/styleguide/verilogguide):
|
||||||
|
/// "Line Length" 100, "Indentation" 2, "Eschatology" `begin` on the
|
||||||
|
/// keyword's line and `end else begin` — but `else` on a new line after a
|
||||||
|
/// labelled `end` — "Module Header Definition Examples" one port per line
|
||||||
|
/// with the list at a 4-space continuation indent, "Use named ports" one
|
||||||
|
/// connection per line. "Tabular Alignment" is only *recommended*, and the
|
||||||
|
/// guide's own examples are not aligned, so alignment stays inferred.
|
||||||
|
/// Confidence: high, from the published guide.
|
||||||
|
pub const GOOGLE: Style = PRESETS[1];
|
||||||
|
|
||||||
|
/// The lowRISC Verilog Coding Style Guide (lowRISC/style-guides,
|
||||||
|
/// VerilogCodingStyle.md), OpenTitan's house style, which extends Google's:
|
||||||
|
/// the same 2 / 100 / `end else begin` (with the same labelled-`end`
|
||||||
|
/// exception, "Begin / End"), one port per line at a 2-space indent ("Module
|
||||||
|
/// Declaration"). "Module Instantiation" *requires* connections aligned in
|
||||||
|
/// tabular style; declaration ports are aligned in the guide's examples but
|
||||||
|
/// not required to be. lucisv has one alignment switch for ports,
|
||||||
|
/// connections and parameters, so the row aligns all three. Two deviations:
|
||||||
|
/// lucisv writes the widest connection `.clk (clk)`, the guide tight
|
||||||
|
/// (`.clk(clk)`); and a comment line inside a table ends lucisv's alignment
|
||||||
|
/// group, where the guide keeps aligning across it. Confidence: high, from
|
||||||
|
/// the published guide, for everything but those two.
|
||||||
|
pub const LOWRISC: Style = PRESETS[2];
|
||||||
|
|
||||||
|
/// "ANSI" as C formatters use the word (Artistic Style, and iStyle, its
|
||||||
|
/// Verilog port: `--style=ansi`, 4-space default): Allman layout, `begin`
|
||||||
|
/// and `else` on lines of their own. The 80 columns are lucisv's guess.
|
||||||
|
/// Confidence: medium for `begin`/`else`, a guess for the rest.
|
||||||
|
pub const ANSI: Style = PRESETS[3];
|
||||||
|
|
||||||
|
/// clang-format's `Microsoft` base style for C-family code — 4 spaces, 120
|
||||||
|
/// columns, braces and `else` on their own lines — carried over to
|
||||||
|
/// `begin`/`end` by analogy, with one connection per line as clang-format's
|
||||||
|
/// `VerilogBreakBetweenInstancePorts` does. **lucisv's guess**: Microsoft
|
||||||
|
/// publishes no Verilog style that we know of.
|
||||||
|
pub const MICROSOFT: Style = PRESETS[4];
|
||||||
|
|
||||||
|
/// A conservative RTL house style of the kind long-lived ASIC teams write
|
||||||
|
/// down: 80 columns, `end` and `else` on separate lines, every port on its
|
||||||
|
/// own line and every port and connection table aligned. **lucisv's guess**:
|
||||||
|
/// NXP publishes no Verilog style guide that we could find.
|
||||||
|
pub const NXP: Style = PRESETS[5];
|
||||||
|
|
||||||
|
/// The preset called `name`, if there is one.
|
||||||
|
pub fn preset(name: &str) -> Option<Style> {
|
||||||
|
PRESETS.into_iter().find(|s| s.name == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The preset names, in [`PRESETS`] order.
|
||||||
|
pub fn names() -> impl Iterator<Item = &'static str> {
|
||||||
|
PRESETS.iter().map(|s| s.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_is_first_and_names_are_unique() {
|
||||||
|
assert_eq!(PRESETS[0], LUCISV);
|
||||||
|
let mut names: Vec<_> = names().collect();
|
||||||
|
names.sort_unstable();
|
||||||
|
names.dedup();
|
||||||
|
assert_eq!(names.len(), PRESETS.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presets_are_found_by_name_and_nothing_else() {
|
||||||
|
assert_eq!(preset("google"), Some(GOOGLE));
|
||||||
|
assert_eq!(preset("Google"), None);
|
||||||
|
assert_eq!(preset(""), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_preset_differs_from_every_other() {
|
||||||
|
for (i, a) in PRESETS.iter().enumerate() {
|
||||||
|
for b in &PRESETS[i + 1..] {
|
||||||
|
let same = Style { name: a.name, ..*b };
|
||||||
|
assert_ne!(*a, same, "{} and {} lay out identically", a.name, b.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,686 @@
|
|||||||
|
//! The named styles (`vlog_formatter::style`): one test per layout switch,
|
||||||
|
//! each flipping that switch alone on top of the default, then every preset
|
||||||
|
//! on one module.
|
||||||
|
//!
|
||||||
|
//! Every switch only moves whitespace, so each test also asserts the two
|
||||||
|
//! properties that matter more than the layout itself: the output is a fixed
|
||||||
|
//! point under the same style, and the default never moves a byte.
|
||||||
|
|
||||||
|
use vlog_formatter::style::{self, Alignment, ListIndent, Placement, PortLists, Style};
|
||||||
|
use vlog_formatter::{
|
||||||
|
format_range, format_selection, format_source, resolve_style, Config, LineRanges,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn format(src: &str, style: Style) -> String {
|
||||||
|
let out = format_source(src, &Config::styled(style)).expect("formats");
|
||||||
|
let again = format_source(&out, &Config::styled(style)).expect("formats again");
|
||||||
|
assert_eq!(again, out, "not a fixed point under `{}`", style.name);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The default with one switch changed.
|
||||||
|
fn with(change: impl FnOnce(&mut Style)) -> Style {
|
||||||
|
let mut style = style::LUCISV;
|
||||||
|
style.name = "test";
|
||||||
|
change(&mut style);
|
||||||
|
style
|
||||||
|
}
|
||||||
|
|
||||||
|
const BRANCHES: &str = "\
|
||||||
|
module m;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (a) begin
|
||||||
|
x <= 1;
|
||||||
|
end else if (b) begin
|
||||||
|
x <= 2;
|
||||||
|
end else begin
|
||||||
|
x <= 3;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
always_comb begin
|
||||||
|
case (s)
|
||||||
|
0: begin
|
||||||
|
y = 1;
|
||||||
|
end
|
||||||
|
default: y = 0;
|
||||||
|
endcase
|
||||||
|
end
|
||||||
|
if (G) begin : gen_a
|
||||||
|
assign z = 1;
|
||||||
|
end else begin : gen_b
|
||||||
|
assign z = 0;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn begin_on_its_own_line_leaves_case_items_alone() {
|
||||||
|
let out = format(BRANCHES, with(|s| s.begin = Placement::OwnLine));
|
||||||
|
assert_eq!(
|
||||||
|
out,
|
||||||
|
"\
|
||||||
|
module m;
|
||||||
|
always_ff @(posedge clk)
|
||||||
|
begin
|
||||||
|
if (a)
|
||||||
|
begin
|
||||||
|
x <= 1;
|
||||||
|
end else if (b)
|
||||||
|
begin
|
||||||
|
x <= 2;
|
||||||
|
end else
|
||||||
|
begin
|
||||||
|
x <= 3;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
always_comb
|
||||||
|
begin
|
||||||
|
case (s)
|
||||||
|
0: begin
|
||||||
|
y = 1;
|
||||||
|
end
|
||||||
|
default: y = 0;
|
||||||
|
endcase
|
||||||
|
end
|
||||||
|
if (G)
|
||||||
|
begin : gen_a
|
||||||
|
assign z = 1;
|
||||||
|
end else
|
||||||
|
begin : gen_b
|
||||||
|
assign z = 0;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn else_on_its_own_line() {
|
||||||
|
let out = format(BRANCHES, with(|s| s.else_keyword = Placement::OwnLine));
|
||||||
|
assert_eq!(
|
||||||
|
out,
|
||||||
|
"\
|
||||||
|
module m;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (a) begin
|
||||||
|
x <= 1;
|
||||||
|
end
|
||||||
|
else if (b) begin
|
||||||
|
x <= 2;
|
||||||
|
end
|
||||||
|
else begin
|
||||||
|
x <= 3;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
always_comb begin
|
||||||
|
case (s)
|
||||||
|
0: begin
|
||||||
|
y = 1;
|
||||||
|
end
|
||||||
|
default: y = 0;
|
||||||
|
endcase
|
||||||
|
end
|
||||||
|
if (G) begin : gen_a
|
||||||
|
assign z = 1;
|
||||||
|
end
|
||||||
|
else begin : gen_b
|
||||||
|
assign z = 0;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allman_is_both_switches_together() {
|
||||||
|
let allman = with(|s| {
|
||||||
|
s.begin = Placement::OwnLine;
|
||||||
|
s.else_keyword = Placement::OwnLine;
|
||||||
|
});
|
||||||
|
let src = "module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n";
|
||||||
|
assert_eq!(
|
||||||
|
format(src, allman),
|
||||||
|
"\
|
||||||
|
module m;
|
||||||
|
initial
|
||||||
|
if (a)
|
||||||
|
begin
|
||||||
|
x = 1;
|
||||||
|
end
|
||||||
|
else
|
||||||
|
begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A comment written before `begin` or before `else` stays exactly where it
|
||||||
|
/// was in the token stream, whichever line the keyword moves to.
|
||||||
|
#[test]
|
||||||
|
fn comments_around_moved_keywords_stay_put() {
|
||||||
|
let src = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
if (a) /* why */ begin
|
||||||
|
x = 1;
|
||||||
|
end
|
||||||
|
// otherwise
|
||||||
|
else begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let allman = with(|s| {
|
||||||
|
s.begin = Placement::OwnLine;
|
||||||
|
s.else_keyword = Placement::OwnLine;
|
||||||
|
});
|
||||||
|
let out = format(src, allman);
|
||||||
|
assert!(out.contains("if (a)\n /* why */\n begin"), "{out}");
|
||||||
|
assert!(out.contains("end\n // otherwise\n else\n begin"), "{out}");
|
||||||
|
// And back: the default puts every keyword where it always did.
|
||||||
|
assert_eq!(format(&out, style::LUCISV), format(src, style::LUCISV));
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEADER: &str = "\
|
||||||
|
module m #(parameter int W = 8) (input logic clk, output logic [W-1:0] q);
|
||||||
|
sub #(.W(W)) u_sub (.clk(clk), .q(q));
|
||||||
|
sub #(8) u_pos (clk, q);
|
||||||
|
sub u_wild (.*);
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_port_per_line_breaks_headers_and_named_lists_only() {
|
||||||
|
let out = format(HEADER, with(|s| s.port_lists = PortLists::OnePerLine));
|
||||||
|
assert_eq!(
|
||||||
|
out,
|
||||||
|
"\
|
||||||
|
module m #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk(clk),
|
||||||
|
.q(q)
|
||||||
|
);
|
||||||
|
sub #(8) u_pos (clk, q);
|
||||||
|
sub u_wild (
|
||||||
|
.*
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
// An empty list has nothing to break.
|
||||||
|
let empty = "module m ();\nendmodule\n";
|
||||||
|
assert_eq!(format(empty, with(|s| s.port_lists = PortLists::OnePerLine)), empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrapped_list_indents_its_entries_two_levels() {
|
||||||
|
let style = with(|s| {
|
||||||
|
s.port_lists = PortLists::OnePerLine;
|
||||||
|
s.list_indent = ListIndent::Wrap;
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
format(HEADER, style),
|
||||||
|
"\
|
||||||
|
module m #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk(clk),
|
||||||
|
.q(q)
|
||||||
|
);
|
||||||
|
sub #(8) u_pos (clk, q);
|
||||||
|
sub u_wild (
|
||||||
|
.*
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
// Wrap alone changes only lists that break anyway.
|
||||||
|
assert_eq!(
|
||||||
|
format(HEADER, with(|s| s.list_indent = ListIndent::Wrap)),
|
||||||
|
format(HEADER, style::LUCISV)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Written without a single padding space, so the default keeps it flush.
|
||||||
|
const FLUSH: &str = "\
|
||||||
|
module m (input logic clk, input logic [7:0] data, output logic valid);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
sub u_sub (.clk(clk), .data_in(data), .v(valid));
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn always_aligned_pads_ports_parameters_and_connections() {
|
||||||
|
// The default reads the source and keeps this flush...
|
||||||
|
assert_eq!(format(FLUSH, style::LUCISV), FLUSH);
|
||||||
|
// ...and `Always` aligns it, which breaks the lists: a column only means
|
||||||
|
// anything one entry per line.
|
||||||
|
assert_eq!(
|
||||||
|
format(FLUSH, with(|s| s.alignment = Alignment::Always)),
|
||||||
|
"\
|
||||||
|
module m (
|
||||||
|
input logic clk,
|
||||||
|
input logic [7:0] data,
|
||||||
|
output logic valid
|
||||||
|
);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
sub u_sub (
|
||||||
|
.clk (clk),
|
||||||
|
.data_in (data),
|
||||||
|
.v (valid)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn always_aligned_still_refuses_what_alignment_cannot_do() {
|
||||||
|
let always = with(|s| s.alignment = Alignment::Always);
|
||||||
|
// Nothing to pad: every row is the same width.
|
||||||
|
let same = "module m;\n localparam int A = 1;\n localparam int B = 2;\nendmodule\n";
|
||||||
|
assert_eq!(format(same, always), same);
|
||||||
|
// Too wide for the line: the whole group stays flush.
|
||||||
|
let wide = with(|s| {
|
||||||
|
s.alignment = Alignment::Always;
|
||||||
|
s.line_length = 40;
|
||||||
|
});
|
||||||
|
let src = "module m;\n localparam int A = 32'hFFFF_FFFF;\n localparam int LONGER_NAME_HERE = 2;\nendmodule\n";
|
||||||
|
assert_eq!(format(src, wide), src);
|
||||||
|
// A blank line still splits two tables.
|
||||||
|
let two = "module m;\n localparam int A = 1;\n\n localparam int LONGER = 2;\nendmodule\n";
|
||||||
|
assert_eq!(format(two, always), two);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One module touching every switch, through every preset.
|
||||||
|
const SAMPLE: &str = "\
|
||||||
|
module top #(parameter int W = 8) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (d == 0) begin
|
||||||
|
q <= '0;
|
||||||
|
end else begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_lucisv_preset_is_the_default() {
|
||||||
|
assert_eq!(style::preset("lucisv"), Some(style::LUCISV));
|
||||||
|
let default = Config::default();
|
||||||
|
let lucisv = Config::styled(style::LUCISV);
|
||||||
|
assert_eq!((default.max_width, default.indent_width), (lucisv.max_width, lucisv.indent_width));
|
||||||
|
assert_eq!(default.style, lucisv.style);
|
||||||
|
assert!(!default.uvm_utils_indent);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_preset_formats_the_sample() {
|
||||||
|
let expected = [
|
||||||
|
(
|
||||||
|
"lucisv",
|
||||||
|
"\
|
||||||
|
module top #(parameter int W = 8) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (d == 0) begin
|
||||||
|
q <= '0;
|
||||||
|
end else begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"google",
|
||||||
|
"\
|
||||||
|
module top #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
input logic [W-1:0] d,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (d == 0) begin
|
||||||
|
q <= '0;
|
||||||
|
end else begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk(clk),
|
||||||
|
.data_in(d)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"lowrisc",
|
||||||
|
"\
|
||||||
|
module top #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
input logic [W-1:0] d,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (d == 0) begin
|
||||||
|
q <= '0;
|
||||||
|
end else begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk (clk),
|
||||||
|
.data_in (d)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"ansi",
|
||||||
|
"\
|
||||||
|
module top #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk)
|
||||||
|
begin
|
||||||
|
if (d == 0)
|
||||||
|
begin
|
||||||
|
q <= '0;
|
||||||
|
end
|
||||||
|
else
|
||||||
|
begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"microsoft",
|
||||||
|
"\
|
||||||
|
module top #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
input logic [W-1:0] d,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk)
|
||||||
|
begin
|
||||||
|
if (d == 0)
|
||||||
|
begin
|
||||||
|
q <= '0;
|
||||||
|
end
|
||||||
|
else
|
||||||
|
begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk(clk),
|
||||||
|
.data_in(d)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"nxp",
|
||||||
|
"\
|
||||||
|
module top #(
|
||||||
|
parameter int W = 8
|
||||||
|
) (
|
||||||
|
input logic clk,
|
||||||
|
input logic [W-1:0] d,
|
||||||
|
output logic [W-1:0] q
|
||||||
|
);
|
||||||
|
localparam int A = 1;
|
||||||
|
localparam int LONGER = 22;
|
||||||
|
always_ff @(posedge clk) begin
|
||||||
|
if (d == 0) begin
|
||||||
|
q <= '0;
|
||||||
|
end
|
||||||
|
else begin
|
||||||
|
q <= d;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
sub #(
|
||||||
|
.W(W)
|
||||||
|
) u_sub (
|
||||||
|
.clk (clk),
|
||||||
|
.data_in (d)
|
||||||
|
);
|
||||||
|
endmodule
|
||||||
|
",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
assert_eq!(expected.len(), style::PRESETS.len());
|
||||||
|
for (name, want) in expected {
|
||||||
|
let preset = style::preset(name).expect("a preset");
|
||||||
|
assert_eq!(format(SAMPLE, preset), want, "preset `{name}`");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formatting with A, then B, then A again lands where A alone did, for
|
||||||
|
/// every pair — except where A *reads* the source's spacing (`Infer`) and B
|
||||||
|
/// wrote columns into it, which A then faithfully keeps.
|
||||||
|
#[test]
|
||||||
|
fn a_round_trip_through_another_preset_comes_back() {
|
||||||
|
for a in style::PRESETS {
|
||||||
|
let once = format(SAMPLE, a);
|
||||||
|
for b in style::PRESETS {
|
||||||
|
let back = format(&format(&once, b), a);
|
||||||
|
if a.alignment == Alignment::Infer && b.alignment == Alignment::Always {
|
||||||
|
// The columns B wrote are now the author's; A keeps them.
|
||||||
|
assert_eq!(back, format(&format(SAMPLE, b), a), "{} via {}", a.name, b.name);
|
||||||
|
} else {
|
||||||
|
assert_eq!(back, once, "{} via {}", a.name, b.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `--lines` and an editor selection lay their constructs out in the style
|
||||||
|
/// and leave every other byte exactly as written.
|
||||||
|
#[test]
|
||||||
|
fn range_and_selection_formatting_follow_the_style() {
|
||||||
|
let src = "\
|
||||||
|
module m;
|
||||||
|
always_comb if (a) begin x = 1; end
|
||||||
|
always_comb if (b) begin y = 1; end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let ansi = Config::styled(style::ANSI);
|
||||||
|
let lines = LineRanges::parse("2").expect("a range");
|
||||||
|
let want = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
if (a)
|
||||||
|
begin
|
||||||
|
x = 1;
|
||||||
|
end
|
||||||
|
always_comb if (b) begin y = 1; end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
assert_eq!(format_range(src, &ansi, &lines).expect("formats"), want);
|
||||||
|
let selected = format_selection(src, &ansi, &lines).expect("formats");
|
||||||
|
assert!(selected.contains("\n always_comb\n if (a)\n begin\n"), "{selected}");
|
||||||
|
assert!(selected.ends_with(" always_comb if (b) begin y = 1; end\nendmodule\n"), "{selected}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auto() -> Config {
|
||||||
|
Config::named("auto").expect("auto is a style")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_auto(src: &str) -> String {
|
||||||
|
let out = format_source(src, &auto()).expect("formats");
|
||||||
|
assert_eq!(format_source(&out, &auto()).expect("formats again"), out, "auto is idempotent");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_keeps_each_file_in_the_layout_it_already_has() {
|
||||||
|
// Written Allman: auto keeps `begin` and `else` on their own lines...
|
||||||
|
let allman = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
if (a)
|
||||||
|
begin
|
||||||
|
x = 1;
|
||||||
|
end
|
||||||
|
else
|
||||||
|
begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
assert_eq!(format_auto(allman), allman);
|
||||||
|
assert_eq!(resolve_style(allman, &auto()).style.begin, Placement::OwnLine);
|
||||||
|
// ...and cuddled stays cuddled, which is also what the default does.
|
||||||
|
let cuddled = format(allman, style::LUCISV);
|
||||||
|
assert_eq!(format_auto(&cuddled), cuddled);
|
||||||
|
assert_eq!(resolve_style(&cuddled, &auto()).style, style::LUCISV);
|
||||||
|
// A messy file moves to the nearest preset, not to an arbitrary one.
|
||||||
|
let messy = "module m;\n always_comb\n if (a)\n begin x = 1; end\n else\n begin x = 2; end\nendmodule\n";
|
||||||
|
assert_eq!(format_auto(messy), allman);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_picks_a_layout_never_a_size() {
|
||||||
|
// An Allman file at 4 spaces keeps auto's 2: indent is the config's, and
|
||||||
|
// auto only ever picks among layouts at that indent.
|
||||||
|
let wide = format(BRANCHES, style::ANSI);
|
||||||
|
let chosen = resolve_style(&wide, &auto());
|
||||||
|
assert_eq!((chosen.indent_width, chosen.max_width), (2, 100));
|
||||||
|
let four = Config { indent_width: 4, ..auto() };
|
||||||
|
assert_eq!(resolve_style(&wide, &four).style.begin, Placement::OwnLine);
|
||||||
|
let out = format_source(&wide, &four).expect("formats");
|
||||||
|
assert_eq!(out, wide, "with indent 4 configured, the ansi file is already formatted");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_with_nothing_to_tell_the_presets_apart_is_the_default() {
|
||||||
|
let plain = "module m;\n assign a = b;\nendmodule\n";
|
||||||
|
assert_eq!(format_auto(plain), plain);
|
||||||
|
assert_eq!(resolve_style(plain, &auto()).style, style::LUCISV);
|
||||||
|
assert_eq!(auto().style_name(), "auto");
|
||||||
|
assert!(!resolve_style(plain, &auto()).auto_style);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A range under auto lays its lines out in the style of the whole file, so
|
||||||
|
/// a selection in an Allman file comes out Allman even when the selected
|
||||||
|
/// lines themselves were written cuddled.
|
||||||
|
#[test]
|
||||||
|
fn auto_ranges_take_the_whole_files_style() {
|
||||||
|
let src = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
begin
|
||||||
|
if (a)
|
||||||
|
begin
|
||||||
|
x = 1;
|
||||||
|
end
|
||||||
|
else
|
||||||
|
begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
always_comb if (b) begin y = 1; end
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let lines = LineRanges::parse("13").expect("a range");
|
||||||
|
let out = format_range(src, &auto(), &lines).expect("formats");
|
||||||
|
assert!(
|
||||||
|
out.ends_with(" always_comb\n if (b)\n begin\n y = 1;\n end\nendmodule\n"),
|
||||||
|
"{out}"
|
||||||
|
);
|
||||||
|
let selected = format_selection(src, &auto(), &lines).expect("formats");
|
||||||
|
assert_eq!(selected, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Google's "Eschatology" and lowRISC's "Begin / End": `end else begin` on
|
||||||
|
/// one line, except after a labelled `end`, where `else` starts a new line.
|
||||||
|
#[test]
|
||||||
|
fn else_after_a_labelled_end_starts_its_own_line_in_the_guides() {
|
||||||
|
let src = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
if (a) begin : l1
|
||||||
|
x = 1;
|
||||||
|
end : l1 else begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
if (G) begin : g1
|
||||||
|
assign z = 1;
|
||||||
|
end : g1 else begin : g2
|
||||||
|
assign z = 0;
|
||||||
|
end : g2
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
let guide = "\
|
||||||
|
module m;
|
||||||
|
always_comb
|
||||||
|
if (a) begin : l1
|
||||||
|
x = 1;
|
||||||
|
end : l1
|
||||||
|
else begin
|
||||||
|
x = 2;
|
||||||
|
end
|
||||||
|
if (G) begin : g1
|
||||||
|
assign z = 1;
|
||||||
|
end : g1
|
||||||
|
else begin : g2
|
||||||
|
assign z = 0;
|
||||||
|
end : g2
|
||||||
|
endmodule
|
||||||
|
";
|
||||||
|
assert_eq!(format(src, style::GOOGLE), guide);
|
||||||
|
assert_eq!(format(src, style::LOWRISC), guide);
|
||||||
|
// The default keeps what it always printed.
|
||||||
|
assert_eq!(format(src, style::LUCISV), src);
|
||||||
|
// And an unlabelled `end` still cuddles in the guides.
|
||||||
|
let plain = format(BRANCHES, style::GOOGLE);
|
||||||
|
assert!(plain.contains(" end else if (b) begin\n"), "{plain}");
|
||||||
|
}
|
||||||
@@ -0,0 +1,953 @@
|
|||||||
|
# format-styles
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Let a project pick a house layout by name instead of living with lucisv's
|
||||||
|
one: `[format] style = "<name>"` in `lucisv.toml`, `--style <name>` on the
|
||||||
|
command line, and a `lucisv.format.style` drop-down in VS Code. The owner
|
||||||
|
asked for the formatter to "adapt to the current file's way of handling when
|
||||||
|
to start newline / what to group / how to align the ports", with a drop-down
|
||||||
|
of common styles (ANSI, Google, Microsoft, NXP) as the fallback if adapting
|
||||||
|
is too ambiguous, and for the rules to be easy to read in the source. So
|
||||||
|
this ships both: six named presets, each one row of a table in
|
||||||
|
`crates/vlog_formatter/src/style.rs`, and `auto`, which lays each file out in
|
||||||
|
the preset it is already closest to. The default, `lucisv`, is byte-for-byte
|
||||||
|
the layout every earlier release produced — proven over the corpus and
|
||||||
|
OpenTitan, not asserted.
|
||||||
|
|
||||||
|
## Assumptions
|
||||||
|
|
||||||
|
- **A style only moves whitespace.** Every switch chooses between a space and
|
||||||
|
a line break in front of a token, a deeper or shallower indent, or padding.
|
||||||
|
The token stream is identical under every style, which is why `verify.rs`
|
||||||
|
is untouched (CLAUDE.md invariant 4: nothing was widened).
|
||||||
|
- **An explicit `indent`/`line-length` beats the preset's**, from whichever
|
||||||
|
rung it came. A preset is a starting point; a number someone wrote down is a
|
||||||
|
decision. `--style ansi` with a `lucisv.toml` that says `indent = 2` is ANSI
|
||||||
|
at 2 spaces.
|
||||||
|
- **`lucisv` and `auto` do not count as "a chosen style" for the editor's
|
||||||
|
`tabSize` rung.** VS Code sends `lucisv` when nobody touched the drop-down,
|
||||||
|
and `auto` picks a layout but no size, so both leave today's
|
||||||
|
`tabSize`-beats-default behaviour exactly as it was. Any other style
|
||||||
|
outranks `tabSize` (an editor default of 4 must not silently undo
|
||||||
|
`google`'s 2).
|
||||||
|
- **`case` items and `do` keep `begin` on their own line's end in every
|
||||||
|
style** — `0: begin`, `do begin`. clang-format's Microsoft style does the
|
||||||
|
same (`AfterCaseLabel: false`), and an Allman `0:` / `begin` reads as a
|
||||||
|
label with nothing under it.
|
||||||
|
- **The `else` switches govern `if`/`else` statements and generate `if`/`else`
|
||||||
|
only.** An immediate assertion's `else` (`assert (a) … else …`), a
|
||||||
|
constraint's `else` and `randsequence`'s keep the layout they always had.
|
||||||
|
`else_after_label` is the guides' one exception: after `end : label`,
|
||||||
|
`google` and `lowrisc` start `else` on a new line (Google "Eschatology",
|
||||||
|
lowRISC "Begin / End"); `lucisv` keeps `end : l1 else begin`, as it always
|
||||||
|
printed.
|
||||||
|
- **"One entry per line" governs module/interface/program headers (parameter
|
||||||
|
and port lists, whenever non-empty) and instances' *named* parameter and
|
||||||
|
connection lists.** A positional override `#(16)` and an ordered connection
|
||||||
|
list `(a, b)` keep fitting on one line, as both guides show. `(.*)` alone
|
||||||
|
is broken like any other named list.
|
||||||
|
- **`Wrap` (two-level list indent) applies to the same lists**, header and
|
||||||
|
instance; function/task port lists and expression lists are untouched.
|
||||||
|
- **`Alignment::Always` reuses the alignment planner unchanged** except for
|
||||||
|
one question it skips — "did the author pad this?". Every other refusal
|
||||||
|
(a group of one, nothing to pad, a group too wide for the line, a row with
|
||||||
|
a comment in it, a blank line or comment between tables) still applies.
|
||||||
|
Its connection spelling is Verible's (`.clk (clk)`, one space before the
|
||||||
|
widest row's `(`); lowRISC's guide writes the widest row tight
|
||||||
|
(`.req_ready_o(req_ready)`). Not modelled: one more axis for one guide's
|
||||||
|
one column. A second lowRISC deviation: a comment line inside a table ends
|
||||||
|
lucisv's alignment group (both layouts are fixed points only because the
|
||||||
|
groups are drawn the same on every pass), where lowRISC keeps aligning
|
||||||
|
across it.
|
||||||
|
- **Known limit — a declaration of several instances under `OnePerLine`.**
|
||||||
|
`p1 u8 (.a(a)), u9 (.a(b));` breaks into the hanging layout every style
|
||||||
|
has always used for several instances: under `google` the connections land
|
||||||
|
at 8, `u9` and each `)` at 4, the opening line at 2 (`microsoft`: 4/12/8).
|
||||||
|
The `)` of each instance is at its instance's column, not the opening
|
||||||
|
line's. Fixing it means a new multi-instance layout for every style, the
|
||||||
|
default included; not done here.
|
||||||
|
- **`auto` never guesses an indent or a width.** It competes the presets'
|
||||||
|
layout switches at the config's own indent and width. Guessing an indent
|
||||||
|
from a file whose formatted output has a different indent is exactly the
|
||||||
|
kind of detector whose second run disagrees with its first. Its measure is
|
||||||
|
the number of lines whose bytes change, indentation included — see
|
||||||
|
"auto" below for why the first round's indentation-blind measure was wrong.
|
||||||
|
- **Under `auto`, a buffer that does not parse and has no remembered preset
|
||||||
|
is laid out in the default (`lucisv`) layout** by range, selection and
|
||||||
|
on-type formatting — the formatter has nothing to resolve from. The
|
||||||
|
language server remembers the preset of each recently formatted document
|
||||||
|
(the 64 most recent), so this only happens before the first successful
|
||||||
|
resolve of a buffer. The CLI's `--lines` has no memory and refuses a file
|
||||||
|
that does not parse anyway.
|
||||||
|
|
||||||
|
## The axes
|
||||||
|
|
||||||
|
Surveyed against what `format/` actually decides today (2026-11-19):
|
||||||
|
|
||||||
|
| candidate | verdict | why |
|
||||||
|
|---|---|---|
|
||||||
|
| indent width | **kept** (`indent`) | already a `Config` field; a preset supplies the default |
|
||||||
|
| line length | **kept** (`line_length`) | same |
|
||||||
|
| `begin` same line / own line | **kept** (`begin`) | one choke point (`Fmt::body_after`, `Fmt::gen_block`): a space or a `HardLine` before `begin` |
|
||||||
|
| `else` after `end` | **kept** (`else_keyword`) | one condition in `if_stmt` and in `gen_if` |
|
||||||
|
| `else` after a labelled `end` | **kept** (`else_after_label`) | the same condition, asked of `end : label` — both guides' exception |
|
||||||
|
| header/connection lists: fit vs one per line | **kept** (`port_lists`) | the lists already had a `force_break` flag (`Fmt::style_breaks`) |
|
||||||
|
| list entries at 1 or 2 levels | **kept** (`list_indent`) | Google's guide and Verible's `wrap` both indent header lists 4; one `Indent` more in `delimited_at`, and the alignment budget follows (`Fmt::list_depth`) |
|
||||||
|
| alignment of ports, connections, `parameter`s | **kept** (`alignment`: `Infer` / `Always`) | one skipped question in `align::plan`; `Never` was dropped — no preset needed it |
|
||||||
|
| closing `);` hugging the last port | rejected | no guide wants it; every guide found puts `)` on its own line |
|
||||||
|
| space before `(` in instances / calls | rejected | every source agrees: space after the instance name, none after a function name — already lucisv's |
|
||||||
|
| spaces around `:` in ranges | rejected | both guides want `[7:0]` tight — already lucisv's |
|
||||||
|
| consecutive blank lines kept | rejected | the parser records `blank_before: bool`, not a count; would need a parser change outside this lane, and no guide asks for more than one |
|
||||||
|
| `case` item indentation | rejected | both guides indent items one level — already lucisv's |
|
||||||
|
| net/variable declaration alignment, assignment alignment | rejected | lucisv has no such alignment group today; building one is a feature of its own, not a style switch |
|
||||||
|
|
||||||
|
## The presets
|
||||||
|
|
||||||
|
The same table is the `PRESETS` constant in `style.rs`, one row per preset.
|
||||||
|
|
||||||
|
| style | indent | width | `begin` | `else` | `else` after `end : l` | lists | list indent | columns | modelled on | confidence |
|
||||||
|
|---|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
| `lucisv` | 2 | 100 | same line | same line | same line | fit | block | infer | lucisv itself | exact (byte identity) |
|
||||||
|
| `google` | 2 | 100 | same line | same line | own line | one per line | wrap | infer | Google Verilog Style Guide | high |
|
||||||
|
| `lowrisc` | 2 | 100 | same line | same line | own line | one per line | block | always | lowRISC Verilog Coding Style Guide | high (two deviations, above) |
|
||||||
|
| `ansi` | 4 | 80 | own line | own line | own line | fit | block | infer | Artistic Style / iStyle `--style=ansi` (Allman) | medium for `begin`/`else`; width a guess |
|
||||||
|
| `microsoft` | 4 | 120 | own line | own line | own line | one per line | block | infer | clang-format `Microsoft` base style | guess |
|
||||||
|
| `nxp` | 2 | 80 | same line | own line | own line | one per line | block | always | a conservative RTL house style | guess |
|
||||||
|
|
||||||
|
Sources consulted (2026-11-19):
|
||||||
|
|
||||||
|
- **Google Verilog Style Guide** (google.github.io/styleguide/verilogguide.html,
|
||||||
|
read from the `google/styleguide` gh-pages `verilogguide.md`): "Line
|
||||||
|
Length" (100), "Indentation" (2, no tabs), "Eschatology" (`begin` on the
|
||||||
|
keyword's line, `end else begin`, but `else` on a new line after a labelled
|
||||||
|
`end`), "Line Wrapping" (4-space continuation),
|
||||||
|
"Module Header Definition Examples" and "Use named ports" (one entry per
|
||||||
|
line, entries at 4 spaces, closing paren at column zero), "Tabular
|
||||||
|
Alignment" (alignment *recommended* "where it is reasonable"; the guide's
|
||||||
|
own header examples are not name-aligned — hence `infer`).
|
||||||
|
- **lowRISC Verilog Coding Style Guide** (lowRISC/style-guides,
|
||||||
|
VerilogCodingStyle.md), whose summary says it defaults to "being consistent
|
||||||
|
with Google's C++ Style Guide": "Line Length" 100, "Indentation" 2,
|
||||||
|
"Begin / End" `end else begin` (and the same labelled-`end` exception),
|
||||||
|
"Module Declaration" one port per line, `);` at column zero, its examples
|
||||||
|
aligned in columns (shown, not required), "Module Instantiation"
|
||||||
|
connections *required* "aligned in tabular style", at 2 spaces. lucisv has
|
||||||
|
one alignment switch for ports, connections and parameters, so the row
|
||||||
|
says `always` for all three: the requirement for connections, the examples
|
||||||
|
for ports.
|
||||||
|
- **ANSI**: the iStyle Verilog formatter's README (a port of Artistic Style)
|
||||||
|
lists `--style=ansi` and describes its bracket-breaking mode as "ANSI C/C++
|
||||||
|
style", default indent 4. No Verilog guide by that name exists that we
|
||||||
|
found; 80 columns is our guess.
|
||||||
|
- **Microsoft**: no Microsoft Verilog/SystemVerilog guide found. clang-format's
|
||||||
|
`getMicrosoftStyle` (llvm-project `clang/lib/Format/Format.cpp`):
|
||||||
|
`ColumnLimit = 120`, `IndentWidth = 4`, braces after control statements and
|
||||||
|
before `else` on their own lines; LLVM's base sets
|
||||||
|
`VerilogBreakBetweenInstancePorts = true`. Whether clang-format's own
|
||||||
|
Verilog mode wraps `begin` like a brace was not verified.
|
||||||
|
- **NXP**: no public NXP Verilog style guide found (searched 2026-11-19).
|
||||||
|
The preset is lucisv's guess at a conservative ASIC house style, and the
|
||||||
|
source and the docs say so.
|
||||||
|
|
||||||
|
## Safety sweeps
|
||||||
|
|
||||||
|
Trees: the 860-file corpus (`~/.cache/lucisv-corpus`) and OpenTitan's `hw/`
|
||||||
|
(`~/.cache/lucisv-opentitan-full/hw`, 4 061 files with symlinks followed) —
|
||||||
|
4 921 `.v`/`.sv`/`.vh`/`.svh` files, copied to scratch (the trees are never
|
||||||
|
written). Commands: `tools/style_sweep.sh -b <lucisv> -w <scratch> <trees>`
|
||||||
|
(the CLI, in place, `--no-cache --no-config --no-gitignore`, every run under
|
||||||
|
`tools/guard.sh`) and `cargo run --release -p vlog_formatter --example
|
||||||
|
auto_sweep -- <trees>` (under `guard.sh`). 2026-11-19, final binaries.
|
||||||
|
|
||||||
|
**Default byte identity.** Both trees formatted with the 0.65.4 binary
|
||||||
|
(`d574969`, built before any edit) and with this lane's binary, no flag and
|
||||||
|
`--style lucisv`: `diff -r` is empty both ways (0 lines over 4 921 files;
|
||||||
|
identical summaries, 4 817 reformatted / 90 unchanged / 14 failed, the 14 the
|
||||||
|
same parse errors). The snapshot + idempotency suite is unchanged and green.
|
||||||
|
|
||||||
|
| style | files | parse errors | verification errors | crashes | not idempotent |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `lucisv` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `google` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `lowrisc` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `ansi` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `microsoft` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `nxp` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
| `auto` | 4 921 | 14 | 0 | 0 | 0 |
|
||||||
|
|
||||||
|
"Not idempotent" is `--check` with the same style over the formatted copy
|
||||||
|
(files it would reformat). The 14 parse errors are the baseline's own, under
|
||||||
|
every style.
|
||||||
|
|
||||||
|
**`auto` proof sweep** (`auto_sweep`, fix-round binary): 4 921 files, 14
|
||||||
|
refused (the parse errors), 0 crashes, **0 files whose second or third auto
|
||||||
|
format changed a byte, 0 files whose second or third run named a different
|
||||||
|
preset**. Picked: `lucisv` 4 050, `lowrisc` 645, `google` 92, `microsoft` 92,
|
||||||
|
`nxp` 24, `ansi` 4. (First round, indentation-blind measure: `lucisv` 3 875,
|
||||||
|
`lowrisc` 484, `google` 465, `microsoft` 46, `nxp` 29, `ansi` 8; before
|
||||||
|
`canonical` existed that sweep showed 47 renames, all `lowrisc` → `lucisv`,
|
||||||
|
identical bytes.)
|
||||||
|
|
||||||
|
**Cost of `auto`**: see the latency table under "auto".
|
||||||
|
|
||||||
|
The tables above are from the fix-round binaries (2026-11-19): the per-style
|
||||||
|
table, the default byte identity and the cross-preset matrix below were all
|
||||||
|
re-run after the fix round and came out the same, except the `auto` row of
|
||||||
|
the matrix.
|
||||||
|
|
||||||
|
## auto
|
||||||
|
|
||||||
|
**The measure.** `auto` formats the file with every preset (at the
|
||||||
|
configured indent and width) and keeps the output with the fewest lines whose
|
||||||
|
bytes change — the multiset difference of lines, **indentation included** —
|
||||||
|
ties to the earlier preset. The first round compared lines with indentation
|
||||||
|
stripped and used indentation only to break ties; QA showed that lets a
|
||||||
|
preset that saves three layout lines beat one that keeps 741 lines'
|
||||||
|
indentation (F1). Counting every changed line is also simply what the docs
|
||||||
|
always said.
|
||||||
|
|
||||||
|
**`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). (In VS Code the editor's `tabSize` rung supplies the
|
||||||
|
indent when nothing else does, which often matches the file; the CLI has no
|
||||||
|
such rung.) QA measured that 426 of the 4 921 files' auto output changed
|
||||||
|
between the two measures.
|
||||||
|
|
||||||
|
**F1 experiment** (QA's driver, `qa_auto edit`, rebuilt against this tree):
|
||||||
|
200 sampled files (198 with an `endmodule`), each formatted with auto, one
|
||||||
|
construct inserted before `endmodule`, formatted with auto again. "Flips":
|
||||||
|
the named preset changed; "rewritten": lines of the first output no longer
|
||||||
|
present in the second.
|
||||||
|
|
||||||
|
| inserted construct | flips before → after | files with rewritten lines before → after | worst rewrite before → after |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `assign qa_x=qa_y ;` | 0 → 0 | 0 → 0 | 0 → 0 |
|
||||||
|
| cuddled `always_comb if … begin … end else begin … end` | 4 → 0 | 4 → 0 | 741 → 0 |
|
||||||
|
| Allman `begin`/`else` block | 81 → 1 | 21 → 1 | 140 → 3 |
|
||||||
|
| one-line instance `qa_mod qa_u (.a(qa_a), .b(qa_b));` | 14 → 0 | 14 → 0 | 37 → 0 |
|
||||||
|
|
||||||
|
The remaining flip rewrites 3 lines, so no stabiliser beyond the measure was
|
||||||
|
added. ("Before" is QA's run on the first-round binary; "after" re-runs the
|
||||||
|
same driver, so each column starts from its own binary's auto output.) Every
|
||||||
|
second format in both runs was idempotent.
|
||||||
|
|
||||||
|
**Naming costs a pass; formatting does not need it.** `format_source` under
|
||||||
|
auto and `format_auto` (the server's whole-document path) format once per
|
||||||
|
preset until one leaves the file unchanged, and return the winner.
|
||||||
|
`resolve_style`, which *names* the preset, additionally finds the earliest
|
||||||
|
preset that leaves the output as it is (`canonical`), so a second run names
|
||||||
|
the same one; only it pays that pass. Range and selection formatting resolve
|
||||||
|
through the internal `concrete`, which does not name.
|
||||||
|
|
||||||
|
**The server remembers each document's preset** (`lucisv_server/src/
|
||||||
|
auto_style.rs`, owned by the `Server` struct; the 64 most recent documents,
|
||||||
|
no `didClose` hook). Whole-document formatting and the save hook resolve and
|
||||||
|
remember. Range, multi-range and `;` on-type formatting use the remembered
|
||||||
|
preset; with none, they resolve once from the buffer when it parses and
|
||||||
|
remember that; with none and no parse, they use the default layout (F3's
|
||||||
|
case, now confined to a buffer that has never resolved). A typed newline
|
||||||
|
needs no preset and never searches.
|
||||||
|
|
||||||
|
The memory is invalidated (QA R2-1): a document's entry is **forgotten** on
|
||||||
|
`didOpen`, `didClose`, `didRenameFiles` (old and new name),
|
||||||
|
`didDeleteFiles`, and on any request or whole-document format under a named
|
||||||
|
style; **every** entry is forgotten when settings are applied (pushed or
|
||||||
|
pulled) and when a watched-file event names `lucisv.toml`/`.lucisv.toml`. A
|
||||||
|
`didChange` that replaces the whole buffer — rangeless, or one change from
|
||||||
|
the top whose text is the whole result — marks the entry *replaced*: the next
|
||||||
|
request resolves afresh when the buffer parses, and uses the old preset only
|
||||||
|
when it does not (the lead asked for "forget"; marking instead keeps QA's
|
||||||
|
case 8 — a full-sync client's every keystroke is a whole replacement, and
|
||||||
|
forgetting there would drop the preset of a half-typed buffer, the case the
|
||||||
|
memory exists for). QA's `memattack.py`, re-run against this tree's release
|
||||||
|
binaries: cases 1–9 and 11's eviction check OK; case 10 is a request the
|
||||||
|
server rejects as invalid params (`v x.sv`: a raw space is not a valid URI —
|
||||||
|
a driver issue, not the memory); case 11's last check expected the *old*
|
||||||
|
stale preset after a full-text change ("stale by design") and now gets the
|
||||||
|
re-resolved one, which is the R2-1 fix.
|
||||||
|
|
||||||
|
**Latency** on `pinmux_reg_top.sv` (42 192 lines; auto picks `lowrisc`),
|
||||||
|
release, `qa_auto time2`, two runs agreeing within 5 %:
|
||||||
|
|
||||||
|
| request | before (QA) | after |
|
||||||
|
|---|---|---|
|
||||||
|
| whole-document format, unformatted | 2.30 s | 2.40 s (unchanged: it must search) |
|
||||||
|
| selection / on-type `;` on the formatted buffer | 1.36 s | 0.07 s remembered; 1.24 s for the first request with no memory |
|
||||||
|
| selection / on-type `;` on the unformatted buffer | 3.0 s | 0.10 s remembered; 2.55 s for the first request with no memory |
|
||||||
|
| (selection under a named preset, for scale) | 0.094 s | 0.064 s |
|
||||||
|
|
||||||
|
## Cross-preset stability
|
||||||
|
|
||||||
|
Formatting with A, then B, then A again lands exactly where A alone did —
|
||||||
|
`A(B(A(x))) == A(x)` — **for every pair where A aligns by rule
|
||||||
|
(`lowrisc`, `nxp`)**. Where A *reads* alignment from the source (`Infer`:
|
||||||
|
`lucisv`, `google`, `ansi`, `microsoft`), the identity can fail, and for
|
||||||
|
one root cause: B changed which runs are aligned, and A then faithfully keeps
|
||||||
|
what it finds. B either *wrote* columns (B is `Always`) or *dropped* a table
|
||||||
|
whose padded width no longer fit B's narrower line or deeper indent (an
|
||||||
|
aligned group that overflows falls back to flush as a whole) — e.g. `lucisv`
|
||||||
|
via `ansi` (80 columns, 4 spaces), `microsoft` via `lucisv` (100 < 120). Every
|
||||||
|
other decision is a function of the AST and the config, so it comes back.
|
||||||
|
|
||||||
|
The differences are alignment **plus its knock-on**, not alignment alone.
|
||||||
|
QA classified every differing hunk in 20 files per pair (QA log, F5):
|
||||||
|
`microsoft` via `lucisv` and `ansi` via `nxp` are all padding or the list
|
||||||
|
breaks alignment forces; in `lucisv` via `lowrisc`, 261 of 265 hunks are, and
|
||||||
|
the other 4 (18 lines, e.g. `flash_phy_core.sv:230`, `kmac_entropy.sv:297`)
|
||||||
|
are a named parameter override `#(.Width(HashCntW))` that was broken in
|
||||||
|
`lucisv(x)` and comes back joined once its instance's connection list is
|
||||||
|
aligned — the existing coupling between an instance's head and its
|
||||||
|
connection list, set off by the alignment. This is the alignment feature's
|
||||||
|
design — "a file written without alignment never grows any" — not a style
|
||||||
|
bug.
|
||||||
|
|
||||||
|
Measured (files of 4 921 where `A(B(A(x))) != A(x)`; rows A, columns B):
|
||||||
|
|
||||||
|
| A \ B | lucisv | google | lowrisc | ansi | microsoft | nxp | auto |
|
||||||
|
|---|---|---|---|---|---|---|---|
|
||||||
|
| `lucisv` | — | 0 | 1 288 | 106 | 0 | 1 281 | 0 |
|
||||||
|
| `google` | 0 | — | 1 288 | 106 | 0 | 1 281 | 0 |
|
||||||
|
| `lowrisc` | 0 | 0 | — | 0 | 0 | 0 | 0 |
|
||||||
|
| `ansi` | 0 | 0 | 1 244 | — | 0 | 1 244 | 0 |
|
||||||
|
| `microsoft` | 20 | 20 | 1 296 | 119 | — | 1 290 | 20 |
|
||||||
|
| `nxp` | 0 | 0 | 0 | 0 | 0 | — | 0 |
|
||||||
|
| `auto` | 857 | 1 987 | 1 192 | 1 832 | 1 844 | 2 315 | — |
|
||||||
|
|
||||||
|
The `Always` rows are all zero; every non-zero `Infer` cell is in a column
|
||||||
|
that writes columns (`lowrisc`, `nxp`) or is narrower/deeper than the row
|
||||||
|
(`ansi` for the 100-column rows; 100-column `lucisv`/`google`/`auto` for
|
||||||
|
`microsoft`'s 120). The `auto` row is non-zero by definition: auto keeps the
|
||||||
|
layout it finds, and B just changed it — `auto(B(auto(x)))` is `B`'s layout
|
||||||
|
(or the nearest preset to it), which is the feature working. What holds for
|
||||||
|
auto is the idempotency above.
|
||||||
|
|
||||||
|
## Handshakes
|
||||||
|
|
||||||
|
- **Consumes `align::plan`** (own crate): gained a `mode: Alignment`
|
||||||
|
parameter. `Infer` is exactly the old function; the one call site passes
|
||||||
|
the style's mode.
|
||||||
|
- **Promises `vlog_formatter::Config`**: new fields `style: Style` and
|
||||||
|
`auto_style: bool`; `Config::styled(Style)`, `Config::named(&str)`,
|
||||||
|
`Config::style_name()`. `Config::default()` is `Config::styled(LUCISV)` and
|
||||||
|
lays out byte-identically to before. Every external `Config { .., ..Default }`
|
||||||
|
literal keeps compiling.
|
||||||
|
- **Promises `vlog_formatter::resolve_style(source, &Config) -> Config`**: the
|
||||||
|
preset `auto` *names* for a whole file (the canonical one — stable across
|
||||||
|
runs), and **`vlog_formatter::format_auto(source, &Config) ->
|
||||||
|
Result<(String, Style), FormatError>`**: auto's output and the preset that
|
||||||
|
produced it, for a caller that will format ranges of the same buffer
|
||||||
|
later (the server's memory).
|
||||||
|
- **`lucisv_core::config`**: `FileConfig::format_style: Option<&'static str>`,
|
||||||
|
`STYLE_NAMES` (the presets plus `auto`; pinned equal to the formatter's by
|
||||||
|
`args::tests::the_core_style_names_are_the_formatter_presets` in `lucisv`),
|
||||||
|
`parse_style` (the one error message, reused by `--style` and the server).
|
||||||
|
`lucisv_core` still depends on nothing.
|
||||||
|
- **`lucisv_core::cache::Entry`** gained `style: &'static str`; the store line
|
||||||
|
has seven fields (`…\tuvm\tstyle\tversion\tpath`). A six-field line (0.65.x)
|
||||||
|
and a line naming a style this build does not know are dropped
|
||||||
|
individually, like another version's entry. **One edit outside the new
|
||||||
|
test file:** `crates/lucisv/tests/cli.rs`'s `cache_line` helper (which
|
||||||
|
forges store lines) writes the new `lucisv` field — two existing cache
|
||||||
|
tests failed on the old six-field shape otherwise. The lead lifted the
|
||||||
|
ban on that file mid-lane; the edit is two lines.
|
||||||
|
- **Request to the `server-lint`/71.1 lane (`crates/lucisv_server/src/lint.rs`,
|
||||||
|
owned by lane 71.1, not edited here):** `lint.rs:307` resolves the
|
||||||
|
`line-length` rule's width as `file.line_length.or(client.line_length)
|
||||||
|
.unwrap_or(100)`. Under a style with another width (`ansi` 80, `microsoft`
|
||||||
|
120, `nxp` 80) the editor's `line-length` finding and the formatter now
|
||||||
|
disagree. Wanted: fall back to the chosen style's width —
|
||||||
|
`file.format_style.or(client.style).and_then(vlog_formatter::style::preset)
|
||||||
|
.map_or(100, |s| s.line_length)` — the same ladder `format::indent_width`
|
||||||
|
now walks (that one is fixed here, and lint's `tab_width` already calls it).
|
||||||
|
The CLI's `lucisv check` and the MCP `diagnostics` tool already use the
|
||||||
|
style's width.
|
||||||
|
- **Note for the alignment README (not in this lane's scope):** its rule is
|
||||||
|
now the `Infer` mode; `Always` is documented here.
|
||||||
|
- **`editors/vscode/package.json`**: `lucisv.format.style` (enum with one
|
||||||
|
description per entry, default `lucisv`). `extension.js` forwards the whole
|
||||||
|
`lucisv` section already, so it is unchanged.
|
||||||
|
|
||||||
|
- **`crates/lucisv_server/src/server/notification.rs` (lane 71.1's file;
|
||||||
|
allowed by the lead for these lines only, one call each into
|
||||||
|
`auto_style.rs`, nothing else touched):**
|
||||||
|
1. in `handle_notification`, after `let released = self.forget_port_entry(&method, ¬ification);`:
|
||||||
|
`self.auto_styles.notice(¬ification);`
|
||||||
|
2. in the `DidChangeTextDocument` arm, after the `let (text, end) = { … };` block:
|
||||||
|
`self.auto_styles.changed(&uri, &p.content_changes, &text);`
|
||||||
|
3. first line of `apply_settings`: `self.auto_styles.forget_all();`
|
||||||
|
- **`lucisv_core::config::NAMES`** is now `pub` (the two config file names),
|
||||||
|
so the memory recognises a `lucisv.toml` event without a second copy.
|
||||||
|
- **Server (this lane, formatting handlers only):** `auto_style.rs` (new),
|
||||||
|
a field on `Server` (`server/mod.rs`, constructed in `server/startup.rs`),
|
||||||
|
`server/formatting.rs` routing the five entries through it, and
|
||||||
|
`format::whole_document_edit`. Nothing in `state/` or
|
||||||
|
`server/{index,notification,diagnostics}.rs` (lane 71.1's) was touched.
|
||||||
|
|
||||||
|
## Status / TODO
|
||||||
|
|
||||||
|
- [x] Survey the axes; keep five layout switches plus indent and width
|
||||||
|
- [x] `style.rs`: one `Style` struct, six presets as `const` rows, sources in comments
|
||||||
|
- [x] Axes: `begin`, `else`, lists one-per-line, list indent, alignment
|
||||||
|
- [x] `lucisv` preset byte-identical to 0.65.4 over corpus + OpenTitan
|
||||||
|
- [x] `[format] style`, `--style`, `lucisv.format.style`, MCP; cache key
|
||||||
|
- [x] Per-preset sweeps: no verification errors, no crashes, idempotent
|
||||||
|
- [x] Cross-preset stability measured and explained
|
||||||
|
- [x] Phase 2: `auto`, proof sweep, range/selection use the whole file's style
|
||||||
|
- [x] Docs: root README (Configuration, Named styles), VS Code README
|
||||||
|
- [x] Fix round (QA F1–F8): auto measure counts indentation; server remembers
|
||||||
|
the preset per document; labelled-`end` `else` for google/lowrisc; presets
|
||||||
|
as one table; doc corrections
|
||||||
|
- [ ] Lane 71.1: `lint.rs` line-length width from the style (Handshake request above)
|
||||||
|
|
||||||
|
## Work log
|
||||||
|
|
||||||
|
**2026-11-19 — dev.**
|
||||||
|
|
||||||
|
- Baseline first: built 0.65.4 (`d574969`) before any edit and formatted
|
||||||
|
scratch copies of both trees with it; every "byte-identical" claim below is
|
||||||
|
a `diff -r` against that tree.
|
||||||
|
- `style.rs` holds the whole vocabulary: `Placement`, `PortLists`,
|
||||||
|
`ListIndent`, `Alignment`, the `Style` struct, the six `const` presets and
|
||||||
|
`PRESETS`. Each field's doc has its before/after; each preset's comment says
|
||||||
|
what it is modelled on and how sure.
|
||||||
|
- `format/branch.rs` (new): `if_stmt` moved out of `stmt.rs` and `gen_if` out
|
||||||
|
of `item.rs`, plus `before_keyword` (the space-or-break helper) and
|
||||||
|
`else_cuddles`. `stmt.rs` drops from 604 to 556 production lines, `item.rs`
|
||||||
|
from 472 to 449; the move changed no output (snapshot suite and both tree
|
||||||
|
identities green).
|
||||||
|
- `Fmt::stmt_as_body_from` now calls `body_after(prefix, s, skip, begin)`;
|
||||||
|
`case_item` passes `SameLine`. `gen_block` takes the placement, `gen_case`
|
||||||
|
passes `SameLine`.
|
||||||
|
- `list.rs`: `delimited_dangling` is `delimited_at(.., Block)`; `header_list`
|
||||||
|
uses the style's indent; `style_breaks` and `list_depth` are the two style
|
||||||
|
questions the header and instance code ask.
|
||||||
|
- `align::plan(.., mode)`: `Always` skips `wants_alignment` and nothing else.
|
||||||
|
- Plumbing follows `uvm-utils-indent` everywhere it flows. The CLI and MCP
|
||||||
|
resolve the style first and write explicit `indent`/`line-length` over it;
|
||||||
|
the server's ladder is documented on `format::settings_for`.
|
||||||
|
- **Phase 2.** A per-axis detector (vote on `begin`/`else` placement, port
|
||||||
|
list shape) was designed first and dropped before coding: the formatter
|
||||||
|
itself writes `begin`/`else` in places no switch governs (case items, `do`,
|
||||||
|
after comments, immediate assertions), so votes on the *output* are
|
||||||
|
contaminated by construction and "detect(output) == detect(input)" could
|
||||||
|
only ever be measured, not argued. `auto` instead formats once per preset
|
||||||
|
at the configured indent/width and keeps the output with the least
|
||||||
|
line-multiset difference from the input, indentation compared last; ties go
|
||||||
|
to `PRESETS` order. That is idempotent by construction (argument in
|
||||||
|
`auto.rs`), and naming the *earliest* preset that leaves the output as it is
|
||||||
|
(`canonical`) makes the second run name the same preset too. A first sweep
|
||||||
|
without `canonical` showed 0 byte violations and 47 files whose second run
|
||||||
|
named `lucisv` instead of `lowrisc` (identical bytes) — that is what
|
||||||
|
`canonical` removes.
|
||||||
|
- Cost: `auto` formats a file up to six times (stopping at the first preset
|
||||||
|
that leaves it unchanged, which on an already-formatted file is usually
|
||||||
|
the first); range/selection/on-type formatting under `auto` pay that over
|
||||||
|
the whole buffer to pick the style.
|
||||||
|
|
||||||
|
**2026-11-19 — dev, fix round (QA: PASS WITH FINDINGS).**
|
||||||
|
|
||||||
|
- **F1.** `auto.rs` `distance` is now `(lines whose bytes change, texts
|
||||||
|
differ)`, indentation included; `(0, 0)` still means equal, so the
|
||||||
|
idempotency argument is unchanged. QA's 200-file × 4-construct experiment
|
||||||
|
re-run with QA's own driver: flips 0/4/81/14 → 0/0/1/0, worst rewrite
|
||||||
|
741 → 3 lines (table under "auto"). No stabiliser added: the one remaining
|
||||||
|
flip changes 3 lines. The test that relied on indentation being ignored
|
||||||
|
(`auto_picks_a_layout_never_a_size`) now configures the indent, which is
|
||||||
|
the documented contract.
|
||||||
|
- **F3/F4.** `lucisv_server/src/auto_style.rs`: a 64-entry most-recent list
|
||||||
|
of (URI, preset), on the `Server`. Whole-document format and the save hook
|
||||||
|
resolve (`vlog_formatter::format_auto`) and remember; range, multi-range
|
||||||
|
and `;` on-type use the memory, resolve-and-remember when the buffer
|
||||||
|
parses, else fall back to the default layout (documented). A newline never
|
||||||
|
resolves. `resolve_style` keeps the naming pass; the formatter's own
|
||||||
|
range/selection path (`auto::concrete`) and `format_auto` drop it.
|
||||||
|
Five unit tests and three end-to-end tests (`server/tests/formatting.rs`).
|
||||||
|
- **F2.** New style column `else_after_label`: `OwnLine` for google and
|
||||||
|
lowrisc (and ansi/microsoft/nxp, where `else` is already on its own line),
|
||||||
|
`SameLine` for lucisv. One condition in `branch.rs` (`else_cuddles`), for
|
||||||
|
procedural and generate `if`. Test
|
||||||
|
`else_after_a_labelled_end_starts_its_own_line_in_the_guides`.
|
||||||
|
- **F5–F7.** Cross-preset text now says "alignment plus its knock-on" with
|
||||||
|
QA's 261/265 numbers; lowRISC's ports-required claim corrected (row
|
||||||
|
unchanged: the one alignment switch covers connections, which the guide
|
||||||
|
requires); the comment-line deviation listed; the multi-instance hanging
|
||||||
|
layout recorded as a known limit and the `list_indent` doc corrected.
|
||||||
|
- **F8.** `style.rs`: the presets are one `PRESETS` table, a `row(..)` per
|
||||||
|
preset, columns aligned by hand under `#[rustfmt::skip]` (reason in the
|
||||||
|
comment); the named constants are `PRESETS[i]` and carry the provenance.
|
||||||
|
`port_lists` names exactly the lists it governs; `begin` lists the headers
|
||||||
|
that move with it.
|
||||||
|
|
||||||
|
**2026-11-19 — dev, round 3 (QA round 2: PASS WITH FINDINGS).**
|
||||||
|
|
||||||
|
- **R2-1.** `auto_style.rs` forgets as listed under "auto" (open, close,
|
||||||
|
rename, delete, named-style requests and formats; everything on a settings
|
||||||
|
change or a seen `lucisv.toml` event) and marks an entry *replaced* on a
|
||||||
|
whole-buffer `didChange`, re-resolving on the next request when the buffer
|
||||||
|
parses. Deviation from the brief, reasoned under "auto": marked, not
|
||||||
|
forgotten, so a full-sync client's half-typed buffer keeps its preset.
|
||||||
|
The three one-line calls in `notification.rs` are listed under Handshakes.
|
||||||
|
Tests: four new unit tests (open/close/rename/delete; config file and
|
||||||
|
settings; whole-buffer replacement, partial edit and full-range-from-top;
|
||||||
|
named-style forgetting) and four new end-to-end tests (replaced buffer,
|
||||||
|
auto → named format → auto, close + reopen, rename). QA's `memattack.py`
|
||||||
|
run against this tree: see "auto".
|
||||||
|
- **R2-2.** "`auto` picks a layout for the configured indent and width; it
|
||||||
|
never infers them — set `indent` to match the file first", with the
|
||||||
|
4-space Allman example (checked on the CLI: indent 2 → lucisv layout;
|
||||||
|
`--indent 4 --line-length 80` → unchanged), in this README, the root
|
||||||
|
README, the extension README and the `lucisv.format.style` `auto`
|
||||||
|
description.
|
||||||
|
|
||||||
|
## Changelog paragraph (for the lead)
|
||||||
|
|
||||||
|
**Named formatting styles.** `[format] style = "<name>"` in `lucisv.toml`,
|
||||||
|
`--style <name>` on the command line, or the new `lucisv.format.style`
|
||||||
|
drop-down in VS Code picks a house layout: `lucisv` (the default, unchanged
|
||||||
|
byte for byte), `google` (the Google Verilog Style Guide: one port and
|
||||||
|
connection per line at a 4-space continuation indent), `lowrisc` (OpenTitan's
|
||||||
|
guide: the same with every port and connection table aligned), and `ansi`,
|
||||||
|
`microsoft` and `nxp` — lucisv's educated guesses at those names (Allman
|
||||||
|
`begin`/`else`, 4 spaces and 80 or 120 columns; a conservative aligned RTL
|
||||||
|
style), not rules those companies publish. `auto` keeps each file in the
|
||||||
|
preset it is already closest to, and the language server remembers each
|
||||||
|
document's preset so on-type and selection formatting stay fast. Every style only moves whitespace and runs
|
||||||
|
through the same safety check; each was swept over the 860-file corpus and
|
||||||
|
OpenTitan's `hw/` tree with no verification error, crash or idempotency
|
||||||
|
failure. An explicit `indent`/`line-length` still wins over a preset's.
|
||||||
|
|
||||||
|
## QA log
|
||||||
|
|
||||||
|
**2026-11-19 — QA (Opus 5.5).** Verdict: **PASS WITH FINDINGS.** None of the
|
||||||
|
four invariants broke anywhere I looked, and the default output is
|
||||||
|
byte-identical. The findings are about how `auto` behaves, how honest the
|
||||||
|
presets are and how accurate the docs are. Scratch:
|
||||||
|
`/private/tmp/claude-501/-Users-lucio-repo-lucisv/d043c274-11ff-4de2-ab0f-45daa8a877f0/scratchpad/qa715/`
|
||||||
|
(`bin/` holds my drivers). No source edits were made.
|
||||||
|
|
||||||
|
*Baseline.* `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||||
|
-- -D warnings` clean; the one manifest warning (`workspace.package.authors`)
|
||||||
|
is already on the base. Every test run went through guard.sh: vlog_formatter
|
||||||
|
374/0, lucisv 151/0, lucisv_core 119/0, lucisv_server 1980/0, lucisv_mcp
|
||||||
|
384/0, node 37/0. `tools/gates.sh` was run on its own (no guard.sh wrapper)
|
||||||
|
and printed **PASS**, every step green. `git diff d574969 -- '**/verify.rs'`
|
||||||
|
is empty. No test was deleted: every test name in d574969 still exists. The
|
||||||
|
only `-assert` lines are the `align::plan` calls that gained
|
||||||
|
`Alignment::Infer`, and the two cache-format assertions that gained the
|
||||||
|
`lucisv` field. The `cli.rs` `cache_line` change is the two lines described,
|
||||||
|
and it weakens nothing. Production sizes: `stmt.rs` and `item.rs` shrank, and
|
||||||
|
every changed file stays under its threshold.
|
||||||
|
|
||||||
|
*Default byte identity, rebuilt independently.* Base built from `git archive
|
||||||
|
d574969` with its own target dir. 4 921 files (corpus + OpenTitan `hw`,
|
||||||
|
scratch copies) were formatted four ways: base vs new with no flag, new
|
||||||
|
`--style lucisv`, and base vs new with a `lucisv.toml` setting only
|
||||||
|
`line-length = 90` / `indent = 3`. `diff -r` gives **0 lines** for all three
|
||||||
|
comparisons, and stderr is identical too. Sanity check: the toml tree differs
|
||||||
|
from the default tree in 4 690 files.
|
||||||
|
|
||||||
|
*Invariants per style, using my own driver* (`bin/sweep.sh` plus
|
||||||
|
`bin/lexcmp.py`). lexcmp is an independent Python lexer: maximal-munch
|
||||||
|
words, strings and escaped identifiers kept whole, based numbers and `@*`
|
||||||
|
normalised as `verify.rs` already does, `` `define `` lines compared whole,
|
||||||
|
and comments compared by count and per-line-stripped text. I mutation-tested
|
||||||
|
it on five crafted corruptions and it caught all five. Run against the base
|
||||||
|
binary's output it reports zero problems. Each style was formatted three
|
||||||
|
times over the full tree.
|
||||||
|
|
||||||
|
| style | files | parse err | verif err | crash/guard kill | partial output on failure | token diffs | comment diffs | run2≠run1 | run3≠run2 |
|
||||||
|
|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
| lucisv | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| google | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| lowrisc | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| ansi | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| microsoft | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| nxp | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| auto | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
|
*Hand attacks* (`hand/src`, 12 files) were run under all seven styles, at
|
||||||
|
the default size and at `--line-length 40` with `--indent 8` and with
|
||||||
|
`--indent 1`. The inputs covered:
|
||||||
|
|
||||||
|
- comments after a header, after `end`, between `end` and `else`, and
|
||||||
|
between `)` and `begin`
|
||||||
|
- labelled blocks, `else if` chains, generate `if`/`for`/`case`,
|
||||||
|
`fork…join_none`, `do…while`, `case` items, macros as statements,
|
||||||
|
`assert … else`, `@*`, nested `if` without `begin`
|
||||||
|
- an empty port list, a single port, unpacked dimensions and defaults,
|
||||||
|
`.*`, positional connections, `#(16)`
|
||||||
|
- `` `ifdef `` inside port and connection lists and inside an aligned group
|
||||||
|
- multi-instance declarations, `(* *)` on an instance
|
||||||
|
- 80- and 120-column expressions
|
||||||
|
- tabs plus CRLF, no trailing newline, non-ASCII text
|
||||||
|
- a fence, an empty file, a comment-only file, a parse error
|
||||||
|
|
||||||
|
Results: 0 token diffs, 0 comment diffs, every file idempotent, and the
|
||||||
|
parse-error file was refused with its bytes unchanged. Three inputs failed
|
||||||
|
identically on the d574969 binary, so they are bugs that predate this lane:
|
||||||
|
|
||||||
|
- a comment between a generate `end` and `else` gives a verification error;
|
||||||
|
the safety net caught it and nothing was written
|
||||||
|
- `` `ifdef `` between `end` and `else` is a parse error
|
||||||
|
- `(* keep *)` on an ANSI port is a parse error
|
||||||
|
|
||||||
|
Each layout matched its row, with the exception in F2.
|
||||||
|
|
||||||
|
*Plumbing.* All checked by hand, all as documented:
|
||||||
|
|
||||||
|
- toml with a valid style; unknown, wrong-case, empty and trailing-space
|
||||||
|
names, each giving exit 2 with `file:line` and the list of names
|
||||||
|
- wrong types (`1`, `true`, an array), giving "expected a quoted string"
|
||||||
|
- `style` outside `[format]`
|
||||||
|
- `--style` with `--indent`/`--line-length`, flag over toml, and a toml
|
||||||
|
`indent` over the flag's preset
|
||||||
|
- nested configs: the nearest one wins with no merging
|
||||||
|
- `check --select line-length` under each style (80, 100 and 120 columns,
|
||||||
|
auto 100)
|
||||||
|
- MCP `format` live over stdio, ansi + `indent = 3`, byte-equal to the CLI
|
||||||
|
- the cache: A → B → A is never served stale; a corrupt 7th field, a
|
||||||
|
6-field line and a garbage line are each dropped without error; the base
|
||||||
|
binary reading the new store re-checks the file and rewrites it
|
||||||
|
- the `lucisv.format.style` drop-down matches `STYLE_NAMES` (a test pins
|
||||||
|
this)
|
||||||
|
|
||||||
|
*auto.*
|
||||||
|
|
||||||
|
- **Determinism:** `--threads 1` vs the default thread count over all
|
||||||
|
4 921 files: 0 diff lines.
|
||||||
|
- **Ties:** I built a file where `lucisv` and `nxp` tie exactly at 15/16.
|
||||||
|
It went to `lucisv`, the earlier preset, three runs gave the same bytes,
|
||||||
|
and the result is idempotent.
|
||||||
|
- **Edge cases:** an empty file, a comment-only file, a fence region and a
|
||||||
|
parse error all behave as under a fixed preset.
|
||||||
|
- **Range:** `--lines` under auto changed nothing outside the range, and the
|
||||||
|
result was stable.
|
||||||
|
- **Stability and cost:** findings F1, F3 and F4.
|
||||||
|
|
||||||
|
**Findings.**
|
||||||
|
|
||||||
|
- **F1 — medium-high (user-visible, not an invariant): under `auto`, a
|
||||||
|
one-line edit can rewrite most of a file.** `auto.rs` `distance` compares
|
||||||
|
layout lines first and indentation only to break ties. A preset that saves
|
||||||
|
3 layout lines therefore beats one that keeps 741 lines' indentation.
|
||||||
|
Repro (`qa_auto/` probe, scratch):
|
||||||
|
1. Take `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv`.
|
||||||
|
2. Auto picks `microsoft`, at distance (626, …) against `google` (626, …).
|
||||||
|
3. Insert `always_comb if(qa) begin qa_x=1; end else begin qa_x=0; end`
|
||||||
|
before `endmodule` and run auto again.
|
||||||
|
4. It now picks `google`, and `ListIndent::Wrap` re-indents **741 of 1 314
|
||||||
|
lines**.
|
||||||
|
|
||||||
|
Measured on 200 random files with `endmodule`, comparing the auto output
|
||||||
|
before and after one inserted construct. The `--style auto` column counts
|
||||||
|
files whose pre-existing lines changed.
|
||||||
|
|
||||||
|
| inserted construct | preset changed | pre-existing lines changed | >20 lines changed |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `assign qa_x=qa_y ;` | 0 | 0 | 0 |
|
||||||
|
| the cuddled if/else line above | 4 | 4 | 2 (741, 194 lines) |
|
||||||
|
| an Allman if/else block | 81 | 21 | 2 (140 lines max) |
|
||||||
|
| a one-line instance `qa_mod qa_u (.a(qa_a), .b(qa_b));` | 14 | 14 | 2 (37 lines max) |
|
||||||
|
|
||||||
|
In the last row, typing one ordinary instance into a google-style file
|
||||||
|
flips it to `lucisv` and un-breaks every short header. Idempotency still
|
||||||
|
holds in every case. Possible cheap mitigations, for the lead to decide:
|
||||||
|
- compare total changed lines instead of lexicographically
|
||||||
|
- add hysteresis: keep the preset the input is already a fixed point of
|
||||||
|
unless another wins by a margin
|
||||||
|
- in the editor, pin the preset per document
|
||||||
|
- **F2 — medium (preset honesty): `google` and `lowrisc` cuddle `else`
|
||||||
|
after a labelled `end`.** Both cited guides make an exception: after a
|
||||||
|
labelled `end`, the `else` goes on a new line (Google "Eschatology";
|
||||||
|
lowRISC "Begin / End"). Repro: `if (a) begin : l1 … end : l1` / `else
|
||||||
|
begin` with `--style google` or `--style lowrisc` prints `end : l1 else
|
||||||
|
begin`. The preset comments in `style.rs` (GOOGLE, LOWRISC) leave this
|
||||||
|
exception out.
|
||||||
|
- **F3 — medium (functional): under `auto`, range, selection and on-type
|
||||||
|
formatting fall back to `lucisv` whenever the buffer has a parse error
|
||||||
|
anywhere.** `auto.rs` `resolve_style` does this in its `Err(_) =>
|
||||||
|
PRESETS[0]` arm. A half-typed buffer is exactly when on-type runs, and
|
||||||
|
selection formatting otherwise works around parse errors. Repro: take the
|
||||||
|
google-formatted `common_cells/src/stream_throttle.sv`, insert an
|
||||||
|
unindented 4-line broken instance at line 48, and run `format_selection`
|
||||||
|
lines 48–51 with auto:
|
||||||
|
- with no parse error elsewhere, it lays the instance out google-style
|
||||||
|
(one connection per line)
|
||||||
|
- with ` assign qa = ;` added near the end, it joins the instance onto
|
||||||
|
one line, lucisv-style
|
||||||
|
|
||||||
|
This is documented in a code comment, but not in either README.
|
||||||
|
- **F4 — medium (cost; the README is optimistic).** Release build, on a
|
||||||
|
busy machine, 10 largest files:
|
||||||
|
|
||||||
|
| file | auto, unformatted | lucisv, unformatted | auto selection, formatted file | lucisv selection | auto selection, unformatted file |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `pinmux_reg_top.sv`, 42 192 lines | 2.30 s | 0.37 s | 1.36 s | 0.094 s | 3.0 s |
|
||||||
|
| `rv_plic_reg_top.sv`, 20 021 lines | 0.45 s | — | 0.25 s | — | — |
|
||||||
|
| `ac_range_check_reg_top.sv`, 14 418 lines | 0.32 s | — | 0.28 s | — | — |
|
||||||
|
|
||||||
|
The README says an already-formatted file costs "0.41 s vs 0.40 s (the
|
||||||
|
first preset leaves it unchanged)". That holds only when the file's preset
|
||||||
|
is `lucisv`. pinmux's auto output resolves to `google`, so every selection
|
||||||
|
pays three whole-file formats: `lucisv`, then `google`, then `canonical`'s
|
||||||
|
`lucisv` again. Selection does not need `canonical`, which only names the
|
||||||
|
preset. Caching the resolved preset per document version would remove the
|
||||||
|
whole cost from on-type. Whether 1–3 s per on-type keystroke on 20k–42k
|
||||||
|
line files is acceptable is the lead's call.
|
||||||
|
- **F5 — low (docs): the cross-preset claim "every other decision … comes
|
||||||
|
back" is slightly overstated.** I reproduced the counts for lucisv via
|
||||||
|
lowrisc (1 288), microsoft via lucisv (20) and ansi via nxp (1 244). I then
|
||||||
|
classified every differing hunk in 20 files per pair (`bin/classify.py`):
|
||||||
|
- microsoft via lucisv and ansi via nxp: all padding, or lists broken by
|
||||||
|
alignment
|
||||||
|
- lucisv via lowrisc: 261 of 265 hunks are padding or alignment-forced
|
||||||
|
breaks; 4 hunks (18 lines) are something else. Examples:
|
||||||
|
`flash_phy_core.sv:230` and `kmac_entropy.sv:297`. A named parameter
|
||||||
|
override `#(.Width(HashCntW))`, broken in `lucisv(x)`, comes back
|
||||||
|
joined in `lucisv(lowrisc(lucisv(x)))` once its connection list is
|
||||||
|
aligned.
|
||||||
|
|
||||||
|
This is the pre-existing coupling between the head and the connection
|
||||||
|
list, and it is a knock-on effect of alignment rather than a new bug. The
|
||||||
|
README should say so instead of "only alignment".
|
||||||
|
- **F6 — low (docs):**
|
||||||
|
- `style.rs` LOWRISC says the guide's "Module Declaration" section
|
||||||
|
*requires* aligned ports. The guide requires alignment only for
|
||||||
|
instantiation port expressions; for declarations it is just shown in
|
||||||
|
the examples. The feature README's "aligned in columns" has the same
|
||||||
|
issue.
|
||||||
|
- lowRISC keeps a comment line without a blank line before it inside the
|
||||||
|
same alignment block. lucisv breaks the group at the comment. This
|
||||||
|
deviation is not listed beside the widest-row-tight one in Assumptions.
|
||||||
|
- **F7 — low (cosmetic; the layout predates the lane but is now common):**
|
||||||
|
`OnePerLine` breaks every multi-instance declaration (`p1 u8 (.a(a)), u9
|
||||||
|
(.a(b));`) into the old hanging layout. Under `google`, entries land at
|
||||||
|
8, `)` and `u9` at 4, and the opening line is at 2. Same under
|
||||||
|
`microsoft` at 4/12/8. `style.rs` `list_indent` says the closing `)`
|
||||||
|
stays at the opening line's column, which is false here.
|
||||||
|
- **F8 — low (readability, concrete gaps in `style.rs`):**
|
||||||
|
- The module doc says "every preset is a table row in this file", but the
|
||||||
|
presets are six separate 9-line struct literals. Only the README has the
|
||||||
|
side-by-side table.
|
||||||
|
- `port_lists`' doc does not say which lists it governs (not positional
|
||||||
|
connections, not function/task ports, not `#(16)`). That is in the
|
||||||
|
README's Assumptions only.
|
||||||
|
- `begin`'s doc does not say it also moves `always_comb`/`initial`/`for`
|
||||||
|
`begin` (ansi prints `always_comb` / `begin`).
|
||||||
|
|
||||||
|
Confirmed honest: in every user-facing place `ansi`, `microsoft` and `nxp`
|
||||||
|
appear (root README, extension README, package.json `enumDescriptions` and
|
||||||
|
`markdownDescription`, `style.rs` comments), they are labelled as lucisv's
|
||||||
|
guesses, and no citation is made up. Both guides were fetched
|
||||||
|
(google/styleguide `verilogguide.md` up to character 100 000;
|
||||||
|
lowRISC/style-guides `VerilogCodingStyle.md`). Indent 2, width 100,
|
||||||
|
`begin` on the keyword's line, `end else begin`, one entry per line, Google's
|
||||||
|
4-space list indent, lowRISC's 2-space list indent, and Google's
|
||||||
|
recommended-only alignment all match the text, apart from F2 and F6.
|
||||||
|
|
||||||
|
Not verified:
|
||||||
|
- a live VS Code or LSP session (the server's style ladder is covered only
|
||||||
|
by unit tests, which I read against the README)
|
||||||
|
- the dev's per-preset pick counts (lucisv 3 875, …)
|
||||||
|
- the rest of Google's guide beyond character 100 000
|
||||||
|
- lint.rs line-length under ansi/microsoft/nxp in the server (owned by
|
||||||
|
lane 71.1; the Handshake request stands)
|
||||||
|
|
||||||
|
**2026-11-19 — QA round 2 (Opus 5.5), on the fix round.** Verdict:
|
||||||
|
**PASS WITH FINDINGS.** No invariant violation, and the default output is
|
||||||
|
still byte-identical. F1, F2, F4 and F8 are fixed. F3 is fixed for the case
|
||||||
|
it named, but the new per-document memory can serve a stale preset (R2-1).
|
||||||
|
Binaries were rebuilt from the worktree (`bins/new2`, `bins/server2`).
|
||||||
|
Drivers are in scratch `bin/`: `sweep2.sh`, `identity2.sh`, `lexcmp.py`,
|
||||||
|
`lsp.py`, `memattack.py`, plus the `qa_auto` probe's `edit2` mode.
|
||||||
|
|
||||||
|
*Baseline.*
|
||||||
|
- `cargo fmt --check` clean; `clippy --all-targets -D warnings` clean.
|
||||||
|
- node tests 37/0.
|
||||||
|
- `tools/gates.sh` **PASS**, with every suite run through guard.sh:
|
||||||
|
vlog_formatter 376/0, lucisv 151/0, lucisv_core 119/0, lucisv_server
|
||||||
|
1988/0, lucisv_mcp 384/0; corpus step 814/6, the same as round 1.
|
||||||
|
- `git diff d574969 -- '**/verify.rs'` is empty.
|
||||||
|
- No test name from d574969 is missing.
|
||||||
|
- The one rewritten test, `auto_picks_a_layout_never_a_size`, now
|
||||||
|
configures indent 4 and asserts Allman output. It does not hide a
|
||||||
|
regression, but it reflects a behaviour change (R2-2).
|
||||||
|
- Sizes: unchanged hot spots. `auto_style.rs` is 184 lines with its tests;
|
||||||
|
no production file grew past a threshold.
|
||||||
|
|
||||||
|
*Default byte identity* against the d574969 build, over all 4 921 files: no
|
||||||
|
flag, `--style lucisv`, and a toml with only `line-length`/`indent` each
|
||||||
|
give **0 diff lines** in output and in stderr.
|
||||||
|
|
||||||
|
*Invariants, independent lexer, three runs per style, all 4 921 files.* For
|
||||||
|
every one of the seven styles: 14 parse errors (the base's own), 0
|
||||||
|
verification errors, 0 crashes or guard kills, 0 partial outputs, 0 token
|
||||||
|
diffs, 0 comment diffs, and 0 files changed by the 2nd or the 3rd run.
|
||||||
|
|
||||||
|
*a. Edits under auto.*
|
||||||
|
|
||||||
|
On the numbers that need reconciling: both are right; they are different
|
||||||
|
columns of my round-1 table. For the own-line block, 81 is "preset
|
||||||
|
changed" and 21 is "pre-existing lines changed".
|
||||||
|
|
||||||
|
Round 2, same 200 files, same four constructs, measured as preset changes
|
||||||
|
(and maximum lines rewritten):
|
||||||
|
|
||||||
|
| inserted construct | round 1 | round 2 |
|
||||||
|
|---|---|---|
|
||||||
|
| `assign` | 0 | 0 |
|
||||||
|
| cuddled if/else line | 4 | 0 |
|
||||||
|
| own-line block | 81 | 1 (3 lines) |
|
||||||
|
| one-line instance | 14 | 0 |
|
||||||
|
|
||||||
|
This matches the dev's figures.
|
||||||
|
|
||||||
|
Wider set: 500 new random files with `endmodule`. "Rewritten" counts
|
||||||
|
original lines changed outside the edit; for `delete_block` the deleted
|
||||||
|
lines are taken out of the baseline first.
|
||||||
|
|
||||||
|
| edit | n | preset changed | 0 lines | 1–3 | 4–20 | >20 | max |
|
||||||
|
|---|---|---|---|---|---|---|---|
|
||||||
|
| `assign` line | 499 | 0 | 499 | 0 | 0 | 0 | 0 |
|
||||||
|
| cuddled if/else line | 499 | 3 | 496 | 3 | 0 | 0 | 2 |
|
||||||
|
| Allman if/else block | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||||
|
| one-line instance | 499 | 1 | 498 | 1 | 0 | 0 | 2 |
|
||||||
|
| new port in the header | 419 | 20 | 399 | 16 | 4 | 0 | 6 |
|
||||||
|
| instance, 3 connections one per line | 499 | 25 | 474 | 25 | 0 | 0 | 3 |
|
||||||
|
| `always_ff`, cuddled | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||||
|
| `always_ff`, Allman | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||||
|
| `always_ff`, nxp layout | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||||
|
| delete the last `always … begin` block | 185 | 0 | 85 | 100 | 0 | 0 | 1 |
|
||||||
|
| paste a 37–42-line module in another preset | 499 | 161 | 339 | 29 | 131 | 0 | 12 |
|
||||||
|
| paste a module in the same preset | 499 | 12 | 487 | 4 | 8 | 0 | 6 |
|
||||||
|
|
||||||
|
- No edit rewrote more than 12 unrelated lines, so none crossed the
|
||||||
|
~20-line flag, and every result was idempotent.
|
||||||
|
- The `delete_block` 1-line cases are the blank line left behind,
|
||||||
|
collapsed. Example: `spid_fifo2sram_adapter.sv`.
|
||||||
|
- Pasting a whole google-formatted module into a lucisv file flips the file
|
||||||
|
in 101 of 298 cases and re-lays up to 12 of its own header lines. Majority
|
||||||
|
rule by line count is a defensible outcome.
|
||||||
|
|
||||||
|
*c. The per-document memory, live over stdio against `lucisv-server`.*
|
||||||
|
Setup: auto via `didChangeConfiguration`. "Google file" means a
|
||||||
|
google-formatted module; the range format target is one unindented
|
||||||
|
one-line instance. Ground truth is the CLI's auto on the same buffer.
|
||||||
|
|
||||||
|
| case | expected | got | result |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1. First range on a google file | resolves google | google; edits confined to the range; second range returns no edits | OK |
|
||||||
|
| 2. Buffer replaced by a lucisv-layout text (external reformat / reload) | lucisv | **google** | FAIL, R2-1 |
|
||||||
|
| 3. Whole-document format with a remembered preset | searches afresh | equals CLI auto | OK |
|
||||||
|
| 4. Range after that format | lucisv | lucisv | OK |
|
||||||
|
| 5. Named `lucisv` / `google` while a preset is remembered | memory ignored | memory ignored | OK |
|
||||||
|
| 6. auto → whole-document format under `lucisv` → auto, then a range | lucisv | **google** | FAIL, R2-1 |
|
||||||
|
| 7. Close, then reopen the same URI with lucisv content | lucisv | **google** | FAIL, R2-1 |
|
||||||
|
| 8. Buffer stops parsing after a preset is remembered | remembered google | google, for range and for `;` on-type | OK |
|
||||||
|
| 9. Buffer never parsed | default layout (documented) | default layout | OK |
|
||||||
|
| 10. Same file under `c%6Dx.sv`, `cmx.sv`, `CMX.sv` | independent entries, none inherits | independent | OK |
|
||||||
|
| 11. 70 documents | oldest evicted and resolved afresh, newest kept, list bounded at 64 | as expected | OK |
|
||||||
|
|
||||||
|
- Range locality held in every case, stale ones included. So R2-1 is
|
||||||
|
layout-only and safe.
|
||||||
|
- Latency, 42 192-line pinmux file, live: the first range costs 1.49 s
|
||||||
|
formatted and 2.90 s unformatted (one search). Each later range costs
|
||||||
|
0.06 s, and a named-style range costs 0.067 s. F4 is fixed after the
|
||||||
|
first request per document.
|
||||||
|
- didRename was not run live. By the code, the new URI has no entry
|
||||||
|
(it searches), and the old URI keeps its entry, which is case 7 again if
|
||||||
|
a file reappears under the old URI.
|
||||||
|
|
||||||
|
*d. `else_after_label`.* I wrote new inputs (`hand2/`):
|
||||||
|
- procedural `end : l` followed by `else`, `else if`, `else begin : l`, a
|
||||||
|
trailing `//`, a `/* */` between, a plain `else` statement, and
|
||||||
|
`` `ifdef `` inside the block;
|
||||||
|
- an unlabelled `end` before a labelled `else` block;
|
||||||
|
- `unique if`;
|
||||||
|
- generate `if`/`else if`/`else` chains with labels, including inside a
|
||||||
|
labelled `for`.
|
||||||
|
|
||||||
|
Under all seven styles: token-equal, comments intact, idempotent.
|
||||||
|
|
||||||
|
The cited sections, re-fetched today:
|
||||||
|
- Google "Eschatology": "if `end` has a label, a following `else` must be
|
||||||
|
on a new line".
|
||||||
|
- lowRISC "Begin / End": the same rule, with an `end : a` / `else begin : b`
|
||||||
|
example at the same column.
|
||||||
|
|
||||||
|
google and lowrisc now print exactly that, and `end else begin : t9` (no
|
||||||
|
end label) stays cuddled. lucisv still cuddles, and its byte identity
|
||||||
|
holds. One older bug, already present in d574969, showed up here: a
|
||||||
|
trailing `// c` after a generate `end : g4` followed by `else` is a
|
||||||
|
verification error under every style. The safety net catches it. It is the
|
||||||
|
round-1 generate-comment-before-else bug again.
|
||||||
|
|
||||||
|
*e. Table attributes.* `#[allow(clippy::too_many_arguments)]` at
|
||||||
|
`style.rs:102` and `#[rustfmt::skip]` at `style.rs:138` each carry a reason.
|
||||||
|
The table is column-aligned with a header comment and reads side by side.
|
||||||
|
`cargo fmt --check` passes.
|
||||||
|
|
||||||
|
**Findings, round 2.**
|
||||||
|
- **R2-1 — medium (wrong preset served; layout only, safe).**
|
||||||
|
`crates/lucisv_server/src/auto_style.rs`, `concrete` → `recall`: the
|
||||||
|
memory is keyed by URI alone and never invalidated. Nothing clears it:
|
||||||
|
not `didChange`, `didOpen`, `didClose`, a settings change, nor a whole
|
||||||
|
document format under a named style. Repro: cases 2, 6 and 7 above
|
||||||
|
(`bin/memattack.py`).
|
||||||
|
- In case 6, the user formats the whole file under `lucisv`, switches
|
||||||
|
back to auto, and the next selection or on-type `;` is laid out
|
||||||
|
google-style in a file that is entirely lucisv.
|
||||||
|
- It stays that way until the next whole-document format or save.
|
||||||
|
- Cheap fixes: drop the entry on `didOpen`/`didClose` and on any
|
||||||
|
settings change, and on a whole-document format under a named style;
|
||||||
|
or key the entry by the document version it was resolved on, and
|
||||||
|
re-resolve only on a full-text replacement.
|
||||||
|
- **R2-2 — low-medium (behaviour change from F1, undocumented in the
|
||||||
|
README).** Now that indentation counts in full, a file whose indent
|
||||||
|
differs from the configured one loses its layout under auto. Repro:
|
||||||
|
`lucisv --style auto` with default indent 2 on a 4-space Allman file
|
||||||
|
(`hand/src/a01` formatted `--style ansi`) prints cuddled lucisv layout;
|
||||||
|
round 1 kept it Allman. The dev's test documents this as "indent is the
|
||||||
|
config's". In VS Code the editor `tabSize` rung softens it; on the CLI it
|
||||||
|
does not. Between rounds, 426 of 4 921 files' auto output changed.
|
||||||
|
Worth a sentence in the README's `auto` paragraph.
|
||||||
|
- Round-1 F5–F7 doc fixes were read and are accurate. F7's hanging
|
||||||
|
multi-instance layout is recorded as a known limit.
|
||||||
|
|
||||||
|
Not verified in round 2:
|
||||||
|
- a real VS Code session
|
||||||
|
- `didRename` live
|
||||||
|
- a lucisv.toml style change while a preset is remembered: by the code it
|
||||||
|
behaves like case 6, since `concrete` checks only `config.auto_style`
|
||||||
|
- the dev's pick counts
|
||||||
|
- Google's guide past character 100 000
|
||||||
|
|
||||||
|
## Review
|
||||||
|
|
||||||
|
**Lead, 2026-11-19.** Accepted for 0.65.5, after two QA rounds and three dev rounds.
|
||||||
|
|
||||||
|
- The owner asked for adaptation to the file, with named styles as the
|
||||||
|
fallback if that was too ambiguous. Both shipped, and the order they were
|
||||||
|
built in was the right one: presets first, each proven on 4 921 files, then
|
||||||
|
`auto` as a search over them rather than a detector — the dev dropped the
|
||||||
|
voting detector before writing it because its stability could only be
|
||||||
|
measured, never argued. `auto`'s idempotency is argued (a preset's own
|
||||||
|
output is its fixed point) and then measured.
|
||||||
|
- QA earned its keep twice. Round 1 found that `auto` could re-indent 741
|
||||||
|
lines after a one-line edit; round 2 found the fix's per-document memory
|
||||||
|
could go stale. Both are fixed and both are the kind of thing only an
|
||||||
|
adversarial run finds. The invariant table (seven styles, three runs,
|
||||||
|
independent lexer, mutation-tested) is the evidence I am accepting this on.
|
||||||
|
- I allowed three one-line calls in `server/notification.rs`, another lane's
|
||||||
|
file, for the memory's invalidation; they are listed under Handshakes and I
|
||||||
|
resolve that merge.
|
||||||
|
- The dev departed from my wording on whole-buffer replacement (re-resolve,
|
||||||
|
not forget) and was right: a full-sync client would otherwise lose the
|
||||||
|
preset of every half-typed buffer.
|
||||||
|
- Not done, recorded: the server's `line-length` lint still falls back to 100
|
||||||
|
under the 80- and 120-column styles (`lint.rs`, lane 71.1's file — I take
|
||||||
|
it at that merge); multi-instance declarations under one-per-line styles;
|
||||||
|
the three pre-existing bugs QA met on the way (comment between a generate
|
||||||
|
`end` and `else`: verification error; `` `ifdef `` between `end` and `else`
|
||||||
|
and an attribute on an ANSI port: parse errors) go to the backlog.
|
||||||
|
- Owed to a human: the drop-down in a running VS Code. `ansi`, `microsoft`
|
||||||
|
and `nxp` are guesses and say so wherever a user meets them.
|
||||||
@@ -5,6 +5,17 @@ for you. The extension and its bundled language server share one version
|
|||||||
number; the full engineering notes live in the
|
number; the full engineering notes live in the
|
||||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||||
|
|
||||||
|
## 0.65.5 — 2026-11-19
|
||||||
|
|
||||||
|
- **Formatting styles, from a drop-down.** `lucisv.format.style` picks the
|
||||||
|
layout: `lucisv` (the default, unchanged), `google`, `lowrisc`, `ansi`,
|
||||||
|
`microsoft`, `nxp`, or `auto`. `google` and `lowrisc` follow those published
|
||||||
|
guides; `ansi`, `microsoft` and `nxp` are lucisv's educated guesses, not
|
||||||
|
published rules.
|
||||||
|
- **`auto` keeps a file in the layout it is already closest to.** It never
|
||||||
|
guesses indent or line length — set those to match the file. A checked-in
|
||||||
|
`lucisv.toml` `[format] style` still outranks the editor setting.
|
||||||
|
|
||||||
## 0.65.4 — 2026-11-19
|
## 0.65.4 — 2026-11-19
|
||||||
|
|
||||||
- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a
|
- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
|||||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||||
setup.
|
setup.
|
||||||
|
|
||||||
The current release is **0.65.4**. Its platform packages include
|
The current release is **0.65.5**. Its platform packages include
|
||||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||||
[Agents (MCP)](#agents-mcp)):
|
[Agents (MCP)](#agents-mcp)):
|
||||||
|
|
||||||
@@ -329,6 +329,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
|||||||
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
|
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
|
||||||
| `lucisv.lineLength` | unset | Maximum formatter width, 40–400; built-in default is 100 |
|
| `lucisv.lineLength` | unset | Maximum formatter width, 40–400; built-in default is 100 |
|
||||||
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
|
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
|
||||||
|
| `lucisv.format.style` | `lucisv` | A drop-down of layout presets — `lucisv`, `google`, `lowrisc`, `ansi`, `microsoft`, `nxp` — or `auto`, which keeps each file in the preset it is already closest to (remembered per document from its last full format, so on-type and selection formatting stay fast and keep the preset while the file has a syntax error). `auto` picks a layout for the configured indent and width and never infers them: set `lucisv.indent` (or the project's `indent`) to match the file first — a 4-space Allman file under `auto` at indent 2 comes out in the `lucisv` layout. A preset also sets the indent and line length, below `lucisv.indent`/`lucisv.lineLength`; `ansi`, `microsoft` and `nxp` are lucisv's guesses, not those organisations' rules. See the [style table](https://git.luci.ooo/lucio/lucisv/src/branch/master/README.md#named-styles) |
|
||||||
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
|
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
|
||||||
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
|
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
|
||||||
| `lucisv.hierarchy.duts` | `[]` | Modules the Hierarchy pane treats as DUTs, by name — the checked-in list a team shares. Each one adds two sections ahead of "Other modules"; a DUT from this setting is shown locked and can only be removed here |
|
| `lucisv.hierarchy.duts` | `[]` | Modules the Hierarchy pane treats as DUTs, by name — the checked-in list a team shares. Each one adds two sections ahead of "Other modules"; a DUT from this setting is shown locked and can only be removed here |
|
||||||
@@ -404,8 +405,11 @@ The configuration ladder is:
|
|||||||
|
|
||||||
1. The nearest `lucisv.toml` / `.lucisv.toml` discovered for the file.
|
1. The nearest `lucisv.toml` / `.lucisv.toml` discovered for the file.
|
||||||
2. `lucisv.lineLength` and `lucisv.indent` editor settings.
|
2. `lucisv.lineLength` and `lucisv.indent` editor settings.
|
||||||
3. VS Code's tab size, for indentation only.
|
3. The indent and width of the style the file resolves to (`[format] style`
|
||||||
4. Built-in defaults: 100 columns and 2 spaces.
|
in that `lucisv.toml`, else `lucisv.format.style`) — when one other than
|
||||||
|
`lucisv` or `auto` was chosen, this outranks the tab size below.
|
||||||
|
4. VS Code's tab size, for indentation only.
|
||||||
|
5. Built-in defaults: 100 columns and 2 spaces.
|
||||||
|
|
||||||
`lucisv.filelist` is an explicit editor override for index scope. Open buffers
|
`lucisv.filelist` is an explicit editor override for index scope. Open buffers
|
||||||
are always layered over the chosen scope, even when a scratch file is not in
|
are always layered over the chosen scope, even when a scratch file is not in
|
||||||
@@ -436,6 +440,12 @@ default):
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Release 0.65.5 highlights
|
||||||
|
|
||||||
|
Version 0.65.5 adds named formatting styles — `google`, `lowrisc`, `ansi`,
|
||||||
|
`microsoft`, `nxp` and `auto` beside the unchanged default — chosen from the
|
||||||
|
`lucisv.format.style` drop-down or `[format] style` in `lucisv.toml`.
|
||||||
|
|
||||||
## Release 0.65.4 highlights
|
## Release 0.65.4 highlights
|
||||||
|
|
||||||
Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins
|
Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "lucisv",
|
"name": "lucisv",
|
||||||
"version": "0.65.4",
|
"version": "0.65.5",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "lucisv",
|
"name": "lucisv",
|
||||||
"version": "0.65.4",
|
"version": "0.65.5",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"vscode-languageclient": "9.0.1"
|
"vscode-languageclient": "9.0.1"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "lucisv",
|
"name": "lucisv",
|
||||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||||
"version": "0.65.4",
|
"version": "0.65.5",
|
||||||
"publisher": "guoliangchen",
|
"publisher": "guoliangchen",
|
||||||
"author": "Guoliang Chen",
|
"author": "Guoliang Chen",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@@ -583,6 +583,29 @@
|
|||||||
"scope": "window",
|
"scope": "window",
|
||||||
"markdownDescription": "Light the Hierarchy pane's rows that lead to the active file: the row whose module the file declares in a bright orange with a solid bar at its edge, each row above it one shade dimmer, down to a faint floor. Every instance of the module is lit, with its whole path. The shades are the `lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor` and `lucisv.hierarchyCurrentBar` theme colours, which `workbench.colorCustomizations` can override."
|
"markdownDescription": "Light the Hierarchy pane's rows that lead to the active file: the row whose module the file declares in a bright orange with a solid bar at its edge, each row above it one shade dimmer, down to a faint floor. Every instance of the module is lit, with its whole path. The shades are the `lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor` and `lucisv.hierarchyCurrentBar` theme colours, which `workbench.colorCustomizations` can override."
|
||||||
},
|
},
|
||||||
|
"lucisv.format.style": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"lucisv",
|
||||||
|
"google",
|
||||||
|
"lowrisc",
|
||||||
|
"ansi",
|
||||||
|
"microsoft",
|
||||||
|
"nxp",
|
||||||
|
"auto"
|
||||||
|
],
|
||||||
|
"enumDescriptions": [
|
||||||
|
"lucisv's own layout and the default: 2 spaces, 100 columns, `end else begin`, a header on one line when it fits, alignment kept where you wrote it.",
|
||||||
|
"The Google Verilog Style Guide: 2 spaces, 100 columns, `end else begin`, one port and one connection per line at a 4-space continuation indent.",
|
||||||
|
"The lowRISC (OpenTitan) Verilog style guide: like google, but the lists at a 2-space indent and every port and connection table aligned in columns.",
|
||||||
|
"Allman layout, as C formatters' `ansi` style: 4 spaces, 80 columns, `begin` and `else` on lines of their own. lucisv's guess, not a published Verilog standard.",
|
||||||
|
"After clang-format's Microsoft base style: 4 spaces, 120 columns, `begin` and `else` on lines of their own, one port and one connection per line. lucisv's guess; Microsoft publishes no Verilog style.",
|
||||||
|
"A conservative RTL house style: 2 spaces, 80 columns, `end` and `else` on separate lines, one port per line, every table aligned. lucisv's guess; NXP publishes no Verilog style.",
|
||||||
|
"Each file in the preset it is already closest to: lucisv formats it with every preset's layout and keeps the one that changes the fewest lines. Indent and line length are not guessed — they come from `#lucisv.indent#`/`#lucisv.lineLength#`, the editor, or the defaults — so set the indent to match the file first: a 4-space Allman file under `auto` at indent 2 comes out in the `lucisv` layout."
|
||||||
|
],
|
||||||
|
"default": "lucisv",
|
||||||
|
"markdownDescription": "The layout preset the formatter uses. Each one sets the indent and line length too; `#lucisv.indent#` and `#lucisv.lineLength#`, when set, still win over the preset's, and a style you choose here outranks `#editor.tabSize#`. Every style only moves whitespace — the same safety check runs whichever you pick. A checked-in `lucisv.toml` with `[format] style = \"…\"` outranks this setting, so a project and its editors cannot disagree. `ansi`, `microsoft` and `nxp` are lucisv's educated guesses at what those names suggest, not rules published by those organisations."
|
||||||
|
},
|
||||||
"lucisv.format.uvmUtilsIndent": {
|
"lucisv.format.uvmUtilsIndent": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"default": false,
|
"default": false,
|
||||||
|
|||||||
Executable
+73
@@ -0,0 +1,73 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Prove every formatting style safe over real trees: for each preset, format
|
||||||
|
# a scratch copy of the trees in place, count verification errors and
|
||||||
|
# crashes, re-check the output for idempotency, and format every A-output
|
||||||
|
# with B and then A again to measure cross-preset stability.
|
||||||
|
#
|
||||||
|
# Usage: tools/style_sweep.sh -b lucisv -w workdir [-s "lucisv google ..."] tree...
|
||||||
|
#
|
||||||
|
# Never writes to the trees themselves -- only to copies under workdir.
|
||||||
|
# Every lucisv run goes through tools/guard.sh. Prints one TSV row per
|
||||||
|
# preset and one per ordered pair; exit 1 if any verification error, crash
|
||||||
|
# or idempotency violation was seen.
|
||||||
|
# See docs/features/format-styles/README.md.
|
||||||
|
|
||||||
|
set -u
|
||||||
|
|
||||||
|
here=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
lucisv=
|
||||||
|
work=
|
||||||
|
styles="lucisv google lowrisc ansi microsoft nxp auto"
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case $1 in
|
||||||
|
-b) lucisv=$2; shift 2 ;;
|
||||||
|
-w) work=$2; shift 2 ;;
|
||||||
|
-s) styles=$2; shift 2 ;;
|
||||||
|
-*) echo "usage: $0 -b lucisv -w workdir [-s styles] tree..." >&2; exit 2 ;;
|
||||||
|
*) break ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[ -x "$lucisv" ] && [ -n "$work" ] && [ $# -gt 0 ] || {
|
||||||
|
echo "usage: $0 -b lucisv -w workdir [-s styles] tree..." >&2; exit 2; }
|
||||||
|
|
||||||
|
flags="--no-cache --no-config --no-gitignore"
|
||||||
|
run() { "$here/guard.sh" -t 1200 -- "$lucisv" $flags "$@"; }
|
||||||
|
|
||||||
|
# The sources: every .v/.sv/.vh/.svh of every tree (the walk's
|
||||||
|
# EXTENSIONS), symlinks followed as the walk follows them, paths kept,
|
||||||
|
# nothing else.
|
||||||
|
rm -rf "$work" && mkdir -p "$work/src"
|
||||||
|
for tree in "$@"; do
|
||||||
|
dest="$work/src/$(basename "$tree")"
|
||||||
|
(cd "$tree" && find -L . -type f \( -name '*.v' -o -name '*.sv' -o -name '*.vh' -o -name '*.svh' \) -not -path '*/.git/*' |
|
||||||
|
while IFS= read -r f; do mkdir -p "$dest/$(dirname "$f")"; cp "$f" "$dest/$f"; done)
|
||||||
|
done
|
||||||
|
files=$(find "$work/src" -type f | wc -l | tr -d ' ')
|
||||||
|
|
||||||
|
status=0
|
||||||
|
printf 'style\tfiles\tparse-errors\tverification-errors\tcrashes\tnot-idempotent\n'
|
||||||
|
for s in $styles; do
|
||||||
|
cp -R "$work/src" "$work/$s"
|
||||||
|
run --style "$s" "$work/$s" >/dev/null 2>"$work/$s.log"
|
||||||
|
parse=$(grep -c ': parse error\|: lex error' "$work/$s.log")
|
||||||
|
verr=$(grep -c 'verification failed' "$work/$s.log")
|
||||||
|
crash=$(grep -ci 'panic\|guard.sh' "$work/$s.log")
|
||||||
|
run --check --style "$s" "$work/$s" >"$work/$s.check" 2>/dev/null
|
||||||
|
again=$(grep -c '^Would reformat' "$work/$s.check")
|
||||||
|
printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$s" "$files" "$parse" "$verr" "$crash" "$again"
|
||||||
|
[ "$verr" -eq 0 ] && [ "$crash" -eq 0 ] && [ "$again" -eq 0 ] || status=1
|
||||||
|
done
|
||||||
|
|
||||||
|
printf '\nA\tB\tfiles where A(B(A(x))) != A(x)\n'
|
||||||
|
for a in $styles; do
|
||||||
|
for b in $styles; do
|
||||||
|
[ "$a" = "$b" ] && continue
|
||||||
|
rm -rf "$work/pair" && cp -R "$work/$a" "$work/pair"
|
||||||
|
run --style "$b" "$work/pair" >/dev/null 2>&1
|
||||||
|
run --style "$a" "$work/pair" >/dev/null 2>&1
|
||||||
|
diff -rq "$work/$a" "$work/pair" >"$work/$a-$b.diff"
|
||||||
|
printf '%s\t%s\t%s\n' "$a" "$b" "$(wc -l <"$work/$a-$b.diff" | tr -d ' ')"
|
||||||
|
done
|
||||||
|
done
|
||||||
|
rm -rf "$work/pair"
|
||||||
|
exit $status
|
||||||
Reference in new issue
Block a user