Compare commits

..
4 Commits
Author SHA1 Message Date
Guoliang ChenandClaude Mythos 5.2 dbb2349267 Release 0.65.7: 0.65.6, built for every platform
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m19s
0.65.6 was tagged and never published: the release build failed to compile
lucisv-server for Windows. lucisv_core::walk::dir_id is a Copy (dev, ino)
pair on unix and an owned PathBuf elsewhere, and 71.1's
Workspace::holds_another_spelling_of moved it inside a closure
(lucisv_server/src/state/incremental.rs). Compared by reference now.

tools/gates.sh gains a `cross` step: cargo check of the three shipped
binaries for x86_64-pc-windows-gnu and x86_64-unknown-linux-musl with the
rustup toolchain release.sh --cross uses (skipped with a note when it is
absent). It fails on the unfixed tree with the release run's own error and
passes on this one. tools/RELEASING.md lists it.

CHANGELOG.md's 0.65.7 section carries 0.65.6's notes in full under a short
account of what happened; the v0.65.6 tag is left where it is.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots).

Gates: tools/gates.sh PASS on this tree including cross; a full local
tools/release.sh --cross and tools/audit_artifacts.sh dist pass (seven .vsix
packages, eighteen binaries).

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 10:52:35 -08:00
Guoliang ChenandClaude Mythos 5.2 58d3db3e3c Release 0.65.6: saving a file no longer re-indexes the workspace
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Failing after 4m55s
TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of
whole-index work, twice (the save and VS Code's watcher echo), and watcher
events for files the index could not hold started whole rescans.

- vlog_semantic: resolution records every table lookup per reading file,
  misses included (workspace/dependents.rs, references.rs, replace.rs); an
  update re-resolves the edited file and the readers of keys whose values
  changed in what resolution reads. An unchanged record merges nothing. When
  the readers hold more than an eighth of all references, old results are
  removed in one pass over the postings.
- lucisv_server: watcher events are classified per file (state/watched.rs);
  the include graph keeps every include line as written and re-resolves the
  lines a named path could satisfy, in one pass per event; an event naming
  more paths than half the index takes the single rescan; an open buffer the
  index does not hold joins on its first save; completion tables are rebuilt
  only for the names a file declares. Every save still republishes every open
  buffer. The line-length lint follows the formatting style's width.
- Fixed on the way: removing an included header left other files' include
  edges pointing at it.

Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package
member 12 ms; warm startup +40..120 ms for the readers table.

QA failed the first cut on four stale answers found with an independent
fresh-server oracle; all four are fixed and are differential tests. Dev
(three rounds), QA (two rounds) and lead review:
docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from
what the QA rounds and an investigation found in earlier releases too.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0,
lucisv_server 2011/0, lucisv_mcp 384/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 08:52:01 -08:00
Guoliang ChenandClaude Mythos 5.2 80017a59f2 Release 0.65.5: named formatting styles
release / build-and-publish (push) Successful in 5m22s
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]>
2026-11-19 07:03:20 -08:00
Guoliang ChenandClaude Mythos 5.2 7408face90 TODO §70: the tests are portable to Linux (macOS-verified), and §71's queue
Test code only. The suite had only ever run on macOS; the first Linux trial
found clippy red on three unused imports and 11 failing tests.

- Unused imports (lucisv_server hover.rs, includes.rs test modules): they now
  carry the same cfg as the macOS/Windows-only tests that use them.
- Eight permission-denied tests (lucisv cli, lucisv_core walk, lucisv_mcp
  apply/cache/qa_m6, lucisv_server filelist): each first probes that the
  mode it relies on is enforced and says 'skipped' if not (root ignores
  modes); std only, no uid check.
- file_ops' case-mismatched include test probes the filesystem's case
  sensitivity first.
- large.rs' two linear-time tests bound growth (8x input <= 24x time, best
  of five) instead of wall-clock; shown to fail at ~60-74x on a quadratic
  implementation by dev and QA independently.
- scan_trace's stage-sum lower bound is asserted on the best of three
  sessions (reproduced flaky on macOS under load: 2.21 ms of 5.10 ms).
- walk.rs' TempTree test helper gains the Drop its doc promised.
- tools/linux_check.sh runs the working tree in the luhpe-linux-x64 runner's
  job image, as root or --user, without a push.

Linux: root green and --user green but for the scan_trace flake were seen
once, on 88546c8 plus round 1 of this lane. Nothing since has run there (the
owner's ssh key expired), so TODO §70's Linux line and the ci.yml linux job
stay open. Dev, QA (mutation table) and lead review:
docs/features/linux-test-portability/README.md.

TODO.md also gains §71, the owner's eight-feature queue, with its waves.

Gates: tools/gates.sh PASS on this tree (0.65.4 + this), lucisv_server 1977/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 05:35:13 -08:00
82 changed files with 9582 additions and 601 deletions

No files matched your search

+182
View File
@@ -4,6 +4,188 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.65.7 — 2026-11-19
### 0.65.6, built for every platform
0.65.6 was tagged but never published: it passed every gate on the Mac and
then failed to compile for Windows, so the release stopped before anything
was built for distribution. This release is 0.65.6 with that fixed; its
notes are below, unchanged.
- **The Windows build compiles again.** One comparison in the language
server's new "is this file already held under another spelling" check moved
a directory identity that is a small copyable pair on macOS and Linux but an
owned path on Windows (`lucisv_server/src/state/incremental.rs`).
- **The gates now compile for the other platforms.** `tools/gates.sh` has a
new `cross` step: `cargo check` of the three shipped binaries for Windows
and Linux, with the same toolchain the release build uses. Until now
platform-conditional code was first compiled by the release build itself,
after the gates.
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 0.65.6 — 2026-11-19
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 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
### `` `ifdef `` blocks fold, and pin in sticky scroll
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.65.4"
version = "0.65.7"
[[package]]
name = "lucisv_mcp"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.65.4"
version = "0.65.7"
[[package]]
name = "vlog_refactor"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.65.4"
version = "0.65.7"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.65.4"
version = "0.65.7"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+60 -4
View File
@@ -144,6 +144,9 @@ indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
[format]
style = "google" # a named layout, same as --style (see Named styles)
[lint]
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
ignore = ["module-filename"] # removed after selection
@@ -173,11 +176,20 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of
the [named styles](#named-styles). The style is resolved first and supplies
the starting indent and line length; an explicit `indent` or `line-length` —
from a flag or from the file — then wins over the preset's, so
`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An
unknown style name is the same hard error as an unknown key, and lists the
valid names. In the editor, `lucisv.toml` outranks the editor settings as for
every formatting key, and a chosen style (other than `lucisv` or `auto`) also
outranks the editor's tab size.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
it is a formatting choice lucisv leaves to the project, because it changes
bytes in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
@@ -512,7 +524,8 @@ Key ideas carried over from ruff/prettier:
Defaults follow Verible: **2-space indent**, **100-column lines** (both
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
[Configuration](#configuration)).
[Configuration](#configuration)). The list below is the default `lucisv`
style; the [named styles](#named-styles) change some of it.
- One port / parameter / connection per line once a header doesn't fit
- Cuddled `begin`/`end` (`end else begin`)
@@ -521,6 +534,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
through verbatim
### Named styles
`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down
pick one of a handful of house layouts. Every style moves whitespace only —
which line a token starts on and how many spaces precede it — so the same
token-equivalence check guards all of them, and each one is a fixed point of
itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for
every preset; `docs/features/format-styles/README.md`).
| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns |
|---|---|---|---|---|---|---|---|---|
| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them |
| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them |
| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned |
| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them |
| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them |
| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned |
| `auto` | — | — | the preset the file is already closest to | | | | | |
`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html)
and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md)
(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses**
at what those names suggest — C formatters' ANSI/Allman layout, clang-format's
`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house
style — not rules those organisations publish; none of them publishes a Verilog
style that we could find. A `case` item's and a `do`'s `begin` stays on its
own line's end in every style. "Header & connection lists" are module
headers' parameter and port lists and instances' *named* overrides and
connections — not `#(16)`, ordered connections or function ports. `lowrisc`
differs from its guide in two places: the widest aligned connection keeps one
space before its `(`, and a comment line ends an aligned table.
`auto` formats the file once per preset, at the configured indent and width,
and keeps the output that changes the fewest lines (indentation included, so
a one-line edit does not flip a whole file to another preset); it never
guesses an indent or a width, and it is idempotent by construction.
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under
`auto`, range and selection formatting use the style of the whole file, not
of the selected lines; the language server remembers each document's preset
from its last whole-file format, so a keystroke or a selection does not
search again, and a buffer with a parse error keeps its preset. One that has
never resolved — no memory, and it does not parse — gets the default layout.
### Alignment is inferred, not imposed
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
+172
View File
@@ -7263,3 +7263,175 @@ Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
non-white TextMate scopes across themes.
## 70. The tests pass on Linux, and one cleaning round (2026-11-19, owner's order)
Every suite had only ever run on macOS arm64; the Linux and Windows binaries
ship unexecuted. A `linux-x64` Actions runner now exists (`luhpe-linux-x64`,
a resource-capped Docker-in-Docker container on the Gitea host), and the
first trial of the suite in its job image found: clippy red on three unused
imports in `lucisv_server` test modules (their only users are tests compiled
on macOS/Windows alone), and 11 distinct failing tests out of ~5 300 — eight
that set up an unreadable/unwritable path and so cannot fail as root (the
job image's user), one that assumes a case-insensitive filesystem, two
`…_in_linear_time` timing assertions. No product failure among them as far
as the trial shows. One lane, `docs/features/linux-test-portability`;
`tools/linux_check.sh` runs the working tree in that image without a push.
- [x] `cargo clippy --all-targets -- -D warnings` clean on Linux and on
macOS (`crates/lucisv_server/src/hover.rs`, `includes.rs` test modules,
and whatever else the Linux build names).
- [x] The permission-denied tests (`crates/lucisv/tests/cli.rs`,
`crates/lucisv_core/src/walk.rs`, `crates/lucisv_mcp/src/apply.rs` and
`tests/cache.rs`, `tests/qa_m6.rs`, `crates/lucisv_server/src/state/tests/filelist.rs`)
pass both as root and as an unprivileged user: where the platform does
not enforce the permission the test says so and stops, it does not
assert the opposite.
- [x] `crates/lucisv_server/src/file_ops.rs`
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`
holds on a case-sensitive filesystem or is scoped to the insensitive
ones, with the reason written at the test.
- [x] `crates/lucisv_server/src/large.rs` — the two `…_in_linear_time`
tests pass on the runner **and still fail when the conversion is
quadratic** (shown, not asserted).
- [x] The cleaning round: test code only, driven by what the tools report on
either platform — unused imports and dead helpers, platform assumptions
left implicit, assertions on wall-clock or environment that the runner
shows to be fragile. No test is deleted and the test count does not
drop; no production code and nothing in `verify.rs` changes.
- [ ] `cargo test --workspace` green on Linux as root and with `--user`,
and `tools/gates.sh` green on macOS.
- [ ] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
`docs/topo.md` and `tools/RELEASING.md` updated.
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
Ordered by the owner on 2026-11-19, to be done unattended after §70 lands:
each item goes through the dev → QA → lead-review loop, is committed, and
ships as its own release — `0.65.2`, `0.65.3`, … `0.65.n` in the order they
finish — and once all are done, `0.66.0`. The lead has the owner's standing
go-ahead to commit, tag and push for this queue. Every feature is tried on
the OpenTitan tree (not only on unit fixtures) before it is called done.
The items are the owner's words, lightly condensed; each gets its own
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`)
Today every
file edit re-indexes everything. A change to a `define` may have to;
a typical, localized edit must not.
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
work dynamically: answer first from what is already in the same file
(hover to a definition in this file), and use the relationship map to
load completion candidates on demand.
- [ ] **71.3 Highlighting does not wait for the index.** Always run a
localized, viewport-only highlight; it may be imperfect and be
corrected later, but basic colours must not wait for the whole
database.
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
sticky-scroll ("floating") bars.
- [x] **71.5 The formatter adapts to the file's own style** (0.65.5, `docs/features/format-styles`: six named styles and `auto`)
— where lines
break, what is grouped, how ports align. If inferring that is too
ambiguous, a setting with a drop-down of named styles instead (ANSI,
Google, Microsoft, NXP — educated guesses), with the rules easy to
read in the source.
- [x] **71.6 The module view shows where you are.** (0.65.2, `docs/features/hierarchy-current-path`; not yet seen in a running editor.)
Highlight the open
file's instance and its parents in different shades — bright light
orange for the instance, dimmer the further up — or anything in that
spirit that makes the hierarchy easy to read.
- [ ] **71.7 Find References sometimes answers "not found"** on a
port/signal, then works after clicking elsewhere and back. VS Code or
the server? Investigate, then fix what is ours.
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
(the `[]` of
`signal[]` gets highlighted today), **but do highlight `TODO`,
`FIXME`, `FIX_ME`, `TBD`**, plus a user setting for custom words that
are highlighted only in comments.
- [ ] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
### 71 — wave 1 (lead, 2026-11-19): 71.6 runs beside §70
The owner asked not to wait for §70's Linux runs. §70 is test code in the
Rust crates and touches no contract; 71.6 is the extension's hierarchy view
(`editors/vscode/hierarchy*.js`, `package.json`, the extension README and
changelog). Disjoint file sets, and the one edge between the two areas
(`editors/vscode ◀──▶ lucisv_server`, the spawn contract) is touched by
neither — so they run as two lanes: §70 on trunk's tree (already in flight
there), 71.6 in the worktree `../lucisv-wt/71.6` on `lane/71.6-module-view`,
branched from `88546c8`. 71.1–71.3 all live in `lucisv_server`'s state and
indexing, collide with each other and with §70's test files, and wait for
§70 to merge.
- Lane 71.6 owns: `editors/vscode/hierarchyView.js`, `hierarchyModel.js`,
`hierarchySections.js` and their `_test.js` files, new
`editors/vscode/*.js` modules it adds, `editors/vscode/package.json`
(`contributes` only — not `version`), `editors/vscode/.vscodeignore`,
`tools/release.sh`'s runtime-module checks if a new module needs listing,
`docs/features/hierarchy-current-path/README.md`.
- Wave 2 (lead, 2026-11-19): 71.6 shipped as 0.65.2 (`e9f5090`). §70 is still
in flight on trunk's tree, so the next lane is again one that stays out of
the Rust test files: **71.8** (comments), in `../lucisv-wt/71.8` on
`lane/71.8-comments` from `e9f5090`. It owns
`editors/vscode/syntaxes/*`, `language-configuration.json`, new
`editors/vscode/*.js` modules and tests, `extension.js` wiring,
`package.json` `contributes`, `.vscodeignore`, the extension README, and —
only if the stray colour turns out to come from the server's semantic
tokens — `crates/lucisv_server/src/tokens.rs` and `tokens/`, which §70
does not touch. `docs/features/comment-highlighting/README.md`.
- Wave 3 (lead, 2026-11-19): 71.8 shipped as 0.65.3 (`948f8a0`) and 71.4 as
0.65.4 (`d574969`), each from its own worktree; both tagged locally and
**not pushed** — the owner's ssh key left the agent at about 05:00 (its
`AddKeysToAgent 1h`), which also stops `tools/linux_check.sh`. §70 is
committed on macOS evidence with its Linux line left open. 71.5 (formatter
styles) runs in `../lucisv-wt/71.5` from `d574969`. Owed once ssh is back,
in this order: push master and the tags one at a time; re-run §70 on Linux
(root twice, `--user`); add the `linux` job to `ci.yml`.
- Wave 4 (lead, 2026-11-19): 71.5 shipped as 0.65.5 from `../lucisv-wt/71.5`,
rebased onto §70's commit. 71.1 (localized re-index) is with QA in
`../lucisv-wt/71.1`. Found on the way by 71.5's QA, all present in 0.65.4
and filed here, not fixed:
- [ ] A comment between a generate `end` and `else` (also a trailing `// c`
after a labelled generate `end` before `else`) is a verification
error: the file is left unformatted. The safety net works; the
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
- [x] 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.
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
QA rounds and a read-only investigation turned up, all present before this
wave, becomes lane **71.7** (the owner's Find References item, widened):
- [ ] A caret just past an identifier's last letter asks about the next
character: references, definition, hover and highlight come back
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
"not found, then works after clicking back".
- [ ] A `didChange` arriving during a whole rescan can overtake an older
one still queued (`server/mod.rs` `process_batch`): with incremental
sync the server's buffer is corrupted until the file is reopened.
- [ ] A burst `[request, didOpen]` during the startup scan is re-held at
every file (`server/index.rs` `answer_what_is_waiting`): the scan
takes ~300 s on OpenTitan instead of ~1.7 s.
- [ ] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
- 0.65.6 never published (lead, 2026-11-19): the release build failed to
compile `lucisv-server` for Windows — `dir_id` is a `Copy` pair on unix and
a `PathBuf` elsewhere, and 71.1's new code moved it in a closure
(`state/incremental.rs`). The gate caught nothing because nothing before
the release build compiles for another platform. Fixed by the lead (one
line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a
`cross` step so the next one is caught before the tag. Seven of the eight
§71 items therefore have releases 0.65.2–0.65.5 and 0.65.7.
+74 -7
View File
@@ -1,7 +1,7 @@
//! Hand-rolled command line parsing for the `lucisv` binary.
use lucisv_core::cache;
use lucisv_core::config::FileConfig;
use lucisv_core::config::{self, FileConfig};
use vlog_formatter::{Config, LineRanges};
/// Which tool this invocation runs.
@@ -58,6 +58,8 @@ pub struct Options {
pub line_length: Option<usize>,
/// `--indent`, if given; otherwise the config file decides.
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
/// whole-file run.
pub lines: Option<LineRanges>,
@@ -98,8 +100,13 @@ impl Options {
}
/// Formatter settings for one file: CLI flag > config file > default.
///
/// The style is resolved first and supplies the starting indent and line
/// length; an explicit `indent`/`line-length`, from the flag or the file,
/// is then written over the preset's, whichever rung named the style.
pub fn config_with(&self, file: &FileConfig) -> Config {
let mut config = Config::default();
let name = self.style.or(file.format_style);
let mut config = name.and_then(Config::named).unwrap_or_default();
if let Some(n) = self.line_length.or(file.line_length) {
config.max_width = n;
}
@@ -196,6 +203,12 @@ OPTIONS:
filelist, and neither reads nor writes the cache
--line-length <N> maximum line length (default 100)
--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
-h, --help show this help
-V, --version show version
@@ -275,7 +288,7 @@ FILELISTS:
CACHE:
A file whose exact content lucisv has already verified is formatted — under
the same line-length, indent and lucisv version — is skipped on the next run
the same line-length, indent, style and lucisv version — is skipped on the next run
and reported as `N files from cache`. Only that \"already formatted\"
verdict is ever cached: a file that would be reformatted, or that failed,
is re-checked every run. The cache is one text file under `.lucisv_cache/`;
@@ -288,10 +301,12 @@ CONFIGURATION:
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
read by lucisv-server only — the CLI reads a filelist only when `-f` names
one, so `lucisv rtl/` always means the directory it was given). One table
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
paths, resolved against the config file's own directory). A command line
one, so `lucisv rtl/` always means the directory it was given). The
`[format]` table takes `style` (a preset name, as `--style`) and
`uvm-utils-indent` (true/false). The `[lint]` table takes `select` and
`ignore` (arrays of rule names, `--select`/`--ignore` semantics) and
`waivers` (an array of waiver file paths, resolved against the config
file's own directory). A command line
flag overrides the file's corresponding key; the other keys still apply —
`--waiver-file` is the exception, and adds to `waivers` rather than
replacing it.
@@ -335,6 +350,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
exclude: Vec::new(),
line_length: None,
indent: None,
style: None,
lines: None,
output_format: OutputFormat::Text,
fix: false,
@@ -400,6 +416,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--indent requires a value")?;
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
}
"--style" => {
let v = args.next().ok_or("--style requires a value")?;
opts.style = Some(config::parse_style(&v)?);
}
"--lines" => {
let v = args.next().ok_or("--lines requires a value")?;
line_specs.push(v);
@@ -526,6 +546,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
fn parse(args: &[&str]) -> Result<Options, 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);
}
#[test]
fn a_style_sets_the_starting_values_and_explicit_ones_win() {
let none = FileConfig::default();
let opts = parse(&["--style", "microsoft", "rtl"]).unwrap();
let config = opts.config_with(&none);
assert_eq!(config.style, style::MICROSOFT);
assert_eq!((config.indent_width, config.max_width), (4, 120));
// The file's explicit keys beat the flag's preset...
let file = FileConfig { indent: Some(3), ..Default::default() };
assert_eq!(opts.config_with(&file).indent_width, 3);
assert_eq!(opts.config_with(&file).max_width, 120);
// ...and the flag beats the file's style.
let google = FileConfig { format_style: Some("google"), ..Default::default() };
assert_eq!(opts.config_with(&google).style, style::MICROSOFT);
let opts = parse(&["--indent", "2", "rtl"]).unwrap();
let config = opts.config_with(&google);
assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2));
// No style anywhere is exactly the old default.
let config = parse(&["rtl"]).unwrap().config_with(&none);
assert_eq!(config.style, style::LUCISV);
}
#[test]
fn an_unknown_style_names_the_styles() {
let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") };
assert!(message.contains("unknown style `allman`"), "{message}");
assert!(
message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
"{message}"
);
assert!(parse(&["--style"]).is_err());
}
/// `lucisv_core` keeps its own copy of the names so it can reject a bad
/// `[format] style` without depending on the formatter; this is the test
/// that keeps the copy honest.
#[test]
fn the_core_style_names_are_the_formatter_presets() {
let mut names: Vec<&str> = style::names().collect();
names.push("auto");
assert_eq!(names, config::STYLE_NAMES);
for name in config::STYLE_NAMES {
assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name));
}
}
#[test]
fn config_excludes_are_appended_to_cli_excludes() {
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
+1
View File
@@ -338,6 +338,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
line_length: config.max_width,
indent: config.indent_width,
uvm_utils_indent: config.uvm_utils_indent,
style: config.style_name(),
}
}
+28 -2
View File
@@ -1268,7 +1268,8 @@ impl TempDir {
}
/// One hand-written cache line, for the tests that forge entries. The
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`,
/// and the style is always the default, `lucisv`.
fn cache_line(
path: &str,
content: &str,
@@ -1278,7 +1279,7 @@ fn cache_line(
version: &str,
) -> String {
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
}
#[test]
@@ -2241,11 +2242,33 @@ fn unlock(dir: &TempDir) {
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), and there a
/// directory the walk cannot read cannot be built, so the tests below say so
/// and stop instead of asserting a warning that cannot happen.
#[cfg(unix)]
fn listing_is_refused() -> bool {
use std::os::unix::fs::PermissionsExt;
let probe = TempDir::new("mode-probe");
let shut = probe.path.join("shut");
std::fs::create_dir(&shut).expect("probe dir");
std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o000)).expect("chmod");
let refused = std::fs::read_dir(&shut).is_err();
let _ = std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o755));
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
if !listing_is_refused() {
return;
}
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
@@ -2262,6 +2285,9 @@ fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted()
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
if !listing_is_refused() {
return;
}
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
+171
View File
@@ -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));
}
+76 -21
View File
@@ -12,6 +12,8 @@ use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::config::STYLE_NAMES;
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
@@ -35,6 +37,10 @@ pub struct Entry {
/// The `[format] uvm-utils-indent` that verdict was reached under: it
/// changes the output of a UVM class, so it is part of the key.
pub uvm_utils_indent: bool,
/// The `[format] style` that verdict was reached under, one of
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
/// differently, so it is part of the key.
pub style: &'static str,
}
/// The cache for one run: loaded once at startup, written once at exit.
@@ -107,8 +113,8 @@ impl Cache {
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
);
}
text
@@ -154,28 +160,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let fields: Vec<&str> = line.splitn(6, '\t').collect();
let fields: Vec<&str> = line.splitn(7, '\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
[content, line_length, indent, uvm, style, version, path] => {
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
if path.is_empty() {
return None;
}
if version == VERSION {
// A style this build does not know is another build's
// entry: stale, not corrupt.
let known = STYLE_NAMES.into_iter().find(|n| *n == style);
if let (Some(style), true) = (known, version == VERSION) {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
Entry { content, line_length, indent, uvm_utils_indent, style },
);
}
}
// A store written before `uvm-utils-indent` joined the key: a
// well-formed line of that older shape says nothing about the
// option, so it is dropped individually, exactly like another
// version's entry. (The version field alone already makes such
// a store miss; the codec stays self-describing anyway.)
// Anything else on five fields is corruption and discards the
// file like any other malformed line.
// A store written before `style` joined the key: a well-formed
// line of that older shape says nothing about the style, so it is
// dropped individually, exactly like another version's entry.
[content, line_length, indent, uvm, _version, path] => {
prefix(content, line_length, indent)?;
uvm.parse::<bool>().ok()?;
if path.is_empty() {
return None;
}
}
// And the same for the shape before `uvm-utils-indent` joined it.
// (The version field alone already makes such a store miss; the
// codec stays self-describing anyway.) Anything else on five or
// six fields is corruption and discards the file like any other
// malformed line.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
@@ -228,7 +245,7 @@ mod tests {
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
}
#[test]
@@ -262,6 +279,7 @@ mod tests {
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
@@ -276,7 +294,7 @@ mod tests {
let mut cache = Cache::load(&dir.path);
cache.record(&file, on);
cache.store();
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
assert!(dir.cache_text().contains("\t100\t2\ttrue\tlucisv\t"), "{}", dir.cache_text());
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, on));
@@ -291,7 +309,7 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
@@ -308,6 +326,37 @@ mod tests {
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
}
#[test]
fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() {
// The six-field shape lucisv wrote before `style` joined the key, and
// a style this build does not know: both stale, never corruption.
let dir = TempDir::new("nostyle");
let old = dir.file("old.sv");
let other = dir.file("other.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
other.to_string_lossy(),
3,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted");
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) }));
assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) }));
assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key");
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
@@ -325,7 +374,7 @@ mod tests {
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
@@ -350,13 +399,19 @@ mod tests {
"0000000000000001\t100\t2\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good =
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
let good = format!(
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
file.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
@@ -369,8 +424,8 @@ mod tests {
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
+56 -6
View File
@@ -11,7 +11,14 @@ use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
/// Config file names, in the order a directory is probed.
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
/// The names `[format] style` accepts: the formatter's presets, in its
/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so
/// does not depend on the formatter; the two lists are held equal by a test
/// in the `lucisv` crate, which sees both.
pub const STYLE_NAMES: [&str; 7] =
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
@@ -34,6 +41,9 @@ pub struct FileConfig {
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<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.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
@@ -176,23 +186,30 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
style, uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
/// One key of the `[format]` table: the named `style`, or a boolean that
/// defaults to off, because it changes how already-clean files are laid out
/// and a project has to opt in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "style" {
if config.format_style.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.format_style = Some(parse_style(&parse_string(value)?)?);
return Ok(());
}
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
(known keys: style, uvm-utils-indent)"
))
}
};
@@ -203,6 +220,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
Ok(())
}
/// One of [`STYLE_NAMES`], exactly as spelt there.
pub fn parse_style(name: &str) -> Result<&'static str, String> {
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", "))
})
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
@@ -614,6 +638,32 @@ exclude = [ \"build\", \"*_gen.sv\", ]
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
}
/// `[format] style` names a preset; anything else is an error that lists
/// the presets, the way an unknown key lists the keys.
#[test]
fn the_format_table_carries_a_style() {
assert_eq!(ok("[format]\nstyle = \"google\"").format_style, Some("google"));
assert_eq!(ok("[format]\nstyle = \"lucisv\" # the default").format_style, Some("lucisv"));
assert_eq!(ok("indent = 4").format_style, None);
for name in STYLE_NAMES {
assert_eq!(ok(&format!("[format]\nstyle = \"{name}\"")).format_style, Some(name));
}
let unknown = err("[format]\nstyle = \"gogle\"");
assert!(unknown.contains("unknown style `gogle`"), "{unknown}");
assert!(
unknown.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
"{unknown}"
);
assert!(err("[format]\nstyle = \"Google\"").contains("unknown style `Google`"));
assert!(err("[format]\nstyle = google").contains("expected a quoted string"));
assert!(
err("[format]\nstyle = \"ansi\"\nstyle = \"nxp\"").contains("duplicate key `style`")
);
// Like `uvm-utils-indent`, it lives in `[format]` and nowhere else.
assert!(err("style = \"google\"").contains("unknown key `style`"));
assert!(err("[lint]\nstyle = \"google\"").contains("unknown key `style` under `[lint]`"));
}
/// Everything about the table's shape, the way the `[lint]` table's is
/// pinned: an unknown key is named, a non-boolean value is refused, and a
/// repeated key is an error rather than a last-one-wins.
+39
View File
@@ -731,6 +731,13 @@ mod tests {
}
}
#[cfg(unix)]
impl Drop for TempTree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
@@ -794,12 +801,41 @@ mod tests {
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
/// Whether file modes bind this process: a mode-000 `rel` (a directory
/// when `rel` ends in `/`, else a file) refuses to be read. Root reads it
/// anyway (Linux CI jobs run as root), so the unreadable-path tests below
/// cannot build their path there; they say so and stop.
#[cfg(unix)]
fn reading_is_refused(rel: &str) -> bool {
let probe = TempTree::new("mode-probe");
let path = probe.path.join(rel);
if rel.ends_with('/') {
std::fs::create_dir(&path).expect("probe dir");
} else {
probe.write(rel, "");
}
probe.chmod(rel, 0o000);
let refused = if rel.ends_with('/') {
std::fs::read_dir(&path).is_err()
} else {
std::fs::File::open(&path).is_err()
};
probe.chmod(rel, 0o755);
if !refused {
eprintln!("skipped: a mode-000 `{rel}` is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
if !reading_is_refused("shut/") {
return;
}
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
@@ -815,6 +851,9 @@ mod tests {
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
if !reading_is_refused("shut") {
return;
}
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
+23
View File
@@ -274,6 +274,25 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Whether file modes bind this process: a mode-555 directory under `dir`
/// refuses a new file. Root writes it anyway (Linux CI jobs run as root),
/// so there the half of the test below that needs a directory refusing
/// the temp file cannot be built; it says so and stops.
#[cfg(unix)]
fn creating_is_refused(dir: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = dir.join("mode-probe");
fs::create_dir(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
let refused = fs::write(shut.join("x"), "").is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
}
refused
}
#[cfg(unix)]
#[test]
fn a_write_that_fails_after_another_landed_says_what_was_written() {
@@ -290,6 +309,10 @@ mod tests {
let refused = commit(&[&first, &second], name).unwrap_err();
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
if !creating_is_refused(&dir) {
fs::remove_dir_all(dir).unwrap();
return;
}
// … but a directory that will not take the temp file fails only at
// the write, after `a.sv` landed: said, not hidden.
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
+3 -1
View File
@@ -161,7 +161,9 @@ impl Runs {
}
waivers.absorb(file);
}
let format = vlog_formatter::Config::default();
// The width and indent the file would be formatted with, its style's
// included, so the linter and the formatter cannot disagree.
let format = super::format::formatter_config(config);
Ok(Run {
rules,
options,
+26 -3
View File
@@ -119,9 +119,10 @@ fn fixed_and_formatted(
}
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
/// `Options::config_with` with no command-line flags.
fn formatter_config(file: &FileConfig) -> Config {
let mut config = Config::default();
/// `Options::config_with` with no command-line flags: the style first, then
/// the explicit keys over the preset's indent and width.
pub(super) fn formatter_config(file: &FileConfig) -> Config {
let mut config = file.format_style.and_then(Config::named).unwrap_or_default();
if let Some(width) = file.line_length {
config.max_width = width;
}
@@ -195,3 +196,25 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
.iter()
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_formatter::style;
/// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no
/// flags does: the style first, the explicit keys over its numbers.
#[test]
fn the_style_comes_first_and_explicit_keys_win() {
let none = formatter_config(&FileConfig::default());
assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100));
let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() };
let config = formatter_config(&ansi);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80));
let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi };
let config = formatter_config(&narrowed);
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90));
let auto = FileConfig { format_style: Some("auto"), ..Default::default() };
assert!(formatter_config(&auto).auto_style);
}
}
+21
View File
@@ -242,11 +242,32 @@ fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
/// Whether file modes bind this process: a mode-555 directory refuses a new
/// file. Root writes it anyway (Linux CI jobs run as root), so there an
/// unwritable cache directory cannot be built; the test says so and stops.
#[cfg(unix)]
fn creating_is_refused(scratch: &Scratch) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = scratch.0.join("mode-probe");
fs::create_dir_all(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
let refused = fs::write(shut.join("x"), "").is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
}
refused
}
#[cfg(unix)]
#[test]
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
if !creating_is_refused(&scratch) {
return;
}
fs::create_dir_all(scratch.cache()).unwrap();
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
let stderr = whole_session(&scratch);
+21
View File
@@ -444,6 +444,24 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), so there a cache
/// directory without permission cannot be built; the test says so and stops.
#[cfg(unix)]
fn listing_is_refused(scratch: &Scratch) -> bool {
use std::os::unix::fs::PermissionsExt;
let shut = scratch.0.join("mode-probe");
fs::create_dir_all(&shut).unwrap();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).unwrap();
let refused = fs::read_dir(&shut).is_err();
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
fs::remove_dir_all(&shut).unwrap();
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
/// A cache directory with no permissions at all (mode 000, holding a whole
/// honest editor store): nothing can be read, so the start is cold; the
/// answers are right; the exit says it could not write, once; the store in
@@ -453,6 +471,9 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
if !listing_is_refused(&scratch) {
return;
}
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let before = hash_file(&scratch.editor_store());
+404
View File
@@ -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(&notification(method, doc(&a)));
assert_eq!(styles.recall(&a), None, "{method}");
}
styles.remember(&a, style::GOOGLE);
styles.remember(&b, style::NXP);
styles.notice(&notification(
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(&notification(
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");
}
}
+105 -9
View File
@@ -197,17 +197,86 @@ impl Candidates {
/// patched: this file's old words are given back and its new ones taken,
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
#[cfg(test)]
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.update_words(index, path, words_in(text));
}
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
#[cfg(test)]
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.take_index_tables(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] in two halves, for a caller that knows
/// which it needs: the word table patched by this file alone…
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
self.set_words(path, words);
}
/// …and the two index-derived tables re-derived for the names one file declared
/// before or declares now — `symbols` its units and connection members,
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
/// the only entries its update can move.
///
/// Exact because every table here is one block per exact name ([`word_cmp`]
/// is total, so equal keys are equal names) and each block is read off
/// the index for that name alone: the unit block from the symbol listing
/// restricted to the name, in the listing's order and deduplicated the
/// same way; a module name present exactly when some unit of it is
/// instantiable; a macro's entry from its first definition in file order.
/// So a block re-derived here is the block a whole re-derivation gives,
/// and every other block is untouched by an update that does not name it.
///
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
pub fn refresh_names(
&mut self,
index: &WorkspaceIndex,
symbols: &HashSet<&str>,
macros: &HashSet<&str>,
) {
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
let mut held = std::mem::take(&mut self.units);
held.retain(|unit| !symbols.contains(unit.name.as_str()));
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
for name in symbols {
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
(Ok(at), false) => {
self.modules.remove(at);
}
(Err(at), true) => self.modules.insert(at, name.to_string()),
_ => {}
}
}
let mut fresh: Vec<Macro> = macros
.iter()
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
.collect();
sort_by_name(&mut fresh, |m| m.name.as_str());
let mut held = std::mem::take(&mut self.macros);
held.retain(|m| !macros.contains(m.name.as_str()));
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
}
/// Every table, rendered for comparison — the equivalence witness the
/// incremental tests hold an updated workspace to a rebuilt one with.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
word_files.sort();
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
per_file.sort();
format!(
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
)
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
@@ -715,7 +784,15 @@ fn char_mask(text: &str) -> u32 {
/// tables want the same records. It is paid once per index build rather than
/// once per keystroke, which is the whole point of both.
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
let symbols = index.workspace_symbols("");
unit_tables(index, index.workspace_symbols(""))
}
/// [`index_tables`] over a given part of the symbol listing — all of it, or
/// the names one update touched — in the listing's own order.
fn unit_tables(
index: &WorkspaceIndex,
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
) -> (Vec<Candidate>, Vec<String>) {
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
// case-folded one — so same-named declarations are already adjacent and a
// plain `dedup` leaves one entry per module name, in `str` order. That is
@@ -757,14 +834,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
out.push(Macro {
name: define.name.clone(),
detail: format!("`define {}{args}", define.name),
});
out.push(macro_of(define));
}
}
sort_by_name(&mut out, |m| m.name.as_str());
@@ -772,6 +842,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// One `` `define``'s completion entry.
fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) }
}
/// Two lists sorted by [`word_cmp`] with no name in common, as one.
fn merge_by_name<T>(held: Vec<T>, fresh: Vec<T>, name: impl Fn(&T) -> &str) -> Vec<T> {
let mut out = Vec::with_capacity(held.len() + fresh.len());
let mut fresh = fresh.into_iter().peekable();
for item in held {
while let Some(next) =
fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less)
{
out.push(next);
}
out.push(item);
}
out.extend(fresh);
out
}
/// Every distinct identifier one file's token stream contains.
///
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
@@ -786,6 +881,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// one pass at the end: no part of a scan may be longer than one file, or the
/// message queue goes unanswered for the length of it
/// (`docs/features/scan-interleave/README.md`).
#[cfg(test)]
pub(crate) fn words_in(text: &str) -> Vec<String> {
words::harvest_text(text)
}
+9
View File
@@ -708,10 +708,19 @@ mod tests {
/// therefore in `includers()`/`include_sources()` — the narrowing must not
/// accidentally depend on the include's target spelling matching the
/// disk's.
///
/// Only a case-insensitive filesystem (macOS, Windows by default) resolves
/// the mismatched spelling at all; on a case-sensitive one (Linux) there
/// is no include to narrow in, so the test checks which it is on and stops
/// there, saying so.
#[test]
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
let tree = Tree::new("case_mismatch");
tree.write("rtl/defs.svh", "`define W 8\n");
if !tree.path.join("rtl/DEFS.svh").is_file() {
eprintln!("skipped: this filesystem is case-sensitive; `DEFS.svh` names no file");
return;
}
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
let ws = tree.workspace();
+97 -6
View File
@@ -15,7 +15,7 @@ use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_selection, format_source, Config, LineRanges};
use vlog_formatter::{format_selection, format_source, style, Config, LineRanges, Style};
use crate::settings::ClientSettings;
use crate::state::Document;
@@ -55,6 +55,16 @@ pub struct Settings {
/// Each rung applies only where every rung above it is silent, so a project
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
/// before either existed.
///
/// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2
/// and 4 first, and supplies the indent and width the other keys then
/// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3:
/// `tabSize` is sent whether or not anyone chose it, and the editor's own
/// default of 4 silently undoing `google`'s 2 is not what choosing a style
/// asked for. With no style chosen — or `lucisv`, which is what VS Code sends
/// when nobody touched the drop-down, and which means exactly "what lucisv
/// always did", or `auto`, which chooses a layout but no size — rung 3
/// behaves exactly as it always has.
pub fn settings_for(
doc: &Document,
client: &ClientSettings,
@@ -86,10 +96,16 @@ pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings)
/// invent an edit from it.
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, 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 {
return Ok(None);
return None;
}
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })
}
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
@@ -184,7 +200,16 @@ fn lines_of(range: Range) -> (u32, u32) {
/// lightbulb the editor requests on every cursor move would be noise.
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
let (file, _problem) = discover(path);
file.indent.or(client.indent).unwrap_or(Config::default().indent_width)
file.indent
.or(client.indent)
.unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent)
}
/// The preset a project or a user picked for this buffer, `lucisv.toml`
/// first; `None` when neither did, or when the pick is `auto`, which names
/// no preset and so no indent.
fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option<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
@@ -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
/// way to set a width from an editor without a `lucisv.toml`.
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
let mut config = Config::default();
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
let named = file.format_style.or(client.style).and_then(Config::named);
// `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;
}
if let Some(indent) = client.indent {
@@ -554,6 +583,68 @@ mod tests {
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]
fn each_key_climbs_the_ladder_independently() {
// A `lucisv.toml` naming only `indent` must not also claim the width:
+2
View File
@@ -1572,6 +1572,8 @@ mod qa_hover_declarations {
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
// Its one user is the case-insensitive-filesystem test below.
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::str::FromStr;
fn temp_dir(tag: &str) -> PathBuf {
+106 -23
View File
@@ -86,7 +86,7 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
///
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
/// ([`IncludeGraph::update_held`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -107,6 +107,11 @@ pub struct IncludeGraph {
/// a single file — which is what makes an incrementally widened graph
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
raw: HashMap<PathBuf, Vec<PathBuf>>,
/// Every held file's `` `include`` lines as written, resolved or not — so
/// a file appearing or vanishing anywhere on disk can be answered by
/// re-resolving just the lines that could name it
/// ([`IncludeGraph::refresh_naming`]), without reading a file.
lines: HashMap<PathBuf, Vec<Include>>,
/// Every in-scope file, exactly as the index spells it.
known: HashSet<PathBuf>,
/// Lower-cased spelling → the one in-scope file that has it, or `None`
@@ -154,29 +159,81 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
/// Re-scan one file's `` `include``s, the rest of the graph left standing —
/// for a file whose text changed while the file set did not, a save of a
/// file the index already holds. The known-file and folded-spelling tables
/// are a function of the file set, and every other file's edges a function
/// of its own text and those tables, so only this file's edges are
/// re-scanned and re-spelled (`docs/features/localized-reindex/README.md`).
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-**resolved** against the disk. So a file appearing or
/// vanishing on disk does not change whether some other file's
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
/// held edge *is* re-spelled against the new file list, because that half
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
/// this is used in — one file's text changed, the file set did not — there
/// is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
/// Until 2026-11-19 this was `update_file`, which also re-learned both
/// tables and re-spelled every edge — O(files) for an answer that cannot
/// move. Its one honest limit is unchanged: an edge of a *different* file
/// is not re-**resolved** against the disk, which is why the incremental
/// path takes only a file the index already holds.
pub fn update_held(&mut self, path: &Path, text: &str) {
self.rescan_edges(path, text);
self.respell();
self.respell_one(path);
}
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
/// Re-resolve the `` `include`` lines of every held file that writes one
/// whose last component could be `path`'s name — the only lines a file
/// appearing, vanishing or moving at `path` can change the answer of,
/// whether or not `path` is in scope: an include is resolved against the
/// disk, not against the scope (`docs/features/localized-reindex`, QA F1).
///
/// The name is compared case-insensitively, so a case-insensitive disk is
/// covered, and a target with no last component (`..`) counts as naming
/// everything. Reads no file: the lines are held.
pub fn refresh_naming(&mut self, path: &Path) {
self.refresh_naming_all(std::slice::from_ref(&path.to_path_buf()));
}
/// [`IncludeGraph::refresh_naming`] for every path of one watcher event
/// at once: one pass over the held lines for the whole set of names, so a
/// burst of ten thousand generated files costs one pass, not ten thousand
/// (QA R2-1). A line is re-resolved exactly when it would have been for
/// one of the paths alone, and re-resolving a file twice gives what once
/// does, so the batch is the same answer.
pub fn refresh_naming_all(&mut self, paths: &[PathBuf]) {
let folded = |name: &std::ffi::OsStr| name.to_string_lossy().to_lowercase();
let names: HashSet<String> =
paths.iter().filter_map(|path| path.file_name()).map(folded).collect();
if names.is_empty() {
return;
}
let could_name = |include: &Include| {
Path::new(&include.target).file_name().is_none_or(|last| names.contains(&folded(last)))
};
let mut naming: Vec<PathBuf> = self
.lines
.iter()
.filter(|(_, lines)| lines.iter().any(could_name))
.map(|(from, _)| from.clone())
.collect();
naming.sort();
for from in naming {
let lines = self.lines.get(&from).cloned().unwrap_or_default();
self.rescan_found(&from, &lines);
self.respell_one(&from);
}
}
/// Re-spell one file's edges from its raw ones.
fn respell_one(&mut self, path: &Path) {
match self.raw.get(path) {
Some(targets) => {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
self.edges.insert(path.to_path_buf(), spelled);
}
None => {
self.edges.remove(path);
}
}
}
/// [`IncludeGraph::update_held`] for a batch of files whose `` `include``
/// lines have already been read, with the `+incdir+`s the scope resolves
/// to right now — the form a scan publishing what it has indexed so far
/// uses. The lines come from the step that indexed each file, for the
@@ -203,11 +260,29 @@ impl IncludeGraph {
self.respell();
}
/// Take `path` into the file set: known, folded, and every held edge
/// re-spelled against the new set — what [`IncludeGraph::from_includes`]
/// over the old set and `path` would have learned. Its own edges are
/// [`IncludeGraph::update_held`]'s business.
pub fn add_known(&mut self, path: &Path) {
if !self.known.insert(path.to_path_buf()) {
return;
}
if let Some(key) = path.to_str().map(str::to_lowercase) {
self.folded
.entry(key)
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.to_path_buf()));
}
self.respell();
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.raw.remove(path);
self.lines.remove(path);
self.respell();
}
@@ -223,6 +298,10 @@ impl IncludeGraph {
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
let targets: Vec<PathBuf> =
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
match found.is_empty() {
true => self.lines.remove(path),
false => self.lines.insert(path.to_path_buf(), found.to_vec()),
};
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
@@ -425,6 +504,9 @@ impl IncludeGraph {
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
let mut lines: Vec<(&PathBuf, &Vec<Include>)> = self.lines.iter().collect();
lines.sort_by_key(|(path, _)| *path);
out.push_str(&format!("lines {lines:?}\n"));
out
}
}
@@ -952,7 +1034,10 @@ mod qa_scope_probe {
}
}
#[cfg(test)]
/// Both probes need `is_file` to succeed for a spelling the file does not
/// have, which only a case-insensitive filesystem does — macOS's and
/// Windows' defaults — so the module is scoped to them.
#[cfg(all(test, any(target_os = "macos", target_os = "windows")))]
mod qa_round2 {
use super::*;
use std::fs;
@@ -963,7 +1048,6 @@ mod qa_round2 {
/// unconditionally once a collision exists, so a third colliding entry is
/// a no-op over an already-`None` slot rather than something that could
/// re-arm it — confirmed here rather than only read off the source.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn three_files_colliding_on_one_folded_spelling_stay_ambiguous() {
let dir =
@@ -995,7 +1079,6 @@ mod qa_round2 {
/// must come back exactly as before this fix — `folded` only ever learns
/// about in-scope files, so an out-of-scope collision has no entry to
/// find and falls through to the "no match" arm, unchanged.
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged() {
let dir =
+103 -77
View File
@@ -354,6 +354,7 @@ mod tests {
use super::*;
use lsp_types::{Position, Range};
use std::path::PathBuf;
use std::time::{Duration, Instant};
/// A fast-path document over `text`.
fn large(text: &str) -> Document {
@@ -793,51 +794,44 @@ mod tests {
/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for
/// 2x, and 596x faster at the top.
///
/// The bound is wall-clock, loose, and in debug (this test runs in the
/// normal suite): ~4x the measured debug cost of the largest size, which
/// the quadratic version overshoots by more than two orders of magnitude.
/// A regression in *kind* fails it; a slow CI box does not.
/// The bound is on the **shape** of the cost, not its size: the fastest
/// of five timings at each size, and the largest size (8x the tokens of
/// the smallest) may cost at most [`GROWTH_SLACK`] times 8x the smallest.
/// Linear is ~8x; the quadratic version is ~64x (73x in the release
/// numbers above). A wall-clock ceiling was here first and failed on the
/// CPU-capped Linux runner in debug, where everything is ~15x slower but
/// still 2x for 2x; a ratio holds on any machine. Shown to trip, with the
/// per-call converter put back into `tokens::flatten`, in
/// `docs/features/linux-test-portability/README.md`.
#[test]
fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() {
use std::time::Instant;
for count in [5_000u32, 10_000, 20_000, 40_000] {
// One line: `module m; wire a0,a1,...,last;` — realistic in shape
// (a wide declaration), synthetic only in how wide.
let mut text = String::from("module m; wire ");
for n in 0..count {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\nendmodule\n");
let doc = large(&text);
let clock = Instant::now();
let window = window(&doc, range(0, 1));
let lex_elapsed = clock.elapsed();
assert!(!window.tokens.is_empty());
let clock2 = Instant::now();
let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1));
let colour_elapsed = clock2.elapsed();
eprintln!(
"{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \
{} tokens answered",
text.len(),
data.len() / 5
);
assert!(!data.is_empty(), "the window really did colour something");
assert!(
colour_elapsed.as_millis() < COLOUR_BUDGET_MS,
"colouring {count} tokens on one line cost {colour_elapsed:?} — \
the quadratic conversion is back"
);
let sizes = [5_000u32, 10_000, 20_000, 40_000];
let docs: Vec<Document> = sizes
.iter()
.map(|&count| {
// One line: `module m; wire a0,a1,...,last;` — realistic in
// shape (a wide declaration), synthetic only in how wide.
let mut text = String::from("module m; wire ");
for n in 0..count {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\nendmodule\n");
large(&text)
})
.collect();
for doc in &docs {
assert!(!window(doc, range(0, 1)).tokens.is_empty());
}
let costs = fastest_of_five(&docs, |doc| {
let clock = Instant::now();
let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1));
let elapsed = clock.elapsed();
assert!(!data.is_empty(), "the window really did colour something");
elapsed
});
assert_grows_linearly(&sizes, &costs, "colouring tokens on one line");
}
/// The wall-clock ceiling the test above holds the colourer to, in a
/// **debug** build: 4.5x the slowest of the four sizes as measured on the
/// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over
/// four runs), where the quadratic version this replaced would need tens
/// of seconds.
const COLOUR_BUDGET_MS: u128 = 350;
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
/// fast-path consumer of `Positions`: `references`' hits still have to
/// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one
@@ -848,50 +842,82 @@ mod tests {
///
/// `large_scan` now walks the hits with one `Positions::walker`, which
/// they are already in ascending order for. This runs at an eighth of the
/// original probe's line lengths so it can live in the normal suite; the
/// bound is debug wall-clock and ~4x the measured cost, which a return of
/// the per-hit rescan overshoots by two orders of magnitude.
/// original probe's line lengths so it can live in the normal suite. The
/// hits and the line both grow with `width`, so the walker's work (each
/// byte of the line once) is linear in it and the per-hit rescan's (the
/// line once per hit) quadratic; the bound is the same shape check as the
/// colour test's above, and shown to trip the same way.
#[test]
fn references_on_one_giant_line_locate_their_hits_in_linear_time() {
use std::time::Instant;
for width in [100u32, 200, 400, 800] {
// One line: `wire sig;` filler `sig` filler `sig` ... — `width`
// occurrences of the needle spread over one line, all comfortably
// under REFERENCE_LIMIT so the cap is not what is being timed.
let mut text = String::from("wire sig;");
for _ in 0..width {
text.push_str(&" filler_word ".repeat(250));
text.push_str("sig");
}
text.push('\n');
let doc = large(&text);
let clock = Instant::now();
let hits = references(&doc, 5, true);
let scan_elapsed = clock.elapsed();
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
let sizes = [100u32, 200, 400, 800];
let docs: Vec<(Document, Vec<TextRange>)> = sizes
.iter()
.map(|&width| {
// One line: `wire sig;` filler `sig` filler `sig` ... —
// `width` occurrences of the needle spread over one line, all
// comfortably under REFERENCE_LIMIT so the cap is not what is
// being timed.
let mut text = String::from("wire sig;");
for _ in 0..width {
text.push_str(&" filler_word ".repeat(250));
text.push_str("sig");
}
text.push('\n');
let doc = large(&text);
let hits = references(&doc, 5, true);
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
(doc, hits)
})
.collect();
let costs = fastest_of_five(&docs, |(doc, hits)| {
let positions = doc.positions();
let clock2 = Instant::now();
let clock = Instant::now();
// Exactly what `Server::large_scan` does with them.
let mut walker = positions.walker();
for hit in &hits {
for hit in hits {
std::hint::black_box(walker.range(*hit));
}
let locate_elapsed = clock2.elapsed();
eprintln!(
"{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}",
text.len()
);
assert!(
locate_elapsed.as_millis() < LOCATE_BUDGET_MS,
"locating {width} hits on one line cost {locate_elapsed:?} — \
the per-hit line rescan is back"
);
}
clock.elapsed()
});
assert_grows_linearly(&sizes, &costs, "locating hits on one line");
}
/// The wall-clock ceiling for the locator above, in a **debug** build:
/// 4.7x the slowest of the four sizes as measured on the machine this was
/// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four
/// runs).
const LOCATE_BUDGET_MS: u128 = 150;
/// How much faster than its input a linear-time test's cost may grow
/// before it fails: 3x, so 24x for an 8x input, where linear measures
/// ~8x (macOS and the Linux runner alike) and quadratic ~64x.
const GROWTH_SLACK: f64 = 3.0;
/// The fastest of five timings of `run` on each input. The rounds go over
/// all the inputs in turn, so a burst of load from the tests running
/// beside this one slows one sample of each size rather than every sample
/// of one. Five, not three: QA saw 18.2x of the 24x limit at three under
/// 2x CPU oversubscription, and more rounds is the margin that does not
/// loosen what the test can see.
fn fastest_of_five<T>(inputs: &[T], mut run: impl FnMut(&T) -> Duration) -> Vec<Duration> {
let mut fastest = vec![Duration::MAX; inputs.len()];
for _ in 0..5 {
for (best, input) in fastest.iter_mut().zip(inputs) {
*best = (*best).min(run(input));
}
}
fastest
}
/// Fails unless the cost at the largest size is within [`GROWTH_SLACK`]
/// of linear growth from the smallest.
#[track_caller]
fn assert_grows_linearly(sizes: &[u32], costs: &[Duration], what: &str) {
for (size, cost) in sizes.iter().zip(costs) {
eprintln!("{what}: {size} → {cost:?}");
}
let (first, last) = (sizes[0], sizes[sizes.len() - 1]);
let input = f64::from(last) / f64::from(first);
let growth =
costs[costs.len() - 1].as_secs_f64() / costs[0].as_secs_f64().max(f64::MIN_POSITIVE);
assert!(
growth <= GROWTH_SLACK * input,
"{what}: {input}x the input cost {growth:.1}x the time ({costs:?}) — \
more than {GROWTH_SLACK}x linear, the quadratic conversion is back"
);
}
}
+86 -1
View File
@@ -304,7 +304,17 @@ fn configured(
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
// The formatter's width ladder, so a line lucisv wrote is never a line
// lucisv calls too long: an explicit width (`lucisv.toml`, then the
// editor), else the chosen style's width (`lucisv.toml`'s `style`, then
// `lucisv.format.style`), else the default. `auto` names no preset and so
// no width — it falls through to the default, as it does in the
// formatter (`docs/features/format-styles/README.md`, Handshakes).
let styled = file.format_style.or(client.style).and_then(vlog_formatter::style::preset);
let width = file
.line_length
.or(client.line_length)
.unwrap_or_else(|| styled.map_or(DEFAULT_LINE_LENGTH, |style| style.line_length));
(options, width, file, problems)
}
@@ -731,6 +741,81 @@ mod tests {
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
/// Whether the server flags `line-length` on a line of `columns`
/// characters, in a scratch tree governed by `toml` (none for `None`),
/// with the editor's `lucisv.format.style` set to `editor_style`.
fn flags_a_line_of(
columns: usize,
toml: Option<&str>,
editor_style: Option<&'static str>,
) -> bool {
let dir = std::env::temp_dir().join(format!(
"lucisv_lint_width_{}_{columns}_{}",
std::process::id(),
toml.map_or(0, str::len) + editor_style.map_or(0, str::len) * 1000
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
if let Some(toml) = toml {
std::fs::write(dir.join("lucisv.toml"), toml).expect("config");
}
let text = format!("module m;\n // {}\nendmodule\n", "x".repeat(columns - 5));
let path = dir.join("m.sv");
std::fs::write(&path, &text).expect("source");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { style: editor_style, ..ClientSettings::default() });
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text);
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let flagged = diagnostics_in(doc, &run)
.iter()
.any(|d| d.code == Some(NumberOrString::String("line-length".into())));
let _ = std::fs::remove_dir_all(&dir);
flagged
}
/// The width `lucisv check` holds the same file to: the CLI's own ladder,
/// an explicit width over the named style's over the default
/// (`lucisv`'s `Options::config_with`), with the editor's style standing
/// in for `--style`.
fn check_width(explicit: Option<usize>, style: Option<&str>) -> usize {
let config = style.and_then(vlog_formatter::Config::named).unwrap_or_default();
explicit.unwrap_or(config.max_width)
}
#[test]
fn line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use() {
// One rung each, from the top: an explicit width beats a style; a
// project's style; the editor's style; the default; and `auto`, which
// names no width and so takes the default.
let rungs: [(&str, Option<&str>, Option<&'static str>, usize); 5] = [
(
"explicit",
Some("line-length = 120\n[format]\nstyle = \"ansi\"\n"),
None,
check_width(Some(120), Some("ansi")),
),
(
"project style",
Some("[format]\nstyle = \"ansi\"\n"),
None,
check_width(None, Some("ansi")),
),
("editor style", None, Some("microsoft"), check_width(None, Some("microsoft"))),
("default", None, None, check_width(None, None)),
("auto", Some("[format]\nstyle = \"auto\"\n"), None, check_width(None, Some("auto"))),
];
assert_eq!(rungs.map(|r| r.3), [120, 80, 120, 100, 100], "premise: the widths check uses");
for (rung, toml, editor, width) in rungs {
assert!(
!flags_a_line_of(width, toml, editor),
"{rung}: a line of exactly {width} is fine"
);
assert!(flags_a_line_of(width + 1, toml, editor), "{rung}: one column more is flagged");
}
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
+1
View File
@@ -6,6 +6,7 @@
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
//! `docs/features/lucisv-server/README.md`.
mod auto_style;
mod candidates;
mod code_action;
mod completion;
@@ -92,7 +92,7 @@ impl Server {
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
pub(super) fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
+15 -6
View File
@@ -26,7 +26,7 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.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
// 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
@@ -45,7 +45,8 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.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.edits(result)
}
@@ -65,7 +66,8 @@ impl Server {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let result = format::ranges_formatting(doc, &settings.config, &params.ranges);
let config = self.auto_styles.concrete(&uri, doc, settings.config);
let result = format::ranges_formatting(doc, &config, &params.ranges);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
@@ -98,9 +100,16 @@ impl Server {
return to_value(Vec::<lsp_types::TextEdit>::new());
};
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.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 edits =
on_type::on_type_formatting(doc, at.position, &params.ch, &settings.config, auto_end);
let edits = on_type::on_type_formatting(doc, at.position, &params.ch, &config, auto_end);
to_value(edits)
}
@@ -133,7 +142,7 @@ impl Server {
// so the ladder runs without its `tabSize` rung.
let 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.edits(result)
}
+99 -15
View File
@@ -18,9 +18,21 @@ use super::batch::opened_in;
use super::client::{notify_on, plural};
use super::progress::IndexWatch;
use super::{Server, INTERLEAVE_ABOVE};
use crate::state::{IndexEvent, Scan, Workspace};
use crate::state::{IndexEvent, OneFile, Scan, Watched, Workspace};
use crate::{design_hierarchy, file_ops};
/// A watcher event naming more than one path per `BURST_DIVISOR` files the
/// index holds takes the whole rescan instead of being sorted path by path.
///
/// Measured on the full OpenTitan `hw` tree (4 058 files, release, one
/// notification of generated files under a gitignored directory, medians of
/// 3): sorting costs ~0.10 ms a path (1 000 paths 0.10 s, 5 000 paths 0.50 s),
/// a cached whole rescan ~0.16 ms an indexed file (0.63–0.65 s) — so the two
/// cross near 1.6 paths per file, and both scale with the tree. Dividing by 2
/// keeps the sorted path at or under ~0.3× the rescan it saves on any tree
/// (QA R2-1: never slower than 7408fac's one rescan per notification).
const BURST_DIVISOR: usize = 2;
impl Server {
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
@@ -59,15 +71,22 @@ impl Server {
/// that file is one the index already holds. Reports whether it ran; a
/// `false` means the caller owes a whole rebuild.
///
/// Everything a rebuild does *after* the scan happens here too, for the
/// same reasons: the code-lens refresh (the file that moved may have
/// changed an instantiation count in any buffer), the diagnostics
/// generation bump (every open buffer's diagnostics are computed against
/// the index), and a republish of every open buffer. The republish stays
/// wholesale rather than narrowing to the buffers that could have moved:
/// a lint reads the index, so any buffer's diagnostics may have changed,
/// and narrowing it correctly needs a dependency graph this server does not
/// have. Worth doing later; wrong to guess at now.
/// When the index moved, everything a rebuild does *after* the scan
/// happens here too, for the same reasons: the code-lens refresh (the file
/// that moved may have changed an instantiation count in any buffer), the
/// hierarchy view's invalidation, the diagnostics generation bump (every
/// open buffer's diagnostics are computed against the index), and a
/// republish of every open buffer. The republish stays wholesale: a lint
/// reads the index, so any buffer's diagnostics may have changed, and it
/// costs ~0.3 ms a buffer on OpenTitan — narrowing it would buy nothing
/// measurable for the one place a stale squiggle could hide
/// (`docs/features/localized-reindex/README.md`).
///
/// When the file's record did **not** move — the watcher's echo of the
/// save that just ran, a save of an unchanged buffer — every answer read
/// off the index alone is the answer it already was, so no lens refresh
/// and no hierarchy invalidation is sent. The republish still is: see
/// below.
///
/// Three things a whole rebuild does that this deliberately does not:
///
@@ -93,19 +112,84 @@ impl Server {
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
let outcome = self.workspace.update_one_file(path);
if outcome == OneFile::NotHeld {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
self.hierarchy_index_changed();
// Lenses and the hierarchy view are read off the index alone, so an
// unchanged record owes them nothing. Diagnostics are not: a lint
// also reads the buffer's `lucisv.toml` and waiver files from disk,
// which no notification reports, and a save has always been when an
// edit to them takes effect (QA F2). So every save republishes.
if outcome == OneFile::Changed {
self.refresh_code_lenses();
self.hierarchy_index_changed();
}
self.republish_all();
// The unchanged case says so inside the parentheses, so every reader
// of the old `reindex_one(<path>) took <ms>` shape still matches.
let unchanged = if outcome == OneFile::Unchanged { ", unchanged" } else { "" };
self.timed(started, |took| {
format!("reindex_one({}{unchanged}) took {took}", path.display())
});
true
}
/// The rescan a watcher event owes, decided file by file
/// ([`Workspace::watched`]): a file the scope provably cannot take — a
/// generated file under a gitignored directory, one outside the folder
/// scope or the filelist — owes nothing; a held file, by whatever
/// spelling the client used, is the one-file update; anything the scope
/// may take and the index does not hold is a whole rebuild, and so are
/// two or more held files, exactly as a checkout always was.
///
/// `named` is every path the event named, any extension: the include
/// lines that could name one are re-resolved first, unless the event takes
/// the whole rescan, which re-resolves all of them (QA F1). An event that owes the index
/// nothing still republishes every open buffer, for the reason
/// [`Server::reindex_one`] gives.
pub(super) fn reindex_watched(
&mut self,
paths: &[std::path::PathBuf],
named: &[std::path::PathBuf],
) {
// A burst — a branch switch, a generator run — is sorted file by file
// only while that is cheaper than the rescan it replaces.
if paths.len().saturating_mul(BURST_DIVISOR) > self.workspace.index().files().len() {
return self.reindex();
}
self.workspace.refresh_includes_naming(named);
let mut held: Vec<std::path::PathBuf> = Vec::new();
for path in paths {
match self.workspace.watched(path) {
Watched::Held(spelled) => held.push(spelled),
Watched::Outside => {}
Watched::Unknown => return self.reindex(),
}
}
held.sort();
held.dedup();
match held.as_slice() {
[] => self.republish_all(),
[one] => {
if !self.reindex_one(one) {
self.reindex();
}
}
_ => self.reindex(),
}
}
/// Every open buffer's diagnostics said again, under a new generation so
/// a pulling client asks again too — what a save owes even when the index
/// did not move. ~0.3 ms a buffer on OpenTitan.
pub(super) fn republish_all(&mut self) {
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
+5
View File
@@ -135,6 +135,11 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<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
/// reported (§42.2). Interior-mutable because a lint pass runs behind
/// `&self` — the pull models compute diagnostics inside a `map` over the
@@ -25,6 +25,7 @@ use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::uri::uri_to_path;
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
@@ -55,6 +56,7 @@ impl Server {
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
// flush, so the flush below already publishes everything.
let released = self.forget_port_entry(&method, &notification);
self.auto_styles.notice(&notification);
// Everything but a `didChange` needs the buffers' analyses current —
// 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
@@ -125,6 +127,7 @@ impl Server {
.unwrap_or("");
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
// flush looks it up for a connection entry to hold back.
let now = std::time::Instant::now();
@@ -134,8 +137,18 @@ impl Server {
}
DidSaveTextDocument::METHOD => {
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
// A save carrying the text the buffer already holds — the
// normal case, since every change was flushed above — has
// nothing to re-analyze. One carrying different text is a
// change the server missed: analyzed and published here,
// so the buffer's own answer is current whatever the
// reindex below finds moved.
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
let uri = p.text_document.uri.clone();
if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
}
// A save is one of the things that rebuild the index; the
// others are a change to `lucisv.exclude`/`lucisv.filelist`
@@ -158,15 +171,28 @@ impl Server {
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
// Whatever else the event owes, every path it names may
// be what an `include` line was looking for — in scope or
// not, of a source extension or not (QA F1). A rescan
// re-resolves every line anyway, so only the paths that
// do not take one are refreshed here.
let named: Vec<std::path::PathBuf> =
p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect();
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
// One file named is the incremental case; a checkout
// filling the list, or the filelist itself moving, is
// the whole rebuild.
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
if watch::names_a_config(&p.changes) {
// A `lucisv.toml` moves excludes, the filelist and
// the lint configuration at once — for the client
// that forwards it (ours registers sources only).
self.reindex();
} else if watch::touches_scope(&p.changes, filelist.as_deref()) {
// The filelist itself moving is the whole rebuild;
// anything else is sorted file by file.
match watch::scope_files(&p.changes, filelist.as_deref()) {
Some(paths) => self.reindex_watched(&paths, &named),
None => self.reindex(),
}
} else {
self.workspace.refresh_includes_naming(&named);
}
}
}
@@ -259,6 +285,7 @@ impl Server {
/// about what a setting *does* any more than `settings::from_payload` and
/// `from_section` can disagree about what it says.
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
self.auto_styles.forget_all();
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
@@ -146,6 +146,7 @@ impl Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
auto_styles: Default::default(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
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!(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());
}
@@ -0,0 +1,754 @@
//! The localized reindex held to a whole rebuild through the real server
//! (`docs/features/localized-reindex/README.md`).
//!
//! Every step goes through the notifications an editor sends — a change, a
//! save and the watcher's echo of it for an open buffer; a watcher event alone
//! for a file rewritten, created or deleted on disk — and after every step the
//! server's state is compared with what a whole rebuild over the same disk and
//! the same buffers gives: the index (postings and readers table included),
//! the completion tables, the include graph, every open buffer's cross-file
//! answers, and **the diagnostics last published for every open buffer**. The
//! last is the one the narrowing could get wrong without any table showing it:
//! a buffer the server decided not to republish must still be showing what a
//! fresh analysis would say.
use std::collections::BTreeMap;
use super::*;
/// A session over a scratch tree, with what it last published per buffer.
struct Mirror {
tree: Tree,
session: Session,
open: BTreeMap<PathBuf, (Uri, i32)>,
shown: BTreeMap<String, Value>,
/// Whole rescans seen, so a sweep can say how much of it the narrowed
/// path carried.
rescans: usize,
}
impl Mirror {
fn new(name: &str, files: &[(&str, &str)], open: &[&str]) -> Mirror {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
Mirror::over(tree, open)
}
fn over(tree: Tree, open: &[&str]) -> Mirror {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Mirror::with(tree, open, wide)
}
fn with(tree: Tree, open: &[&str], settings: ClientSettings) -> Mirror {
// A client that shows a bar, so a whole rescan is visible as one.
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::started(vec![tree.path.clone()], abilities, settings);
let mut mirror =
Mirror { tree, session, open: BTreeMap::new(), shown: BTreeMap::new(), rescans: 0 };
for rel in open {
let path = mirror.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("an open buffer's file is on disk");
let uri = mirror.session.open(&path, &text);
mirror.open.insert(path, (uri, 1));
}
mirror.absorb();
mirror
}
/// Remember the newest diagnostics the server pushed for each buffer, and
/// count the whole rescans (a progress bar begun) among the steps.
fn absorb(&mut self) {
for message in self.session.drain() {
let Message::Notification(n) = message else { continue };
if n.method == PublishDiagnostics::METHOD {
let published: PublishDiagnosticsParams =
serde_json::from_value(n.params).expect("publish params");
let shown = serde_json::to_value(&published.diagnostics).expect("diagnostics");
self.shown.insert(published.uri.as_str().to_string(), shown);
} else if n.method == Progress::METHOD && n.params.to_string().contains("\"begin\"") {
self.rescans += 1;
}
}
}
/// Write `rel` as an editor does: through its buffer when it is open (the
/// change, the save, the disk, the watcher's echo), else on disk alone
/// with the watcher's event.
fn write(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
let created = !path.exists();
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidChangeTextDocument::METHOD, change);
self.tree.write(rel, text);
self.session.notify(DidSaveTextDocument::METHOD, save);
} else {
self.tree.write(rel, text);
}
let kind = if created { FileChangeType::CREATED } else { FileChangeType::CHANGED };
self.event(&path, kind);
}
/// Delete a closed file on disk, as a checkout does.
fn delete(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
assert!(!self.open.contains_key(&path), "the sweep deletes closed files only");
std::fs::remove_file(&path).expect("delete");
self.event(&path, FileChangeType::DELETED);
}
/// Save an open buffer that has not changed, and the watcher's echo — a
/// save the index records nothing about.
fn save_only(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let (uri, _) = self.open.get(&path).cloned().expect("an open buffer");
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidSaveTextDocument::METHOD, save);
self.event(&path, FileChangeType::CHANGED);
}
/// Rewrite an open buffer's file on disk behind the editor's back: the
/// editor reloads the clean buffer (a change carrying the disk's text),
/// and the watcher reports the file. No save.
fn disk_only(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
self.tree.write(rel, text);
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
self.session.notify(DidChangeTextDocument::METHOD, change);
}
self.event(&path, FileChangeType::CHANGED);
}
/// Open a file that is on disk, after the startup scan.
fn open_file(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("on disk");
let uri = self.session.open(&path, &text);
self.open.insert(path, (uri, 1));
}
fn event(&mut self, path: &Path, typ: FileChangeType) {
let changes = vec![FileEvent { uri: path_to_uri(path).expect("uri"), typ }];
self.session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
/// The whole claim: what the server holds and last showed is what a whole
/// rebuild over the same disk and buffers gives. The rebuild is done in
/// place, so a run that passes goes on from the state it already had.
fn holds(&mut self, step: &str) {
self.absorb();
let workspace = &mut self.session.server.workspace;
let incremental = workspace.derived_fingerprint();
workspace.rebuild_index();
let rebuilt = workspace.derived_fingerprint();
if incremental != rebuilt {
let first = incremental.lines().zip(rebuilt.lines()).find(|(a, b)| a != b);
panic!("{step}: the incremental state is not a rebuild's; first difference {first:?}");
}
for (uri, _) in self.open.values() {
let fresh = self.session.server.diagnostics_of(uri);
let fresh = serde_json::to_value(&fresh).expect("diagnostics");
let shown = self.shown.get(uri.as_str()).cloned().unwrap_or(Value::Null);
assert_eq!(shown, fresh, "{step}: {} shows stale diagnostics", uri.as_str());
}
}
/// Every step, each followed by the check.
fn steps(&mut self, steps: &[(&str, &str)]) {
self.holds("before any step");
for (at, (rel, text)) in steps.iter().enumerate() {
self.write(rel, text);
self.holds(&format!("step {at}, `{rel}`"));
}
}
}
const LEAF: &str =
"module leaf (input logic clk, output logic q);\n logic s;\n assign q = s;\nendmodule\n";
const TOP: &str = "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n";
const TB: &str = "module tb;\n top dut ();\n initial $display(dut.u_leaf.s);\nendmodule\n";
const PKG: &str =
"package cfg_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n";
const USER: &str = "module user import cfg_pkg::*; (input word_t a, output word_t b);\n assign b = a + W;\nendmodule\n";
const DEFS: &str = "`define WIDTH 8\n`define CLOG(x) $clog2(x)\n";
const INCLUDER: &str =
"`include \"defs.svh\"\nmodule includer;\n logic [`WIDTH-1:0] v;\nendmodule\n";
fn design() -> Vec<(&'static str, &'static str)> {
vec![
("rtl/leaf.sv", LEAF),
("rtl/top.sv", TOP),
("dv/tb.sv", TB),
("rtl/cfg_pkg.sv", PKG),
("rtl/user.sv", USER),
("rtl/defs.svh", DEFS),
("rtl/includer.sv", INCLUDER),
]
}
#[test]
fn every_kind_of_edit_to_an_open_module_leaves_the_rebuilt_state_and_every_squiggle() {
let mut mirror =
Mirror::new("lr_module", &design(), &["rtl/leaf.sv", "rtl/top.sv", "dv/tb.sv"]);
let open_leaf = |text: &str| ("rtl/leaf.sv", text.to_string());
let steps = [
// Nothing the index records: a comment after the last token.
open_leaf(&format!("{LEAF}// trailing\n")),
// A body edit, a local signal, a comment above everything.
open_leaf(&LEAF.replace("assign q = s;", "assign q = ~s;")),
open_leaf(&LEAF.replace(" logic s;\n", " logic s;\n logic t;\n")),
open_leaf(&format!("// above\n{LEAF}")),
// The port list: renamed, removed, added — `top` connects by name, so
// its unknown-port squiggles must follow without `top` being saved.
open_leaf(&LEAF.replace("input logic clk", "input logic clock")),
open_leaf(&LEAF.replace("input logic clk, ", "")),
open_leaf(&LEAF.replace("output logic q", "output logic q, input logic en")),
// The signal the testbench names hierarchically, gone and back.
open_leaf(&LEAF.replace("logic s;\n assign q = s;", "logic r;\n assign q = r;")),
// The module renamed away, so `top`'s instantiation resolves nowhere.
open_leaf(&LEAF.replace("module leaf", "module leaf2")),
open_leaf(LEAF),
];
let steps: Vec<(&str, &str)> = steps.iter().map(|(rel, text)| (*rel, text.as_str())).collect();
mirror.steps(&steps);
}
#[test]
fn edits_to_a_closed_package_a_define_header_and_an_include_line_all_hold() {
let mut mirror = Mirror::new("lr_package", &design(), &["rtl/user.sv", "rtl/includer.sv"]);
let user_text = USER.replace("+ W", "+ W + DEPTH");
let pkg_depth =
PKG.replace("localparam int W = 8;", "localparam int W = 8;\n localparam int DEPTH = 4;");
let defs_more = format!("{DEFS}`define DEPTH 4\n");
let includer_none = INCLUDER.replace("`include \"defs.svh\"\n", "");
let pkg_renamed = PKG.replace("package cfg_pkg", "package cfg2_pkg");
let defs_wider = DEFS.replace("8", "16");
let defs_params = DEFS.replace("CLOG(x)", "CLOG(x, y)");
let includer_nowhere = INCLUDER.replace("defs.svh", "nowhere.svh");
let steps: Vec<(&str, &str)> = vec![
// A package member the open user does not name yet, then does.
("rtl/cfg_pkg.sv", &pkg_depth),
("rtl/user.sv", &user_text),
// The package member it names, gone.
("rtl/cfg_pkg.sv", PKG),
// The package renamed.
("rtl/cfg_pkg.sv", &pkg_renamed),
("rtl/cfg_pkg.sv", PKG),
// A define header: a value, a new macro, a parameter list.
("rtl/defs.svh", &defs_wider),
("rtl/defs.svh", &defs_more),
("rtl/defs.svh", &defs_params),
// An include line removed and put back, and one that resolves nowhere.
("rtl/includer.sv", &includer_none),
("rtl/includer.sv", INCLUDER),
("rtl/includer.sv", &includer_nowhere),
("rtl/includer.sv", INCLUDER),
];
mirror.steps(&steps);
}
#[test]
fn a_signal_another_file_mentions_keeps_its_lint_answer_as_the_mention_comes_and_goes() {
// `unused-signal` consults the workspace census: `dbg` is unused in
// `probe.sv` but named by `peek.sv`, which is closed. The open buffer is
// never saved here, so only a republish the narrowing owed can move it.
let probe = "module probe;\n logic dbg;\nendmodule\n";
let peek = "module peek;\n initial $display(probe.dbg);\nendmodule\n";
let mut mirror =
Mirror::new("lr_census", &[("probe.sv", probe), ("peek.sv", peek)], &["probe.sv"]);
mirror.steps(&[
("peek.sv", "module peek;\n initial $display(1);\nendmodule\n"),
("peek.sv", peek),
("peek.sv", &format!("{peek}// a comment that moves nothing\n")),
]);
}
#[test]
fn files_created_and_deleted_beside_open_buffers_hold() {
let mut mirror = Mirror::new("lr_files", &design(), &["rtl/top.sv", "rtl/includer.sv"]);
mirror.holds("before any step");
// A second `leaf` makes the instantiation ambiguous; deleting it heals it.
mirror.write("rtl/zz_leaf.sv", LEAF);
mirror.holds("a duplicate module created");
mirror.delete("rtl/zz_leaf.sv");
mirror.holds("and deleted");
mirror.delete("rtl/defs.svh");
mirror.holds("an included header deleted");
mirror.write("rtl/defs.svh", DEFS);
mirror.holds("and recreated");
}
#[test]
fn a_watcher_event_for_a_file_the_scope_cannot_take_costs_no_rescan() {
// A generated file under a gitignored directory, and a file outside the
// workspace root: neither can change the index, so neither may cost the
// progress bar — and the state is still a rebuild's.
let mut mirror = Mirror::new("lr_outside", &design(), &["rtl/top.sv"]);
mirror.tree.write(".gitignore", "build/\n");
mirror.holds("before any step");
let _ = mirror.session.drain();
mirror.write("build/gen.sv", "module gen;\nendmodule\n");
assert!(mirror.session.progress().is_empty(), "no bar for a gitignored file");
mirror.holds("a generated file under build/");
let outside = Tree::new("lr_outside_elsewhere");
outside.write("far.sv", "module far;\nendmodule\n");
let _ = mirror.session.drain();
mirror.event(&outside.path.join("far.sv"), FileChangeType::CHANGED);
assert!(mirror.session.progress().is_empty(), "no bar for a file outside every root");
mirror.holds("a file outside the root");
// A file the scope does take, appearing, is still the whole rebuild —
// which is also what proves the two assertions above can fail.
mirror.rescans = 0;
mirror.write("rtl/new.sv", "module fresh;\nendmodule\n");
mirror.holds("a new file in scope");
assert_eq!(mirror.rescans, 1, "a file the scope takes appearing is a rescan");
assert!(
mirror.session.server.workspace.index().units("fresh").len() == 1,
"the new file is in the index"
);
}
#[test]
fn a_buffer_opened_from_outside_the_filelist_joins_the_index_on_its_first_save() {
// VS Code restores editors while the startup scan runs; one outside the
// filelist is open but not indexed until something rebuilds. Its first
// save used to be that rebuild, bar and all.
let mut files = design();
files.push(("rtl/waits.sv", "`include \"late.svh\"\nmodule waits;\nendmodule\n"));
files.push(("files.f", "rtl/leaf.sv\nrtl/top.sv\nrtl/cfg_pkg.sv\nrtl/waits.sv\n"));
let tree = Tree::new("lr_filelist");
for (rel, text) in &files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv", "dv/tb.sv"], listed);
mirror.rescans = 0;
mirror.write("dv/tb.sv", &TB.replace("$display", "$write"));
mirror.holds("the first save of the unlisted buffer");
assert_eq!(mirror.rescans, 0, "the buffer was on disk before the scan: no rescan");
assert!(mirror.session.server.workspace.index().units("tb").len() == 1, "and it is indexed");
// A file born after the scan may be what some `include` was waiting
// for — `waits.sv`'s is: its lines are re-resolved, still no rebuild.
mirror.write("rtl/late.svh", "`define LATE 1\n");
let path = mirror.tree.path.join("rtl/late.svh");
let uri = mirror.session.open(&path, "`define LATE 1\n");
mirror.open.insert(path, (uri, 1));
mirror.rescans = 0;
mirror.write("rtl/late.svh", "`define LATE 2\n");
mirror.holds("the first save of a buffer younger than the scan");
assert_eq!(mirror.rescans, 0, "the include waiting for it is re-resolved in place");
let graph = mirror.session.server.workspace.includes();
assert_eq!(graph.reachable(vec![mirror.tree.path.join("rtl/waits.sv")]).len(), 2, "and found");
}
/// QA F1: a header the scope cannot take, appearing and vanishing, moves an
/// in-scope includer's edge — an include is resolved against the disk.
#[test]
fn a_header_outside_the_scope_created_and_deleted_moves_the_includers_edges() {
let files = [
(".gitignore", "gen/\n"),
("rtl/a.sv", "`include \"../gen/h.svh\"\nmodule a;\nendmodule\n"),
("rtl/a_inc.svh", "`include \"../gen/h.svh\"\n`define AW 2\n"),
("rtl/b.sv", "`include \"a_inc.svh\"\nmodule b;\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f1_ignored", &files, &["rtl/b.sv"]);
mirror.steps(&[("gen/h.svh", "`define GEN_W 4\n")]);
mirror.rescans = 0;
mirror.delete("gen/h.svh");
mirror.holds("the ignored header deleted");
mirror.write("gen/h.svh", "`define GEN_W 5\n");
mirror.holds("and created again");
assert_eq!(mirror.rescans, 0, "the include graph alone, never a rescan");
}
/// QA R2-1: one event naming a burst of files is sorted path by path only
/// while that is cheaper than a rescan (`BURST_DIVISOR`); past it the event
/// takes the whole rescan. The state is a rebuild's on both sides.
#[test]
fn a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above() {
let mut files = design();
files.push((".gitignore", "gen/\n"));
files.push(("rtl/waits.sv", "`include \"../gen/h0.svh\"\nmodule waits;\nendmodule\n"));
let mut mirror = Mirror::new("lr_burst", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
let held = mirror.session.server.workspace.index().files().len();
let burst = |mirror: &mut Mirror, count: usize, tag: &str| {
let changes: Vec<FileEvent> = (0..count)
.map(|k| {
let rel = format!("gen/{tag}{k}.svh");
mirror.tree.write(&rel, &format!("`define {}{k} 1\n", tag.to_uppercase()));
let path = mirror.tree.path.join(rel);
FileEvent { uri: path_to_uri(&path).expect("uri"), typ: FileChangeType::CREATED }
})
.collect();
let params = DidChangeWatchedFilesParams { changes };
mirror.session.notify(DidChangeWatchedFiles::METHOD, params);
};
mirror.rescans = 0;
burst(&mut mirror, held / 2, "h");
mirror.holds("a burst at the threshold, `h0.svh` among it");
assert_eq!(mirror.rescans, 0, "sorted path by path: {held} held, {} named", held / 2);
burst(&mut mirror, held / 2 + 1, "k");
mirror.write("gen/h0.svh", "`define H0 2\n");
mirror.holds("a burst past the threshold");
assert_eq!(mirror.rescans, 1, "one path more is the whole rescan");
}
/// QA F1, filelist mode: an unlisted header under an `+incdir+`.
#[test]
fn an_unlisted_header_under_an_incdir_created_moves_the_includers_edge() {
let files = [
("files.f", "+incdir+inc\nrtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"h2.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let tree = Tree::new("lr_f1_incdir");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
mirror.write("inc/h2.svh", "`define H2 1\n");
mirror.holds("the unlisted header created");
mirror.delete("inc/h2.svh");
mirror.holds("and deleted");
}
/// QA F2: a `[lint]` edit in `lucisv.toml`, which no notification reports,
/// takes effect at the next save — even one the index records nothing about.
#[test]
fn a_lint_configuration_edit_takes_effect_at_a_save_that_moves_nothing() {
let lint_me = "module lint_me;\n\twire unused_w; \n reg r;\nendmodule\n";
let mut mirror = Mirror::new("lr_f2_toml", &[("rtl/lint_me.sv", lint_me)], &["rtl/lint_me.sv"]);
mirror.holds("before any step");
let uri = mirror.open.values().next().map(|(uri, _)| uri.as_str().to_string()).expect("open");
assert_ne!(mirror.shown.get(&uri), Some(&Value::Array(Vec::new())), "premise: findings");
mirror.tree.write(
"lucisv.toml",
"[lint]\nignore = [\"no-tabs\", \"no-trailing-whitespace\", \"unused-signal\"]\n",
);
mirror.save_only("rtl/lint_me.sv");
mirror.holds("the save after the lint configuration changed");
mirror.tree.write("lucisv.toml", "[lint]\n");
mirror.save_only("rtl/lint_me.sv");
mirror.holds("and after it changed back");
}
/// QA F3: a file moved in from elsewhere after the scan keeps its old times;
/// opened and saved, it joins the index and its waiting includer finds it.
/// No watcher event is sent for the move — a client that does not watch, or
/// an event coalesced away — so the save alone must re-resolve the includer
/// (the event's own re-resolution is F1's test).
#[test]
fn a_file_moved_in_after_the_scan_joins_and_is_found_by_its_includer() {
let files = [
("files.f", "rtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"late.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let elsewhere = Tree::new("lr_f3_elsewhere");
elsewhere.write("late.svh", "`define LATE 7\n");
let tree = Tree::new("lr_f3_moved");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
let moved = mirror.tree.path.join("rtl/late.svh");
std::fs::rename(elsewhere.path.join("late.svh"), &moved).expect("move in");
mirror.open_file("rtl/late.svh");
let (uri, _) = mirror.open[&moved].clone();
let save = serde_json::json!({ "textDocument": { "uri": uri } });
mirror.session.notify(DidSaveTextDocument::METHOD, save);
mirror.holds("opened and saved, with no watcher echo");
}
/// QA F4: an excluded buffer, open and changed on disk, is taken in, as a
/// fresh server takes every open buffer in.
#[test]
fn an_excluded_open_buffer_changed_on_disk_is_taken_in() {
let files = [
("lucisv.toml", "exclude = [\"rtl/b.sv\"]\n"),
("rtl/b.sv", "module b;\nendmodule\n"),
("rtl/top.sv", "module top;\n b u_b ();\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f4_excluded", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
mirror.open_file("rtl/b.sv");
mirror.disk_only("rtl/b.sv", "module b;\n wire w2;\nendmodule\n");
mirror.holds("the excluded buffer changed on disk");
assert_eq!(mirror.session.server.workspace.index().units("b").len(), 1, "taken in");
}
#[cfg(unix)]
#[test]
fn a_held_file_reported_by_its_real_path_takes_the_one_file_update() {
// The workspace is opened through a symlink; the watcher reports the real
// path. Before this round that was a "file the index does not hold" and a
// whole rescan per save.
let real = Tree::new("lr_real");
for (rel, text) in design() {
real.write(rel, text);
}
let link = Tree::new("lr_link");
std::fs::remove_dir_all(&link.path).expect("make room for the link");
std::os::unix::fs::symlink(&real.path, &link.path).expect("symlink");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let mut session = Session::wide_with(vec![link.path.clone()], abilities);
let _ = session.drain();
real.write("rtl/leaf.sv", &LEAF.replace("input logic clk", "input logic clock"));
session.watched(&[real.path.join("rtl/leaf.sv")]);
assert!(session.progress().is_empty(), "the one-file path, not a rescan");
let index = session.server.workspace.index();
assert_eq!(index.member("leaf", "clock").len(), 1, "and the update landed");
assert!(
index.files().iter().all(|path| path.starts_with(&link.path)),
"under the link's spelling"
);
let _ = std::fs::remove_file(&link.path);
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit: a line inserted, deleted, duplicated or swapped with its
/// neighbour, or one identifier renamed to another the file already uses —
/// edits that move spans, names and whole declarations.
fn mutate(text: &str, rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(6) {
0 => lines.insert(at, " // lucisv sweep".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
4 => lines.insert(at, " logic lucisv_sweep_q;".to_string()),
_ => {
let words = vlog_semantic::words::harvest_text(text);
if words.len() >= 2 {
let from = words[rng.below(words.len())].clone();
let to = words[rng.below(words.len())].clone();
if let Some(line) = lines.iter_mut().find(|line| line.contains(from.as_str())) {
*line = line.replacen(from.as_str(), &to, 1);
}
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
/// `steps` seeded mutations over every source file under `tree`, with `open`
/// buffers open, each step checked; now and then a closed file is deleted or
/// a new one created.
fn sweep(tree: Tree, open: usize, seed: u64, steps: usize) {
// `opened` below is also what the lint-configuration step saves.
let mut files: Vec<String> = Vec::new();
collect(&tree.path, &tree.path, &mut files);
files.sort();
assert!(!files.is_empty(), "premise: a tree with sources in it");
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let opened: Vec<String> = (0..open).map(|_| files[rng.below(files.len())].clone()).collect();
let opened_refs: Vec<&str> = opened.iter().map(String::as_str).collect();
// The setting the event kinds QA found need: a gitignored `gen/` whose
// headers an in-scope file waits for, and excluded names to open.
tree.write(".gitignore", "gen/\n");
tree.write("lucisv.toml", "exclude = [\"sweep_excluded_*\"]\n");
let waits: String = (0..4).map(|k| format!("`include \"gen/h{k}.svh\"\n")).collect();
tree.write("sweep_waits.sv", &format!("{waits}module sweep_waits;\nendmodule\n"));
let elsewhere = Tree::new(&format!("lr_sweep_elsewhere_{seed}"));
let mut mirror = Mirror::over(tree, &opened_refs);
mirror.holds(&format!("seed {seed}: before any step"));
mirror.rescans = 0;
for step in 0..steps {
let rel = files[rng.below(files.len())].clone();
let path = mirror.tree.path.join(&rel);
let label = format!("seed {seed}, step {step}, `{rel}`");
match rng.below(24) {
0 if !mirror.open.contains_key(&path) && path.exists() => mirror.delete(&rel),
1 => mirror.write(&format!("sweep_new_{step}.sv"), "module sweep_new;\nendmodule\n"),
// A header outside the scope, waited for, toggled.
2 => {
let header = format!("gen/h{}.svh", rng.below(4));
match mirror.tree.path.join(&header).exists() {
true => mirror.delete(&header),
false => mirror.write(&header, &format!("`define SWEEP_{step} 1\n")),
}
}
// The lint configuration edited, then a save that moves nothing.
3 => {
let rules = ["no-tabs", "unused-signal", "line-length", "no-trailing-whitespace"];
let ignored: Vec<String> = rules
.iter()
.filter(|_| rng.below(2) == 0)
.map(|r| format!("\"{r}\""))
.collect();
let config = format!(
"exclude = [\"sweep_excluded_*\"]\n[lint]\nignore = [{}]\n",
ignored.join(", ")
);
mirror.tree.write("lucisv.toml", &config);
if let Some(open) = opened.get(rng.below(opened.len().max(1))) {
mirror.save_only(open);
}
}
// A file moved in from elsewhere, old times and all, then opened
// and saved.
4 => {
let name = format!("sweep_moved_{step}.svh");
elsewhere.write(&name, &format!("`define SWEEP_MOVED_{step} 1\n"));
let to = mirror.tree.path.join("gen").join(&name);
std::fs::create_dir_all(mirror.tree.path.join("gen")).expect("gen/");
std::fs::rename(elsewhere.path.join(&name), &to).expect("move in");
mirror.event(&to, FileChangeType::CREATED);
let rel = format!("gen/{name}");
mirror.open_file(&rel);
mirror.save_only(&rel);
}
// An excluded file, opened, then changed on disk.
5 => {
let rel = format!("sweep_excluded_{step}.sv");
mirror.write(&rel, &format!("module sweep_excluded_{step};\nendmodule\n"));
mirror.open_file(&rel);
let text = format!("module sweep_excluded_{step};\n wire w;\nendmodule\n");
mirror.disk_only(&rel, &text);
}
_ => {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let text = match mirror.open.contains_key(&path) {
true => mirror.session.server.workspace.text_of(&path).unwrap_or(text),
false => text,
};
mirror.write(&rel, &mutate(&text, &mut rng));
}
}
mirror.holds(&label);
}
eprintln!(
"seed {seed}: {steps} steps over {} files, {} of them whole rescans",
files.len(),
mirror.rescans
);
}
fn collect(root: &Path, dir: &Path, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(root, &path, out);
} else if crate::watch::watched(&path, None) {
if let Ok(rel) = path.strip_prefix(root) {
out.push(rel.to_string_lossy().into_owned());
}
}
}
}
/// Copy every source file under `from` into `tree` under `prefix`, saying
/// how many — none when `from` is not on this machine.
fn copy_into(tree: &Tree, from: &Path, prefix: &str) -> usize {
let mut files: Vec<String> = Vec::new();
collect(from, from, &mut files);
for rel in &files {
let Ok(text) = std::fs::read_to_string(from.join(rel)) else { continue };
tree.write(&format!("{prefix}{rel}"), &text);
}
files.len()
}
fn home(rel: &str) -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rel)
}
#[test]
fn a_seeded_sweep_over_the_hand_written_design_holds() {
for seed in 1..=3 {
let tree = Tree::new(&format!("lr_sweep_{seed}"));
for (rel, text) in design() {
tree.write(rel, text);
}
sweep(tree, 3, seed, 25);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_the_corpus -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over ~/.cache/lucisv-corpus, minutes in a debug build"]
fn a_seeded_sweep_over_the_corpus_holds() {
let from = std::env::var_os("LUCISV_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-corpus"));
for seed in [11, 12, 13] {
let tree = Tree::new(&format!("lr_corpus_{seed}"));
if copy_into(&tree, &from, "") == 0 {
eprintln!("{} not present — skipping", from.display());
return;
}
sweep(tree, 5, seed, 60);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_an_opentitan -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over a sample of OpenTitan, minutes in a debug build"]
fn a_seeded_sweep_over_an_opentitan_sample_holds() {
let hw = std::env::var_os("LUCISV_OPENTITAN")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-opentitan-full/hw"));
for seed in [21, 22] {
let tree = Tree::new(&format!("lr_opentitan_{seed}"));
let mut copied = 0;
for sub in ["ip/uart/", "ip/gpio/", "ip/prim/rtl/", "ip/prim_generic/rtl/", "ip/tlul/rtl/"]
{
copied += copy_into(&tree, &hw.join(sub), sub);
}
if copied == 0 {
eprintln!("{} not present — skipping", hw.display());
return;
}
sweep(tree, 6, seed, 60);
}
}
@@ -56,6 +56,7 @@ mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod localized_reindex;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
@@ -81,17 +81,36 @@ fn an_index_rebuild_moves_the_result_id_too() {
// `inter_file_dependencies: true` is a promise: a save rebuilds the
// index, and what the index says can change what a *different* buffer
// reports. A stale "unchanged" there would be a wrong squiggle.
//
// Since localized-reindex (2026-11-19) the save whose record did not move
// still moves the stamp — a lint reads `lucisv.toml` from disk, and a
// save is when an edit to it takes effect (QA F2) — and so does the save
// of an edit the index has not seen.
let tree = Tree::new("pullreindex");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let stamp = document_pull(&mut session, &uri, None)["resultId"]
.as_str()
.expect("a result id")
.to_string();
let stamp = |session: &mut Session, previous: Option<&str>| {
document_pull(session, &uri, previous)["resultId"]
.as_str()
.expect("a result id")
.to_string()
};
let first = stamp(&mut session, None);
let save = serde_json::json!({ "textDocument": { "uri": uri } });
session.notify(DidSaveTextDocument::METHOD, save.clone());
let after = document_pull(&mut session, &uri, Some(&first));
assert_eq!(after["kind"], "full", "a save that moved no record: {after:#?}");
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let after = document_pull(&mut session, &uri, Some(&stamp));
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module m;\n\twire ;\n wire extra;\nendmodule\n" }],
}),
);
let edited = stamp(&mut session, Some(&first));
session.notify(DidSaveTextDocument::METHOD, save);
let after = document_pull(&mut session, &uri, Some(&edited));
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
}
@@ -201,9 +201,22 @@ fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// Every rescan trigger, one refresh each.
// Every rescan trigger, one refresh each — a save of an edit the index
// has not seen, since a save that moved nothing refreshes nothing
// (localized-reindex, 2026-11-19).
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert!(session.requests().is_empty(), "a save that moved nothing asks for nothing");
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
@@ -223,9 +236,22 @@ fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// A save of an edit the index has not seen, so the save path really
// moves the index (a save that moves nothing refreshes nothing anyway).
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
let index = session.server.workspace.index();
let w = index.member_in("sub", "w", vlog_semantic::Surface::Hierarchical);
assert_eq!(w.len(), 1, "premise: the save moved the index");
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
@@ -368,6 +394,14 @@ fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
let _ = session.drain();
// An edit the index has not seen, so the save moves it.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
@@ -128,10 +128,29 @@ fn the_stages_add_up_to_the_scan_they_describe() {
// the progress callbacks, the per-file word `Vec`, the staging pushes —
// which is deliberately unattributed rather than silently folded into a
// neighbouring stage.
//
// That slack is about a third of an unloaded scan, so one stall landing in
// it (the 4-CPU Linux runner throttles for tens of ms; QA caught 0.43 on
// macOS beside a looping suite) grows `total` and no stage. The upper
// bound is structural — the stages are disjoint pieces of the scan — and
// holds on every scan; the lower bound is a claim about an undisturbed
// scan, so it is asserted on the best of three: a stall spoils one
// sample, not all of them.
let tree = trace_tree("tracesums", 40);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let total = number(&stages, "total");
let mut best = 0.0f64;
for _ in 0..3 {
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let (sum, total) = (named_stage_sum(&stages), number(&stages, "total"));
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
best = best.max(sum / total);
}
assert!(best >= 0.5, "the stages must account for most of it: at best {best:.2} of the scan");
}
/// The sum of every stage a scan's `stages` line names, `total` aside.
fn named_stage_sum(stages: &str) -> f64 {
let named = [
"discovery",
"order",
@@ -157,10 +176,7 @@ fn the_stages_add_up_to_the_scan_they_describe() {
"includes",
"overlay",
];
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
named.iter().map(|key| number(stages, key)).sum()
}
#[test]
+39
View File
@@ -112,6 +112,11 @@ pub struct ClientSettings {
/// declares — the key changes bytes in files that already format cleanly,
/// so nothing turns it on for a user who did not ask.
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.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
@@ -252,6 +257,7 @@ impl Default for ClientSettings {
exclude: Vec::new(),
filelist: None,
uvm_utils_indent: None,
style: None,
inline_templates: None,
inline_instantiation: None,
inline_keywords: None,
@@ -353,6 +359,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
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_instantiation: flag(lucisv.get("inlineInstantiation")),
inline_keywords: flag(lucisv.get("inlineKeywords")),
@@ -581,6 +588,13 @@ fn path(value: Option<&Value>) -> Option<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.
///
/// `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");
}
/// 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
/// 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
+3 -11
View File
@@ -389,18 +389,10 @@ impl Workspace {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
// A broken `lucisv.toml` excludes nothing, and the client's
// `lucisv.exclude` is appended to it — see `walk_excludes`.
let configuring = trace.now();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
let exclude = self.walk_excludes(&mut discovery, root);
ScanTrace::add(&mut trace.config_ms, configuring);
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
+230 -75
View File
@@ -1,96 +1,232 @@
//! Re-indexing one saved file the index already holds, patching every
//! table rather than rebuilding it — the cheap path a `didSave` takes
//! before falling back to a whole rescan.
//! before falling back to a whole rescan — and doing only the work the
//! file's change can reach (`docs/features/localized-reindex/README.md`).
use std::path::Path;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use lucisv_core::walk::dir_id;
use vlog_semantic::FileFacts;
use super::Workspace;
use crate::scan_trace::ScanTrace;
/// What [`Workspace::update_one_file`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OneFile {
/// The index does not hold the file; the caller owes a whole rebuild.
NotHeld,
/// The file's record is the one the index already held — the watcher's
/// echo of a save, or a save that changed nothing the index records — so
/// nothing derived from the index moved and no other buffer's answer can
/// have either.
Unchanged,
/// The index moved, and every open buffer's overlay was refreshed.
Changed,
}
impl Workspace {
/// [`Workspace::update_one_file`], for a test that only asks whether the
/// cheap path was taken.
#[cfg(test)]
pub fn update_one(&mut self, path: &Path) -> bool {
self.update_one_file(path) != OneFile::NotHeld
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
/// contribution exactly as it is, and say what moved.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
/// [`OneFile::NotHeld`] means the caller must fall back to
/// [`Workspace::rebuild_index`]: the file is not one this index already
/// holds, which the cheap path settles only for an open buffer older than
/// the last whole scan ([`Workspace::add_open_buffer`]). A file appearing
/// changes which *other* files exist as far as the include graph is
/// concerned (a `` `include`` that had nothing to resolve to now has
/// something), and answering that takes a walk.
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// * **the workspace index** — [`WorkspaceIndex::update_facts`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
/// rebuild over the same file set would have produced, and say when the
/// record did not move at all;
/// * **the completion tables** — the word table patched by this file's
/// words, and the two index-derived ones re-derived for the names this
/// file declared or declares, only when it now declares something
/// different ([`FileFacts::declares_the_same`]);
/// * **the include graph** — this file's edges re-scanned and re-spelled;
/// nothing else in it depends on one file's text;
/// * **every open buffer's overlay** — refreshed when the index moved,
/// because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
///
/// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts
/// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file
pub fn update_one_file(&mut self, path: &Path) -> OneFile {
if self.index.file_id(path).is_none() {
return self.add_open_buffer(path);
}
// Re-indexing one file *is* the claim that its bytes moved.
self.forget_view(path);
match self.current_text(path) {
Some(text) => {
// The same rule a whole rebuild follows: when the text came
// from an open buffer, that buffer's finished analysis is the
// facts and the words, and neither is derived from the text a
// second time. `current_text` answers with a buffer's text only
// when that buffer is not on the large-file fast path, so the
// analysis found here is a real one.
match self.analysis_of(path) {
Some((facts, words)) => {
self.index.update_facts(facts);
self.candidates.update_words(&self.index, path, words);
}
None => {
self.index.update_file(path.to_path_buf(), &text);
// The words come back out of the record the update
// just wrote, so the file is lexed once rather than
// twice (`FACTS_FORMAT` 13). A path the index somehow
// does not hold falls back to lexing, which is what
// this line always did.
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
Some(words) => self.candidates.update_words(&self.index, path, words),
None => self.candidates.update_file(&self.index, path, &text),
}
}
}
self.includes.update_file(path, &text, self.index.files());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
// one the update just made — no second parse — and it is
// keyed by the text it was made from, which is the buffer's
// when a buffer beat disk. That record is simply never hit
// again if the file on disk says something else.
// A save is the other thing that asks the store something, so
// it opens a re-open a scan deferred rather than writing into
// the store the previous rescan left in hand ([`StoreOpen`]).
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, &text);
}
}
None => {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
let Some(text) = self.current_text(path) else {
self.remove_one(path);
return OneFile::Changed;
};
// The same rule a whole rebuild follows: when the text came from an
// open buffer, that buffer's finished analysis is the facts and the
// words, and neither is derived from the text a second time.
// `current_text` answers with a buffer's text only when that buffer is
// not on the large-file fast path, so the analysis found here is a
// real one. Otherwise the file is parsed once, and its words come back
// out of the record (`FACTS_FORMAT` 13).
let (facts, words) = self.analysis_of(path).unwrap_or_else(|| {
let facts = FileFacts::of(path.to_path_buf(), &text);
let words = facts.words().to_vec();
(facts, words)
});
let declared = self.declared_by_either(path, &facts);
let moved = self.index.update_facts(facts);
// The include lines are not in the record — `` `include "a.svh"`` and
// `` `include <a.svh>`` can read the same to it — so they are
// re-scanned whatever the record said.
self.includes.update_held(path, &text);
self.write_through(path, &text);
if !moved {
return OneFile::Unchanged;
}
self.candidates.set_file_words(path, words);
if let Some((symbols, macros)) = declared {
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
}
self.refresh_overlays();
OneFile::Changed
}
/// The half of [`Workspace::update_one_file`] for a file the index does
/// not hold, which it can settle only for an open buffer — one opened
/// after the last whole scan took its work list, from outside the
/// filelist or under an `exclude`, which a rebuild would take in because
/// every open buffer is taken in.
///
/// What a rebuild would re-read besides the buffer is every other file's
/// `` `include``s, and the only ones the file's arrival can answer
/// differently are those whose last component could be its name — so those
/// are re-resolved ([`IncludeGraph::refresh_naming`]), from the lines the
/// graph holds, against the disk as it is now. No witness of *when* the
/// file appeared is needed, and none is trusted: a birth time was, until
/// QA showed `mv`, `cp -p` and `tar x` set it back (F3).
///
/// The index is merged whole (every id after the new one moves), which
/// is in memory and reads nothing.
///
/// [`IncludeGraph::refresh_naming`]: crate::includes::IncludeGraph::refresh_naming
fn add_open_buffer(&mut self, path: &Path) -> OneFile {
let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld };
let Some(text) = self.current_text(path) else { return OneFile::NotHeld };
if self.holds_another_spelling_of(path) {
// A rebuild would take the buffer's spelling *instead of* the
// held one (`discover.rs`'s `Aliased`), which is not an add.
return OneFile::NotHeld;
}
let (symbols, macros) = facts.declared_names();
let symbols: HashSet<String> = symbols.into_iter().map(str::to_string).collect();
let macros: HashSet<String> = macros.into_iter().map(str::to_string).collect();
self.index.update_facts(facts);
self.candidates.set_file_words(path, words);
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
self.includes.add_known(path);
self.includes.update_held(path, &text);
self.includes.refresh_naming(path);
self.write_through(path, &text);
self.refresh_overlays();
OneFile::Changed
}
/// Whether the index holds the file at `path` under another name — a
/// directory alias — by the test the scan's own overlay applies: the same
/// file name, then the same `(dev, ino)`.
fn holds_another_spelling_of(&self, path: &Path) -> bool {
let Some(id) = dir_id(path) else { return false };
let named = |held: &&PathBuf| held.file_name() == path.file_name();
// By reference: the id is `Copy` on unix and an owned path elsewhere.
self.index.files().iter().filter(named).any(|held| dir_id(held).as_ref() == Some(&id))
}
/// The half of [`Workspace::update_one_file`] for a held file that is
/// gone, capped or unreadable. The files whose `` `include``s could name
/// it are re-resolved, because their lines resolve against the disk and a
/// deleted file is no longer there to find.
fn remove_one(&mut self, path: &Path) {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
self.includes.refresh_naming(path);
self.refresh_overlays();
}
/// Files appeared, vanished or moved at `paths`, wherever they are: the
/// include lines that could name any of them are re-resolved, in one pass.
/// The whole of what such an event owes the graph for a file the index
/// does not hold.
pub fn refresh_includes_naming(&mut self, paths: &[PathBuf]) {
self.includes.refresh_naming_all(paths);
}
/// The names the held record and `facts` put in the completion tables'
/// listings, both records' together — or `None` when the two declare the
/// same things ([`FileFacts::declares_the_same`]) and no listing can move.
fn declared_by_either(
&self,
path: &Path,
facts: &FileFacts,
) -> Option<(HashSet<String>, HashSet<String>)> {
let held = self.index.facts_for(path)?;
if held.declares_the_same(facts) {
return None;
}
let mut symbols: HashSet<String> = HashSet::new();
let mut macros: HashSet<String> = HashSet::new();
for record in [held, facts] {
let (names, defines) = record.declared_names();
symbols.extend(names.into_iter().map(str::to_string));
macros.extend(defines.into_iter().map(str::to_string));
}
Some((symbols, macros))
}
/// Write the file's record through to the persistent store, so an hour of
/// saves is an hour of work the next session does not repeat. The record
/// is the one the update just made — no second parse — and it is keyed by
/// the text it was made from, which is the buffer's when a buffer beat
/// disk; that record is simply never hit again if the file on disk says
/// something else. A save is the other thing that asks the store
/// something, so it opens a re-open a scan deferred rather than writing
/// into the store the previous rescan left in hand ([`StoreOpen`]).
///
/// [`StoreOpen`]: super::StoreOpen
fn write_through(&mut self, path: &Path, text: &str) {
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, text);
}
}
/// Re-resolve every open buffer's cross-file references against the index
/// as it now stands, exactly as a rebuild does.
fn refresh_overlays(&mut self) {
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
@@ -99,20 +235,39 @@ impl Workspace {
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
/// edges, define counts, postings and who read what), the completion
/// tables and the include graph. The workspace is left holding the
/// *rebuilt* index, which is the same index, so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
let before = self.derived_fingerprint();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
assert_eq!(before, self.derived_fingerprint(), "incremental state != rebuilt state");
true
}
/// Everything a rebuild derives from the sources, rendered for comparison:
/// the index, the completion tables, the include graph and every open
/// buffer's cross-file answers.
#[cfg(test)]
pub fn derived_fingerprint(&self) -> String {
let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect();
docs.sort_by_key(|(uri, _)| uri.as_str());
let overlays: Vec<String> = docs
.iter()
.map(|(uri, doc)| {
format!("{} {:?}", uri.as_str(), doc.external.iter().collect::<Vec<_>>())
})
.collect();
format!(
"{}\n{}\n{}\n{}",
self.index.fingerprint(),
self.candidates.fingerprint(),
self.includes.fingerprint(),
overlays.join("\n")
)
}
}
+3
View File
@@ -36,13 +36,16 @@ mod scan;
mod scope;
mod sources;
mod views;
mod watched;
#[cfg(test)]
pub use document::mixed_buffer;
pub use document::{first_token_from, first_token_reaching, Document};
pub use incremental::OneFile;
pub use port_grace::PortGrace;
pub use scan::{IndexEvent, Scan};
pub use views::FileView;
pub use watched::Watched;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
/// to turn its byte span into a line, so an unbounded answer to the empty
@@ -61,6 +61,24 @@ fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
/// Whether file modes bind this process: a mode-000 directory refuses to be
/// listed. Root lists it anyway (Linux CI jobs run as root), so there the
/// directory the scan cannot read cannot be built; the test says so and stops.
#[cfg(unix)]
fn listing_is_refused() -> bool {
use std::os::unix::fs::PermissionsExt;
let probe = Tree::new("modeprobe");
let shut = probe.path.join("shut");
fs::create_dir(&shut).expect("probe dir");
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).expect("chmod");
let refused = fs::read_dir(&shut).is_err();
let _ = fs::set_permissions(&shut, fs::Permissions::from_mode(0o755));
if !refused {
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
}
refused
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
@@ -69,6 +87,9 @@ fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
// existed the walk returned an error the index simply dropped, so a
// permission-denied directory cost every file after it silently.
use std::os::unix::fs::PermissionsExt;
if !listing_is_refused() {
return;
}
let tree = Tree::new("walkwarn");
tree.package("rtl/a.sv", "a");
tree.package("rtl/z.sv", "z");
@@ -25,6 +25,7 @@ mod large_file;
mod lazy_read;
mod open_buffers;
mod persistence;
mod reindex_perf;
mod settings;
mod size_cap;
mod views;
@@ -0,0 +1,206 @@
//! What a save and a keystroke cost the index at OpenTitan scale — the
//! measurements behind `docs/features/localized-reindex/README.md`.
//!
//! Every test here is `#[ignore]`d and asserts nothing but its premises; run
//! them in release, one at a time, through the guard:
//!
//! `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`
//!
//! The tree is `$LUCISV_OPENTITAN` or `~/.cache/lucisv-opentitan-full/hw`;
//! without it every probe says so and returns.
use std::time::{Duration, Instant};
use vlog_semantic::{FileId, SymbolKind};
use super::*;
/// The OpenTitan `hw` tree, when this machine has one.
pub(super) fn opentitan() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
})?;
root.is_dir().then_some(root)
}
/// A workspace over the whole OpenTitan tree, with `open` buffers open.
fn opentitan_workspace(root: &Path, open: &[&str]) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings::default()));
ws.open_whole_workspace(vec![root.to_path_buf()]);
for rel in open {
let path = root.join(rel);
let text = fs::read_to_string(&path).expect("the probe's files are on disk");
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
}
ws
}
fn median(mut runs: Vec<Duration>) -> Duration {
runs.sort();
runs[runs.len() / 2]
}
/// The edits a save is measured after: each is applied to the buffer, then
/// `update_one` runs, then the buffer is put back and updated again.
fn edits(text: &str) -> Vec<(&'static str, String)> {
let body = text.rfind("endmodule").or_else(|| text.rfind("endpackage")).unwrap_or(text.len());
let first = text.find('\n').map_or(0, |at| at + 1);
vec![
("no change (the watcher's echo of a save)", text.to_string()),
("comment appended", format!("{text}\n// an edit\n")),
(
"local signal added",
format!("{} logic probe_local_q;\n{}", &text[..body], &text[body..]),
),
("comment above everything", format!("{}// an edit\n{}", &text[..first], &text[first..])),
]
}
const TARGETS: [&str; 5] = [
"ip/uart/rtl/uart_tx.sv",
"ip/prim_generic/rtl/prim_flop.sv",
"ip/uart/rtl/uart_reg_pkg.sv",
"ip/prim/rtl/prim_assert.sv",
"top_earlgrey/rtl/autogen/top_earlgrey.sv",
];
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_one_saved_file_costs_the_index_at_opentitan_scale() {
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let mut ws = opentitan_workspace(&root, &TARGETS);
assert!(ws.index().files().len() > 3_000, "premise: the whole tree is indexed");
for rel in TARGETS {
let path = root.join(rel);
let uri = crate::uri::path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("on disk");
for (what, edited) in edits(&text) {
let mut runs = Vec::new();
for _ in 0..5 {
ws.set_document(uri.clone(), edited.clone());
let started = Instant::now();
assert!(ws.update_one(&path), "premise: a held file");
runs.push(started.elapsed());
ws.set_document(uri.clone(), text.clone());
ws.update_one(&path);
}
eprintln!("update_one {rel}, {what}: median {:?}", median(runs));
}
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() {
// The three census rules ask `mentioned_outside` once per candidate
// declaration; every net and variable a file declares is the upper bound
// of what one lint pass over that file can ask.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let index = ws.index();
let (mut calls, mut total, mut worst) = (0usize, Duration::ZERO, (Duration::ZERO, 0, None));
for (id, path) in index.files().iter().enumerate() {
let Ok(text) = fs::read_to_string(path) else { continue };
let doc = Document::new(Some(path.clone()), text, index);
let names: Vec<&str> = doc
.semantics
.symbols()
.iter()
.filter(|s| matches!(s.kind, SymbolKind::Net | SymbolKind::Var))
.map(|s| s.name.as_str())
.collect();
let started = Instant::now();
for name in &names {
std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32))));
}
let took = started.elapsed();
calls += names.len();
total += took;
if took > worst.0 {
worst = (took, names.len(), Some(path.clone()));
}
}
eprintln!(
"mention census over {} files: {calls} questions, {:?} each on average; \
worst file {:?} asks {} for {:?}",
index.files().len(),
total / calls.max(1) as u32,
worst.2,
worst.1,
worst.0
);
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_census_adds_to_a_real_lint_pass_at_opentitan_scale() {
// The bound above is every declaration; this is what the rules really
// ask: one buffer's whole lint pass against the indexed workspace, and the
// same pass with no workspace (no census at all), file by file.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let alone = Workspace::default();
let mut added: Vec<(Duration, Duration, PathBuf)> = Vec::new();
for path in ws.index().files() {
let Ok(text) = fs::read_to_string(path) else { continue };
// A fresh document per pass: a document remembers its last lint
// pass (`lint_snapshot`), and a remembered pass costs nothing.
let lint = |within: &Workspace| {
let doc = Document::new(Some(path.clone()), text.clone(), ws.index());
let started = Instant::now();
let run = crate::lint::LintRun::for_document(within, &doc);
std::hint::black_box(crate::diagnostics::all_in(&doc, &run));
started.elapsed()
};
let with = median((0..3).map(|_| lint(&ws)).collect());
let without = median((0..3).map(|_| lint(&alone)).collect());
added.push((with.saturating_sub(without), with, path.clone()));
}
added.sort();
let total: Duration = added.iter().map(|(d, _, _)| *d).sum();
eprintln!(
"census share of a lint pass over {} files: {:?} on average",
added.len(),
total / added.len().max(1) as u32
);
for (delta, with, path) in added.iter().rev().take(5) {
eprintln!(" {delta:?} of {with:?} in {}", path.display());
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_readers_table_holds_at_opentitan_scale() {
// The memory the narrowing costs: one key per table entry any file's
// resolution read, and one file id per reader of it — read back out of
// the fingerprint, which renders the table line by line.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let fingerprint = ws.index().fingerprint();
let lines: Vec<&str> = fingerprint.lines().filter(|line| line.starts_with("read ")).collect();
let readers: usize = lines.iter().map(|line| line.matches(',').count() + 1).sum();
let key_bytes: usize =
lines.iter().filter_map(|line| line.split(' ').nth(2)).map(str::len).sum();
eprintln!(
"readers table over {} files: {} keys ({} KiB of key text), {} reader entries ({} KiB of ids)",
ws.index().files().len(),
lines.len(),
key_bytes / 1024,
readers,
readers * 4 / 1024
);
}
+156
View File
@@ -0,0 +1,156 @@
//! What one path a file watcher named is to the index: a file it holds
//! (perhaps under another spelling), a file the scope provably cannot take,
//! or neither — which only a rescan can settle
//! (`docs/features/localized-reindex/README.md`).
//!
//! A watcher event for a `.sv` the index does not hold used to be a whole
//! rescan, progress bar and all, every time: a generated file under a
//! gitignored build directory, a file outside the folder scope or the
//! filelist, or a held file reported by its real path under a symlinked root.
//! Only the last kind of file can change what the index says, and none of
//! them needs the walk to find that out.
use std::fs;
use std::path::{Path, PathBuf};
use lucisv_core::config::Discovery;
use lucisv_core::walk::collect_files_below;
use super::discover::{oversize, Found};
use super::Workspace;
/// What a watched path is to the index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Watched {
/// A file the index holds, by the spelling it holds it under — or an
/// open buffer it does not hold yet, which a rebuild would take in and the
/// one-file path adds (QA F4).
Held(PathBuf),
/// A file no scan of the scope in force would index. Nothing to do for
/// the index.
Outside,
/// A file the scope may take and the index does not hold: a new file, or
/// one the cap kept out until now. Only a rescan can say.
Unknown,
}
impl Workspace {
/// What `path` is to the index. Errs towards [`Watched::Unknown`]: a
/// wasted rescan costs time, a skipped one would cost a stale index.
pub fn watched(&self, path: &Path) -> Watched {
if let Some(held) = self.held_spelling(path) {
return Watched::Held(held);
}
if self.docs.values().any(|doc| doc.path.as_deref() == Some(path)) {
return Watched::Held(path.to_path_buf());
}
match self.scope_could_take(path) {
true => Watched::Unknown,
false => Watched::Outside,
}
}
/// The spelling the index holds `path` under: `path` itself, or the same
/// file reached through a scope directory's other name — a symlinked root,
/// or a different case on a case-insensitive disk. Resolved through the
/// directories the scope is anchored at, so it costs a handful of
/// `canonicalize` calls rather than one per held file.
fn held_spelling(&self, path: &Path) -> Option<PathBuf> {
let holds = |path: &Path| self.index.file_id(path).is_some();
if holds(path) {
return Some(path.to_path_buf());
}
let real = canonical(path)?;
let mut anchors: Vec<PathBuf> = self.roots.clone();
anchors.extend(self.scope_dirs());
anchors.into_iter().find_map(|anchor| {
let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?;
let spelled = anchor.join(rest);
holds(&spelled).then_some(spelled)
})
}
/// Whether a scan of the scope in force could index `path` — `false` only
/// when it provably could not: a filelist that does not list it, or a
/// walk of the scope's directories that does not find it or finds it over
/// `lucisv.index.maxFileSize`. The walk is `lucisv_core`'s own, rooted
/// where the scan's is, so `.gitignore`, `exclude` and the config's
/// excludes rule it out exactly as they rule it out of a scan.
fn scope_could_take(&self, path: &Path) -> bool {
if let Some(list) = self.filelist_path() {
// An unreadable filelist sends the scan to the rungs below, and
// so it sends this.
if let Ok(list) = lucisv_core::filelist::read(&list) {
return list.files.iter().any(|listed| same_file(listed, path));
}
}
let Some(dir) = path.parent() else { return true };
let dirs = match self.walks_the_workspace() {
true => self.roots.clone(),
false => self.scope_dirs(),
};
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
// The flat read of a rootless session: siblings only.
return dirs.iter().any(|scope| scope == dir);
}
dirs.iter()
.filter(|scope| path.starts_with(scope))
.any(|scope| self.walk_finds(scope, path))
}
/// Whether a walk of `scope` finds `path` under its cap.
fn walk_finds(&self, scope: &Path, path: &Path) -> bool {
let Some(dir) = path.parent() else { return true };
let excludes = self.walk_excludes(&mut Discovery::new(true), scope);
let mut found = None;
let take = &mut |file: PathBuf, len| {
if file == path {
found = Some(Found { path: file, len });
}
};
if collect_files_below(scope, dir, &excludes, true, take, &mut |_| {}).is_err() {
// The directory is gone or unreadable: nothing in it can be read
// either, and the scan would say the same.
return false;
}
found.is_some_and(|found| oversize(&found, self.client.max_file_size, &mut 0).is_none())
}
/// The exclude patterns a walk rooted at `dir` applies: the governing
/// config's, then the client's `lucisv.exclude`. *Appended*, never
/// substituted — the CLI appends a config's excludes to `--exclude` the
/// same way, and a setting that silently dropped a checked-in exclude
/// would put vendored code back in the index for one user only.
pub(super) fn walk_excludes(&self, discovery: &mut Discovery, dir: &Path) -> Vec<String> {
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a server
// that comes up empty. The error is reported when the user formats a
// file in this tree (`format::settings_for`).
let mut exclude = discovery.for_dir(dir).unwrap_or_default().exclude.unwrap_or_default();
exclude.extend(self.client.exclude.iter().cloned());
exclude
}
}
/// Whether two spellings name one file: equal, or equal once resolved. The
/// names are compared first, case-insensitively, so a filelist of thousands
/// costs a resolution only for the entries that could be the one.
fn same_file(listed: &Path, path: &Path) -> bool {
if listed == path {
return true;
}
let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_lowercase());
name(listed) == name(path)
&& canonical(listed).is_some()
&& canonical(listed) == canonical(path)
}
/// `path` with every symlink resolved and, on a case-insensitive disk, every
/// component in the case the disk holds it in. A file that is gone resolves
/// through its directory, so a deletion can still be matched.
fn canonical(path: &Path) -> Option<PathBuf> {
fs::canonicalize(path).ok().or_else(|| {
let real = fs::canonicalize(path.parent()?).ok()?;
Some(real.join(path.file_name()?))
})
}
+20 -13
View File
@@ -112,16 +112,16 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
/// Every path an event named that the index reads, each once and in order —
/// or `None` when one of them is the filelist, whose change moves the whole
/// scope and is a rebuild by definition. A client is free to send `Changed`
/// and `Created` for one file, and that is still one file.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
/// What `server/index.rs`'s `reindex_watched` sorts into held, outside and
/// unknown files (`docs/features/localized-reindex/README.md`); until
/// 2026-11-19 this was `one_scope_file`, which gave up on any list longer
/// than one.
pub fn scope_files(changes: &[FileEvent], filelist: Option<&Path>) -> Option<Vec<PathBuf>> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
@@ -129,10 +129,17 @@ pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
(!named.iter().any(|path| Some(path.as_path()) == filelist)).then_some(named)
}
/// Whether an event names a `lucisv.toml` (either spelling) — a change to
/// which moves the scope's excludes and filelist and the lint configuration
/// together. The names are `lucisv_core::config::NAMES`, the CLI's own.
pub fn names_a_config(changes: &[FileEvent]) -> bool {
changes.iter().filter_map(|change| uri_to_path(&change.uri)).any(|path| {
let name = path.file_name().and_then(|n| n.to_str());
name.is_some_and(|n| lucisv_core::config::NAMES.contains(&n))
})
}
/// Whether one path is something the index reads: a source file, or the
+6
View File
@@ -4873,6 +4873,12 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(LENS_SUB).expect("json")
)),
// An edit before the save: a save that moved nothing the index
// records refreshes nothing (localized-reindex, 2026-11-19).
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(&format!("{LENS_SUB}module lens_extra;\nendmodule\n")).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
@@ -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);
}
}
}
+48 -10
View File
@@ -17,6 +17,7 @@
//! would disagree.
use crate::doc::{concat, text, Doc};
use crate::style::Alignment;
/// 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.
@@ -67,7 +68,18 @@ pub struct Align {
/// `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
/// 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 {
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])) {
return None;
}
if !wants_alignment(src, rows, specs) {
if mode == Alignment::Infer && !wants_alignment(src, rows, specs) {
return None;
}
@@ -218,7 +230,7 @@ mod tests {
// Five spaces where flush writes one: four excess, the threshold.
let src = "aa x\nbbbb y\n";
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]);
}
@@ -226,35 +238,35 @@ mod tests {
fn three_excess_spaces_are_not_a_hint() {
let src = "aa x\nbbbb y\n";
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]
fn single_spaces_stay_flush() {
let src = "aa x\nbbbb y\n";
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]
fn one_common_column_stays_aligned() {
let src = "aa x\nbbbb x\n";
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]
fn equal_widths_have_nothing_to_align() {
let src = "aa x\naa y\n";
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]
fn a_group_of_one_is_never_aligned() {
let src = "aa x\n";
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]
@@ -262,8 +274,34 @@ mod tests {
let src = "aa x\nbbbb y\n";
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
// 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, 5).is_none());
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6, Alignment::Infer).is_some());
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]
+169
View File
@@ -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);
}
}
+134
View File
@@ -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(_), .. })
}
+16 -5
View File
@@ -35,10 +35,12 @@ impl<'a> Fmt<'a> {
})
.collect();
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 { " #" }));
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;
}
if let [only] = &inst.instances[..] {
@@ -108,8 +110,10 @@ impl<'a> Fmt<'a> {
let mut broken = !directives.is_empty();
let items: Vec<ListItem> = match conns {
Connections::Named(list) => {
let aligns = self.connection_aligns(list, directives, depth);
broken |= aligns.iter().any(Option::is_some) || holds_verbatim_value(list);
let aligns = self.connection_aligns(list, directives, self.list_depth(depth));
broken |= aligns.iter().any(Option::is_some)
|| holds_verbatim_value(list)
|| self.style_breaks(!list.is_empty());
list.iter()
.zip(&aligns)
.map(|(c, a)| {
@@ -134,7 +138,7 @@ impl<'a> Fmt<'a> {
.collect(),
};
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.
@@ -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 —
/// with the comments written in any of its five gaps back where they stood.
///
+15 -38
View File
@@ -11,9 +11,11 @@
use crate::align::Align;
use crate::doc::*;
use crate::range::Split;
use crate::style::Placement;
use vlog_parser::ast::*;
use vlog_parser::token::Comment;
use super::branch::before_keyword;
use super::instance::drive_strength;
use super::list::ListItem;
use super::verbatim::Slot;
@@ -485,44 +487,18 @@ impl<'a> Fmt<'a> {
group(head)
}
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
let mut docs = vec![text("if "), self.parens(&g.cond)];
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
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);
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 {
/// Append a generate block, its `begin` placed as `begin` says; returns
/// true if it ended with `end` (so `else` can cuddle).
pub(super) fn gen_block(
&self,
docs: &mut Vec<Doc>,
b: &GenBlock,
depth: usize,
begin: Placement,
) -> bool {
if b.is_block {
if b.before_kw.is_empty() {
docs.push(text(" "));
docs.push(before_keyword(begin));
} else {
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);
header.push(text(")"));
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)
}
@@ -592,7 +568,8 @@ impl<'a> Fmt<'a> {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
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.extend(self.trailing(&item.meta));
}
+55 -2
View File
@@ -11,6 +11,7 @@
use crate::align::{self, Align, ColSpec, Row};
use crate::doc::*;
use crate::style::{ListIndent, PortLists};
use vlog_parser::ast::*;
use vlog_parser::token::Comment;
@@ -125,6 +126,53 @@ impl<'a> Fmt<'a> {
dangling: &[Comment],
close: &str,
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 {
if items.is_empty() && dangling.is_empty() {
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;
// Peek at blank_before flags is handled by leading comments already;
// 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(text(close));
group(docs)
@@ -326,7 +378,8 @@ impl<'a> Fmt<'a> {
j += 1;
}
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] {
*slot = Some(plan.clone());
}
+65 -5
View File
@@ -1,17 +1,19 @@
//! Formatting rules: AST → Doc.
//!
//! Style follows Verible's defaults: 2-space indent, 100-column lines,
//! one-element-per-line port/connection lists when a construct does not fit
//! on a single line, cuddled `begin`/`end`.
//! The default style follows Verible's defaults: 2-space indent,
//! 100-column lines, one-element-per-line port/connection lists when a
//! 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
//! 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`,
//! `phrase`, `list`. This file holds what the crate exports (`Config`,
//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and
//! the name helpers every module writes an identifier through.
mod branch;
mod class;
mod comment;
mod cover;
@@ -32,12 +34,16 @@ use crate::doc::{concat, text, Doc};
use crate::fence::{self, Region};
use crate::printer::Printer;
use crate::range::{self, Split};
use crate::style::{Style, LUCISV};
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
use vlog_parser::ast::*;
/// Everything a formatting run is configured with.
#[derive(Debug, Clone)]
pub struct Config {
/// The line limit the printer breaks at.
pub max_width: usize,
/// Spaces per indentation level.
pub indent_width: usize,
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
/// / `` `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
/// nobody else moves a byte.
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 {
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
/// `Err` (see `docs/features/recursion-limit/README.md`).
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)?;
verify_equivalence(source, &output)?;
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
/// `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
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
pub fn format_range(
@@ -126,6 +185,7 @@ pub fn format_range(
config: &Config,
lines: &range::LineRanges,
) -> Result<String, FormatError> {
let config = &crate::auto::concrete(source, config);
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
let selection = range::select(source, &file, lines);
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
+6 -4
View File
@@ -74,10 +74,10 @@ impl<'a> Fmt<'a> {
})
.collect();
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 { " #" }));
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;
}
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) => {
// An aligned list is a broken list: alignment only
// 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);
ports
.iter()
@@ -116,10 +117,11 @@ impl<'a> Fmt<'a> {
_ => Vec::new(),
};
let items = self.list_entries(items, &m.port_directives);
broken |= self.style_breaks(!items.is_empty());
if !on_fresh_line {
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));
}
}
+18 -69
View File
@@ -1,20 +1,22 @@
//! Statements: the `begin … end` block, a statement as the body of a
//! 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
//! a clocking event.
//!
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
//! statement form — and stays whole; the forms with a layout of their own
//! (`if`, `case`) are the functions after it.
//! statement form — and stays whole; `case` has a layout of its own in the
//! functions after it, `if` in `branch.rs`.
use crate::doc::*;
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
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 crate::style::Placement;
/// 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
@@ -86,7 +88,14 @@ impl<'a> Fmt<'a> {
/// The same, skipping the body's first `skip` leading comments because
/// `prefix` already printed them inside its parentheses. See
/// [`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 {
StmtKind::Block {
label_comments,
@@ -97,7 +106,7 @@ impl<'a> Fmt<'a> {
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.push(self.block_doc(BlockDoc {
label_comments,
@@ -115,7 +124,7 @@ impl<'a> Fmt<'a> {
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading_from(&s.meta, skip));
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));
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.
/// 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
@@ -669,7 +617,8 @@ impl<'a> Fmt<'a> {
{
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
+4
View File
@@ -1,15 +1,19 @@
//! Formatter engine: document IR + printer + formatting rules.
pub mod align;
mod auto;
pub mod doc;
pub mod fence;
pub mod format;
pub mod printer;
pub mod range;
mod selection;
pub mod style;
pub mod verify;
pub use auto::{format_auto, resolve_style};
pub use format::{format_range, format_source, Config, FormatError};
pub use range::LineRanges;
pub use selection::format_selection;
pub use style::Style;
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
/// 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`].
pub fn format_selection(
source: &str,
config: &Config,
lines: &LineRanges,
) -> Result<String, FormatError> {
let config = &crate::auto::concrete(source, config);
let tree = Tree::parse(source).map_err(FormatError::Source)?;
let Some(root) = Scope::root(&tree.file) else {
return format_range(source, config, lines);
+236
View File
@@ -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);
}
}
}
}
+686
View File
@@ -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,152 @@
//! Which files' references read which merged-table keys: recorded while a
//! file's references are resolved, and asked when an update moves a key, so
//! that only the files that read it are resolved again
//! (`docs/features/localized-reindex/README.md`).
//!
//! The recording is a thread-local switch rather than a parameter because the
//! resolution walk (`external.rs`, `reexport.rs`, `hierarchy.rs`) is shared
//! with every request-time caller through a dozen functions that take a
//! `&WorkspaceIndex`; threading a recorder through all of them would change
//! every signature for the one caller that wants it. The lookups note what
//! they read with [`note`], which costs one thread-local check when nothing is
//! recording — every request — and the index's own pass turns it on with
//! [`recording`]. `lint_trace` and `scan_trace` use the same shape.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use super::FileId;
/// A merged table a resolution reads, named by what its key is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Table {
/// `units`, by file-scope name.
Unit = 0,
/// `members`, by the unit that exports the member.
Container = 1,
/// `hier_members`, by the unit that declares the member.
Hier = 2,
/// `bases`, by the class whose base it records.
Base = 3,
/// `reexports`, by the exporting package.
Exporter = 4,
}
const TABLES: [Table; 5] =
[Table::Unit, Table::Container, Table::Hier, Table::Base, Table::Exporter];
/// The keys one resolution pass read, table by table — misses included: a
/// lookup that found nothing is exactly the one a new declaration answers.
#[derive(Debug, Default)]
pub(super) struct Reads {
keys: [HashSet<String>; 5],
}
thread_local! {
static RECORDING: RefCell<Option<Reads>> = const { RefCell::new(None) };
}
/// Note that the resolution running on this thread read `table` under `key`.
pub(super) fn note(table: Table, key: &str) {
RECORDING.with(|cell| {
if let Some(reads) = cell.borrow_mut().as_mut() {
let keys = &mut reads.keys[table as usize];
if !keys.contains(key) {
keys.insert(key.to_string());
}
}
});
}
/// Run `body` and say every key it read. Nests: an outer recording is put
/// back afterwards, untouched by the inner one.
pub(super) fn recording<R>(body: impl FnOnce() -> R) -> (R, Reads) {
let outer = RECORDING.with(|cell| cell.replace(Some(Reads::default())));
let out = body();
let reads = RECORDING.with(|cell| cell.replace(outer)).unwrap_or_default();
(out, reads)
}
/// Key → the files whose last resolution read it, each list sorted and
/// without repeats.
///
/// It holds exactly what resolving every file against the tables as they
/// stand would record, which is what makes "the files that read a moved key"
/// a sound answer to "whose postings can have moved": a file that read no
/// moved key read only values that did not change, so its resolution — a pure
/// function of its own facts and those values — did not change either.
#[derive(Debug, Clone, Default)]
pub(super) struct Dependents {
readers: [HashMap<String, Vec<FileId>>; 5],
}
impl Dependents {
/// Forget every reader, for a rebuild from the records.
pub(super) fn clear(&mut self) {
self.readers.iter_mut().for_each(HashMap::clear);
}
/// Record that `file` read everything in `reads`.
pub(super) fn add(&mut self, file: FileId, reads: Reads) {
for (table, keys) in reads.keys.into_iter().enumerate() {
for key in keys {
let files = self.readers[table].entry(key).or_default();
// A whole rebuild adds files in id order, so the common case
// is a push; an update re-adds a few files in the middle.
match files.last() {
Some(last) if *last >= file => {
if let Err(at) = files.binary_search(&file) {
files.insert(at, file);
}
}
_ => files.push(file),
}
}
}
}
/// Take back what [`Dependents::add`] recorded for `file`.
pub(super) fn remove(&mut self, file: FileId, reads: &Reads) {
for (table, keys) in reads.keys.iter().enumerate() {
for key in keys {
let Some(files) = self.readers[table].get_mut(key) else { continue };
if let Ok(at) = files.binary_search(&file) {
files.remove(at);
}
if files.is_empty() {
self.readers[table].remove(key);
}
}
}
}
/// Take back everything recorded for every file `gone` says, by one pass
/// over the whole table.
pub(super) fn remove_all(&mut self, gone: &dyn Fn(FileId) -> bool) {
for readers in &mut self.readers {
readers.retain(|_, files| {
files.retain(|file| !gone(*file));
!files.is_empty()
});
}
}
/// The files that read `table` under `key`.
pub(super) fn readers(&self, table: Table, key: &str) -> &[FileId] {
self.readers[table as usize].get(key).map_or(&[], Vec::as_slice)
}
/// Every reader, one sorted line per key — for the index's fingerprint, so
/// the equivalence tests hold this table to a rebuild's as well.
pub(super) fn render(&self, out: &mut String) {
for table in TABLES {
let mut keys: Vec<(&String, &Vec<FileId>)> =
self.readers[table as usize].iter().collect();
keys.sort();
for (key, files) in keys {
let ids: Vec<u32> = files.iter().map(|file| file.0).collect();
out.push_str(&format!("read {table:?} {key} by {ids:?}\n"));
}
}
}
}
+23 -4
View File
@@ -13,6 +13,7 @@ use vlog_parser::defines::{Define, DefineTable};
use crate::model::{Surface, SymbolKind};
use super::dependents::{note, Table};
use super::external::{fold_path, last_segment, member_chain, own_members};
use super::hierarchy;
use super::record::{FileFacts, ReferenceFact};
@@ -67,6 +68,7 @@ impl WorkspaceIndex {
/// in disambiguation order (by file path, then by position in the file).
/// More than one means the workspace really does declare the name twice.
pub fn units(&self, name: &str) -> &[Def] {
note(Table::Unit, name);
self.units.get(name).map_or(&[], Vec::as_slice)
}
@@ -80,6 +82,7 @@ impl WorkspaceIndex {
/// hierarchical path may name besides is
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Container, unit);
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -95,6 +98,7 @@ impl WorkspaceIndex {
/// — the completion list behind `p::` and behind an instantiation's
/// connection list.
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Container, unit);
self.members
.get(unit)
.into_iter()
@@ -108,6 +112,7 @@ impl WorkspaceIndex {
&self,
unit: &str,
) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Hier, unit);
self.hier_members
.get(unit)
.into_iter()
@@ -116,6 +121,7 @@ impl WorkspaceIndex {
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Hier, unit);
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -187,6 +193,7 @@ impl WorkspaceIndex {
/// edges `reexport`'s two walks follow. Empty for every unit that
/// re-exports nothing, which is all but a handful in any workspace.
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
note(Table::Exporter, unit);
self.reexports.get(unit).map_or(&[], Vec::as_slice)
}
@@ -262,6 +269,7 @@ impl WorkspaceIndex {
/// declare — which is what ends the chase in
/// [`resolve_external`](super::resolve_external).
pub fn base_of(&self, name: &str) -> Option<&str> {
note(Table::Base, name);
self.bases.get(name).map(String::as_str)
}
@@ -315,7 +323,7 @@ impl WorkspaceIndex {
/// Whether at least one use could name `def` or another declaration equally.
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
self.ambiguous_references.contains(&DefinitionKey::of(def))
self.ambiguous_references.contains_key(&DefinitionKey::of(def))
}
/// Every file holding a use spelled `name` that this index had to look
@@ -429,15 +437,26 @@ impl WorkspaceIndex {
/// sorted by name and is not truncated, so a caller with a result limit
/// applies its own.
pub fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| contains_ignore_ascii_case(name, query))
}
/// [`WorkspaceIndex::workspace_symbols`] for exactly these names, in the
/// same order — what a table built from the whole listing re-derives for
/// the names one update touched (`docs/features/localized-reindex`).
pub fn symbols_named(&self, names: &HashSet<&str>) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| names.contains(name))
}
fn symbols_where(&self, keep: impl Fn(&str) -> bool) -> Vec<WorkspaceSymbol<'_>> {
let mut out = Vec::new();
for (name, defs) in &self.units {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def }));
}
}
for (unit, members) in &self.members {
for (name, defs) in members {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol {
name,
container: Some(unit),
@@ -626,7 +645,7 @@ impl IndexBuilder {
facts: self.files,
..WorkspaceIndex::default()
};
index.merge(None);
index.merge();
index
}
}
+16 -3
View File
@@ -24,21 +24,26 @@
//! two member surfaces holds what, and the reads that take a
//! [`crate::Surface`] instead of assuming one.
mod dependents;
mod external;
mod hierarchy;
mod index;
mod path_units;
mod record;
mod reexport;
mod references;
mod replace;
mod update;
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
pub use index::{index_order, IndexBuilder};
pub use record::FileFacts;
use dependents::Dependents;
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
pub(crate) use reexport::Reexport;
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use vlog_parser::span::TextRange;
@@ -326,10 +331,18 @@ pub struct WorkspaceIndex {
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Declarations touched by at least one ambiguous external reference,
/// each with how many such references touch it — counted so one file's
/// references can be taken back without re-resolving the rest.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
ambiguous_references: HashMap<DefinitionKey, u32>,
/// The same, by the file whose references contributed them — so a sweep
/// can take a file's share back without re-resolving it.
ambiguous_by_file: HashMap<FileId, Vec<DefinitionKey>>,
/// Which files' references read which table keys — what lets an update
/// re-resolve only the files that read a key it moved.
dependents: Dependents,
}
/// The headline numbers of a built index.
+53 -1
View File
@@ -11,7 +11,7 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
@@ -271,6 +271,58 @@ impl FileFacts {
pub fn path(&self) -> &Path {
&self.path
}
/// Whether `other` declares what this record declares, as far as
/// [`WorkspaceIndex::workspace_symbols`](super::WorkspaceIndex::workspace_symbols)
/// and the `` `define`` table can see — the same units and
/// connection-surface members by name, kind and owning unit, in the order
/// that listing sorts them, and the same `` `define``s with the same
/// parameters in the same order — wherever in the file they now sit.
///
/// The completion tables are built from exactly those two views, so an
/// edit that moved no such declaration (a body change, a comment, a new
/// local signal) leaves them as they were and need not re-derive them
/// (`docs/features/localized-reindex/README.md`).
pub fn declares_the_same(&self, other: &FileFacts) -> bool {
let define = |define: &Define| (define.name.clone(), define.params.clone());
let defines = |facts: &FileFacts| -> Vec<(String, Option<Vec<String>>)> {
let entries = facts.defines.entries().iter();
entries.filter(|d| d.kind == DefineKind::Define).map(define).collect()
};
self.symbol_view() == other.symbol_view() && defines(self) == defines(other)
}
/// Every name this file puts in the workspace-symbol listing — its units
/// and its connection-surface members — and every macro it `` `define``s:
/// what a table built from those listings re-derives when the file moves.
pub fn declared_names(&self) -> (HashSet<&str>, HashSet<&str>) {
let units = self.units.iter().map(|decl| decl.name.as_str());
let members = self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection);
let symbols = units.chain(members.map(|(_, decl)| decl.name.as_str())).collect();
let entries = self.defines.entries().iter();
let macros =
entries.filter(|d| d.kind == DefineKind::Define).map(|d| d.name.as_str()).collect();
(symbols, macros)
}
/// This file's workspace symbols, spans aside: `(name, container, kind)`
/// in `workspace_symbols`' order, which within one file is by name, then
/// container, then position.
fn symbol_view(&self) -> Vec<(&str, Option<&str>, SymbolKind)> {
let units = self
.units
.iter()
.map(|decl| (decl.name.as_str(), None, decl.name_span.start, decl.kind));
let members =
self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection).map(
|(unit, decl)| {
(decl.name.as_str(), Some(unit.as_str()), decl.name_span.start, decl.kind)
},
);
let mut view: Vec<_> = units.chain(members).collect();
view.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));
view.into_iter().map(|(name, container, _, kind)| (name, container, kind)).collect()
}
}
/// One file's two identifier censuses, both read off the same token stream:
@@ -0,0 +1,176 @@
//! The declaration → use postings, built from every file's reference facts or
//! re-done for a few files: what an update calls once it knows which files
//! read a key it moved (`docs/features/localized-reindex/README.md`).
use std::collections::HashSet;
use super::dependents::{recording, Reads};
use super::external::{resolve_fact, ExternalTarget};
use super::record::ReferenceFact;
use super::{DefinitionKey, FileId, ReferenceSite, WorkspaceIndex};
/// What one reference puts into the postings.
enum Posting {
/// One use of one declaration.
Site(DefinitionKey, ReferenceSite),
/// A use that could name any of these declarations equally.
Ambiguous(Vec<DefinitionKey>),
}
impl WorkspaceIndex {
/// Rebuild every posting, the ambiguity counts and the readers table from
/// every file's facts.
pub(super) fn merge_references(&mut self) {
self.reference_sites.clear();
self.ambiguous_references.clear();
self.ambiguous_by_file.clear();
self.dependents.clear();
let every: Vec<FileId> = (0..self.facts.len()).map(|id| FileId(id as u32)).collect();
self.resolve_files(&every);
}
/// Put `files`' postings in, resolved against the tables as they stand.
///
/// `files` is in id order, and each file's postings go in after every
/// posting of a lower-numbered file and before every higher one — the
/// order [`WorkspaceIndex::merge_references`] produces by visiting the
/// files in that order, so a few files re-done in place give the lists a
/// whole rebuild gives.
pub(super) fn resolve_files(&mut self, files: &[FileId]) {
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, site) => {
let sites = self.reference_sites.entry(key).or_default();
let at = sites.partition_point(|held| held.file <= file);
sites.insert(at, site);
}
Posting::Ambiguous(keys) => {
for key in keys {
*self.ambiguous_references.entry(key).or_default() += 1;
self.ambiguous_by_file.entry(file).or_default().push(key);
}
}
}
}
self.dependents.add(file, reads);
}
}
/// Take `files`' postings out again.
///
/// Re-resolving them against the tables as they stand finds exactly what
/// [`WorkspaceIndex::resolve_files`] put in, because those are the tables
/// it was put in against — every update keeps the postings equal to a
/// resolution of every file over the current tables, and resolution is a
/// pure function of the two. So nothing per file has to be remembered to
/// undo it.
pub(super) fn unresolve_files(&mut self, files: &[FileId]) {
let leaving: HashSet<FileId> = files.iter().copied().collect();
let mut touched: HashSet<DefinitionKey> = HashSet::new();
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, _) => {
touched.insert(key);
}
Posting::Ambiguous(keys) => {
keys.iter().for_each(|key| self.forget_ambiguity(key))
}
}
}
self.dependents.remove(file, &reads);
self.ambiguous_by_file.remove(&file);
}
for key in touched {
let Some(sites) = self.reference_sites.get_mut(&key) else { continue };
sites.retain(|site| !leaving.contains(&site.file));
if sites.is_empty() {
self.reference_sites.remove(&key);
}
}
}
/// [`WorkspaceIndex::unresolve_files`] by one pass over the postings
/// rather than by re-resolving `files`: every site a file put in is
/// dropped wherever it is, its ambiguity taken back from what it is
/// recorded to have contributed, and its id struck from every reader
/// list. Linear in the postings, not in `files` — the cheaper way out when
/// `files` hold a large share of every reference (a package most of the
/// tree imports), where re-resolving them would be most of a whole merge.
pub(super) fn unresolve_by_sweep(&mut self, files: &[FileId]) {
let mut leaving = vec![false; self.facts.len()];
for file in files {
if let Some(slot) = leaving.get_mut(file.0 as usize) {
*slot = true;
}
}
let gone = |file: FileId| leaving.get(file.0 as usize).copied().unwrap_or(false);
self.reference_sites.retain(|_, sites| {
sites.retain(|site| !gone(site.file));
!sites.is_empty()
});
for file in files {
for key in self.ambiguous_by_file.remove(file).unwrap_or_default() {
self.forget_ambiguity(&key);
}
}
self.dependents.remove_all(&gone);
}
/// How many references `files` hold, against how many every file holds —
/// the two numbers that choose between the two ways out.
pub(super) fn reference_share(&self, files: &[FileId]) -> (usize, usize) {
let count =
|file: &FileId| self.facts.get(file.0 as usize).map_or(0, |f| f.references.len());
let total = self.facts.iter().map(|facts| facts.references.len()).sum();
(files.iter().map(count).sum(), total)
}
fn forget_ambiguity(&mut self, key: &DefinitionKey) {
let Some(count) = self.ambiguous_references.get_mut(key) else { return };
*count -= 1;
if *count == 0 {
self.ambiguous_references.remove(key);
}
}
/// One file's postings, and every table key resolving them read.
fn postings_of(&self, file: FileId) -> (Vec<Posting>, Reads) {
let Some(facts) = self.facts.get(file.0 as usize) else {
return (Vec::new(), Reads::default());
};
recording(|| {
let mut out = Vec::new();
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
out.push(Posting::Site(key, site));
}
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
out.push(Posting::Site(DefinitionKey::of(&def), site));
}
ExternalTarget::Ambiguous(defs) => {
out.push(Posting::Ambiguous(
defs.iter().map(DefinitionKey::of).collect(),
));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
out
})
}
}
@@ -0,0 +1,345 @@
//! Replacing one held file's record with a different one, doing only the
//! work the change can reach: the tables re-merged for the keys either record
//! names, from the files that contribute to them, and the postings re-done for
//! the files whose resolution read a key whose value really moved
//! (`docs/features/localized-reindex/README.md`).
use std::collections::{BTreeMap, BTreeSet, HashSet};
use crate::model::SymbolKind;
use super::dependents::Table;
use super::record::FileFacts;
use super::reexport::Reexport;
use super::update::Affected;
use super::{Def, FileId, WorkspaceIndex};
/// One unit's members: member name → every declaration of it.
type MemberTable = BTreeMap<String, Vec<Def>>;
/// The entries an update names in the four tables resolution reads, held
/// aside: the old tables' entries, swapped back in for as long as it takes to
/// take the readers' old postings out.
#[derive(Default)]
struct Entries {
units: Vec<(String, Option<Vec<Def>>)>,
members: Vec<(String, Option<MemberTable>)>,
hier_members: Vec<(String, Option<MemberTable>)>,
reexports: Vec<(String, Option<Vec<Reexport>>)>,
/// The whole class → base table, when either record has a class with a
/// base — the only way it can move, and it is rebuilt whole when it does.
bases: Option<BTreeMap<String, String>>,
}
/// The keys whose value, as resolution reads it, an update changed.
#[derive(Default)]
struct Moved {
keys: Vec<(Table, String)>,
}
/// One declaration as resolution reads it — see [`seen`].
type Seen<'a> = (FileId, u32, u32, SymbolKind, Option<&'a str>);
/// What resolution reads of one declaration: which declaration it is (the
/// posting key is its file and name span), what kind, and the type a member
/// hop continues through. A declaration whose body grew moved its
/// `decl_span` and its lines, and no posting can tell.
fn seen(defs: &[Def]) -> Vec<Seen<'_>> {
defs.iter()
.map(|d| (d.file, d.name_span.start, d.name_span.end, d.kind, d.type_name.as_deref()))
.collect()
}
fn seen_members(members: Option<&MemberTable>) -> Vec<(&str, Vec<Seen<'_>>)> {
members.into_iter().flatten().map(|(name, defs)| (name.as_str(), seen(defs))).collect()
}
impl WorkspaceIndex {
/// Replace the record at `at` with a different one.
///
/// * The **tables** are re-merged for the keys either record names
/// ([`Affected`]), from the records of the files that contribute to those
/// keys — the same loop a whole merge runs, over fewer files.
/// * The **postings** are re-done for this file and for every file whose
/// last resolution read a key whose value moved
/// ([`Dependents`](super::dependents::Dependents)): taken out against the
/// old tables, put back against the new ones.
///
/// A file that read no moved key read only values this replacement did not
/// change, so its postings are already what a rebuild would give. "Moved"
/// is judged as resolution sees a value ([`seen`]): an edit inside a
/// module's body moves the module's extent and the declarations after the
/// edit, but not the module's name, so the files that only instantiate it
/// are left alone.
///
/// Returns the files whose postings were re-done, for the tests that pin
/// the narrowing itself.
pub(super) fn replace_facts(&mut self, at: usize, facts: FileFacts) -> Vec<FileId> {
let file = FileId(at as u32);
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
let contributors = self.contributors(&affected, at);
let mut old = self.take_entries(&affected);
let mut old_facts = std::mem::replace(&mut self.facts[at], facts);
self.merge_tables(Some(&affected), contributors.as_deref());
if old.bases.is_some() {
self.merge_bases();
}
let readers = self.readers_of(&self.moved(&old, &affected), file);
// The readers' old postings out: re-resolved against the tables and
// the record they were made from, which costs what putting them back
// costs — or, when the readers hold more than an eighth of every
// reference, swept out in one pass over the postings, which is then
// the cheaper of the two (QA F5: every importer of a widely imported
// package re-resolved twice was slower than the old whole merge).
let (share, total) = self.reference_share(&readers);
if sweeps(share, total) {
self.unresolve_by_sweep(&readers);
} else {
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
self.unresolve_files(&readers);
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
}
self.resolve_files(&readers);
readers
}
/// Take the entries `affected` names out of the tables resolution reads.
fn take_entries(&mut self, affected: &Affected) -> Entries {
Entries {
units: take(&mut self.units, &affected.units),
members: take(&mut self.members, &affected.containers),
hier_members: take(&mut self.hier_members, &affected.containers),
reexports: take(&mut self.reexports, &affected.exporters),
bases: (!affected.classes.is_empty()).then(|| std::mem::take(&mut self.bases)),
}
}
/// Exchange the held entries with the tables' — twice is no change.
fn swap_entries(&mut self, held: &mut Entries) {
swap_in(&mut self.units, &mut held.units);
swap_in(&mut self.members, &mut held.members);
swap_in(&mut self.hier_members, &mut held.hier_members);
swap_in(&mut self.reexports, &mut held.reexports);
if let Some(bases) = held.bases.as_mut() {
std::mem::swap(&mut self.bases, bases);
}
}
/// Every key whose value, as resolution reads it, differs between the
/// held entries and the tables now.
fn moved(&self, old: &Entries, affected: &Affected) -> Moved {
let mut out = Moved::default();
for (name, defs) in &old.units {
let now = self.units.get(name).map_or(&[][..], Vec::as_slice);
if seen(defs.as_deref().unwrap_or_default()) != seen(now) {
out.keys.push((Table::Unit, name.clone()));
}
}
for (table, held, now) in [
(Table::Container, &old.members, &self.members),
(Table::Hier, &old.hier_members, &self.hier_members),
] {
for (unit, members) in held {
if seen_members(members.as_ref()) != seen_members(now.get(unit)) {
out.keys.push((table, unit.clone()));
}
}
}
for (exporter, entries) in &old.reexports {
if entries.as_ref() != self.reexports.get(exporter) {
out.keys.push((Table::Exporter, exporter.clone()));
}
}
if let Some(bases) = &old.bases {
for class in &affected.classes {
if bases.get(class) != self.bases.get(class) {
out.keys.push((Table::Base, class.clone()));
}
}
}
out
}
/// This file and every file whose postings read a moved key, in id order.
fn readers_of(&self, moved: &Moved, file: FileId) -> Vec<FileId> {
let mut out: BTreeSet<FileId> = BTreeSet::from([file]);
for (table, key) in &moved.keys {
out.extend(self.dependents.readers(*table, key));
}
out.into_iter().collect()
}
/// Every file holding a record under a key in `affected`, in id order —
/// read off the merged tables, whose entries say which file each came
/// from. `None` means every file: a re-export entry does not carry its
/// file, so a record that names an exporter takes the whole loop.
fn contributors(&self, affected: &Affected, at: usize) -> Option<Vec<usize>> {
if !affected.exporters.is_empty() {
return None;
}
let mut out: BTreeSet<usize> = BTreeSet::from([at]);
let id = |file: FileId| file.0 as usize;
for name in &affected.units {
out.extend(self.units.get(name).into_iter().flatten().map(|def| id(def.file)));
}
for unit in &affected.containers {
for table in [&self.members, &self.hier_members] {
let defs = table.get(unit).into_iter().flat_map(|m| m.values()).flatten();
out.extend(defs.map(|def| id(def.file)));
}
}
for module in &affected.modules {
let edges = self.instantiations.get(module).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for base in &affected.bases {
let edges = self.subclasses.get(base).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for name in &affected.macros {
let defines = self.macro_definitions.get(name).into_iter().flatten();
out.extend(defines.map(|(file, _)| id(*file)));
}
Some(out.into_iter().collect())
}
}
/// Below this many references in the whole index a sweep never pays: the
/// re-resolution of a few small files is already sub-millisecond.
const SWEEP_FLOOR: usize = 20_000;
/// Whether the readers' old postings go out by a sweep ([`sweeps`]'s rule:
/// they hold more than an eighth of every reference in an index big enough
/// for that to cost something) or by re-resolution.
fn sweeps(share: usize, total: usize) -> bool {
#[cfg(test)]
if let Some(forced) = tests::FORCE_SWEEP.with(std::cell::Cell::get) {
return forced;
}
total >= SWEEP_FLOOR && share * 8 > total
}
/// Remove the entries under `keys`, keeping each with its key — an absent
/// one as `None`, so swapping it back in removes what is there.
fn take<V>(table: &mut BTreeMap<String, V>, keys: &HashSet<String>) -> Vec<(String, Option<V>)> {
keys.iter().map(|key| (key.clone(), table.remove(key))).collect()
}
/// Exchange each held entry with the table's entry under the same key, an
/// absent entry on either side included.
fn swap_in<V>(table: &mut BTreeMap<String, V>, held: &mut [(String, Option<V>)]) {
for (key, value) in held {
let current = table.remove(key.as_str());
if let Some(value) = value.take() {
table.insert(key.clone(), value);
}
*value = current;
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::path::PathBuf;
use super::*;
thread_local! {
/// Which way out a test forces, whatever the sizes say.
pub(super) static FORCE_SWEEP: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Every edit of a small chained design, each checked against a whole
/// build, with the readers' postings taken out each way in turn — the
/// sweep is otherwise taken only on trees of 20 000 references and up.
#[test]
fn both_ways_out_give_the_index_a_whole_build_gives() {
let base = [
("a.sv", "package a_pkg;\n localparam int W = 8;\nendpackage\nclass base_c;\n int m;\nendclass\n"),
("b.sv", "module leaf (input logic clk);\n logic s;\nendmodule\nclass mid_c extends base_c;\nendclass\n"),
("c.sv", "module top;\n import a_pkg::*;\n logic c;\n leaf u (.clk(c));\n initial $display(u.s, W);\nendmodule\nclass leaf_c extends mid_c;\n function void f(); m = 1; endfunction\nendclass\n"),
("d.sv", "module dup (input logic a);\nendmodule\nmodule user;\n dup i (.a(1'b0));\nendmodule\n"),
("e.sv", "module user2;\n dup j ();\nendmodule\n"),
];
let edits = [
("a.sv", "// top\npackage a_pkg;\n localparam int W = 8;\n localparam int V = 1;\nendpackage\nclass base_c;\n int n, m;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nclass mid_c extends other_c;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nmodule dup;\nendmodule\n"),
("e.sv", "// a line\nmodule user2;\n dup j ();\nendmodule\n"),
("c.sv", "module top;\n logic c;\nendmodule\n"),
];
for forced in [true, false] {
FORCE_SWEEP.with(|cell| cell.set(Some(forced)));
let mut files: Vec<(String, String)> =
base.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for round in 0..2 {
for (path, text) in edits.iter().chain(base.iter()) {
let slot = files.iter_mut().find(|(p, _)| p == path).expect("a held file");
slot.1 = text.to_string();
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"sweep={forced}, round {round}: `{path}`"
);
}
}
FORCE_SWEEP.with(|cell| cell.set(None));
}
}
fn build(files: &[(String, String)]) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
const LEAF: &str = "module leaf (input logic clk);\n logic s;\nendmodule\n";
const TOP: &str = "module top;\n logic c;\n leaf u (.clk(c));\nendmodule\n";
const TB: &str = "module tb;\n top t ();\n initial $display(t.u.s);\nendmodule\n";
/// The files an update of `leaf.sv` to `text` re-resolves, by path.
fn re_resolved(text: &str) -> Vec<String> {
let mut index = WorkspaceIndex::build([
(PathBuf::from("leaf.sv"), LEAF),
(PathBuf::from("tb.sv"), TB),
(PathBuf::from("top.sv"), TOP),
]);
let facts = FileFacts::of(PathBuf::from("leaf.sv"), text);
let files = index.replace_facts(0, facts);
files.iter().filter_map(|&file| index.path(file)).map(|p| p.display().to_string()).collect()
}
#[test]
fn a_body_edit_re_resolves_only_the_file_itself() {
// The module's name, its port and its signal keep their spans; only
// its extent and its body moved, and no posting can see either. A new
// declaration would be a new member, and the hierarchical reader
// re-resolved for it — a member table is judged whole.
let grown = "module leaf (input logic clk);\n logic s;\n assign s = clk;\nendmodule\n";
assert_eq!(re_resolved(grown), ["leaf.sv"]);
}
#[test]
fn a_port_edit_re_resolves_the_file_that_connects_to_it() {
// Same length, so the signal after it keeps its span — but the
// hierarchical path asks the connection surface before the
// hierarchical one, so it read the port table too.
let renamed = "module leaf (input logic clq);\n logic s;\nendmodule\n";
assert_eq!(re_resolved(renamed), ["leaf.sv", "tb.sv", "top.sv"]);
}
#[test]
fn a_moved_internal_signal_re_resolves_the_file_whose_path_reaches_it() {
let moved = "module leaf (input logic clk);\n logic pad;\n logic s;\nendmodule\n";
assert_eq!(re_resolved(moved), ["leaf.sv", "tb.sv"]);
}
#[test]
fn an_edit_above_everything_re_resolves_every_reader() {
let shifted = format!("// above\n{LEAF}");
assert_eq!(re_resolved(&shifted), ["leaf.sv", "tb.sv", "top.sv"]);
}
}
+135 -138
View File
@@ -4,18 +4,15 @@
//! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`]
//! that proves it.
use std::collections::{BTreeMap, HashSet};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use crate::model::Surface;
use super::external::{resolve_fact, ExternalTarget};
use super::record::{facts_of, FileFacts, ReferenceFact};
use super::{
DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex,
};
use super::record::{facts_of, FileFacts};
use super::{DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, WorkspaceIndex};
impl WorkspaceIndex {
/// Replace one file's contribution to the index — or add the file, when
@@ -38,8 +35,13 @@ impl WorkspaceIndex {
/// remove; nothing in this workspace holds one across an update (the
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
self.update_facts(facts_of(path, src));
///
/// Reports whether the index moved: `false` exactly when the file's new
/// record equals the one held, which is the watcher's echo of a save and a
/// save that changed nothing — the cheapest answer there is, and a sound
/// one, since an index is a function of its records.
pub fn update_file(&mut self, path: PathBuf, src: &str) -> bool {
self.update_facts(facts_of(path, src))
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
@@ -51,26 +53,28 @@ impl WorkspaceIndex {
/// [`IndexBuilder::add_file`](super::IndexBuilder::add_file) with
/// the parse already done: same contract, same result. Whether the record
/// really describes the file is the caller's business.
pub fn update_facts(&mut self, facts: FileFacts) {
///
/// Reports whether the index moved, as [`WorkspaceIndex::update_file`]
/// does.
pub fn update_facts(&mut self, facts: FileFacts) -> bool {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
Ok(at) if self.facts[at] == facts => return false,
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
// and the file list has not, so ids are untouched.
Ok(at) => {
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
self.facts[at] = facts;
self.merge(Some(&affected));
self.replace_facts(at, facts);
}
// A file the index did not hold: every id from here on shifts, so
// every table is rebuilt from the records. No parse, no read.
Err(at) => {
self.files.insert(at, path);
self.facts.insert(at, facts);
self.merge(None);
self.merge();
}
}
true
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
@@ -117,7 +121,7 @@ impl WorkspaceIndex {
}
}
}
self.merge(None);
self.merge();
}
/// Drop one file from the index, reporting whether it was there.
@@ -130,7 +134,7 @@ impl WorkspaceIndex {
};
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
self.merge();
true
}
@@ -185,11 +189,11 @@ impl WorkspaceIndex {
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
let mut ambiguous: Vec<(&DefinitionKey, &u32)> = self.ambiguous_references.iter().collect();
ambiguous.sort();
for definition in ambiguous {
for (definition, count) in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
"ambiguous-ref {}:{}..{} x{count}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
@@ -238,17 +242,36 @@ impl WorkspaceIndex {
));
}
}
// Not an answer any caller reads, but the table that decides which
// files the *next* update re-resolves: one that drifted from a
// rebuild's would be a stale posting waiting to happen.
self.dependents.render(&mut out);
out
}
/// Rebuild the merged tables from the per-file records.
/// Rebuild every merged table, the postings and the readers table from
/// the per-file records.
///
/// `affected` names the keys that may have moved; `None` means all of
/// them. Either way this is one loop over the path-sorted records pushing
/// in the order it meets them, which is the *only* place any table's order
/// is decided — so a restricted merge and a whole one agree by
/// construction, and both agree with [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self, affected: Option<&Affected>) {
/// The tables are one loop over the path-sorted records pushing in the
/// order it meets them ([`WorkspaceIndex::merge_tables`]), which is the
/// *only* place any table's order is decided — so a restricted merge over
/// a few files and a whole one agree by construction, and both agree with
/// [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self) {
self.merge_tables(None, None);
self.merge_bases();
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// The table half of [`WorkspaceIndex::merge`]: clear the keys `affected`
/// names (all of them for `None`) and push back every record under them,
/// visiting `files` — the files that hold such records, in id order — or
/// every file for `None`. Visiting fewer files is the same loop, because a
/// file with no record under a cleared key pushes nothing.
pub(super) fn merge_tables(&mut self, affected: Option<&Affected>, files: Option<&[usize]>) {
match affected {
None => {
self.units.clear();
@@ -281,117 +304,87 @@ impl WorkspaceIndex {
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
match files {
Some(files) => files.iter().for_each(|&id| self.push_records(id, affected)),
None => (0..self.facts.len()).for_each(|id| self.push_records(id, affected)),
}
// The reverse inheritance edge is rebuilt whole every time, whatever
// `affected` says: it is one entry per `extends` written anywhere (a
// few thousand on opentitan), and rebuilding it is both cheaper to
// reason about and the reason a restricted merge cannot leave it
// half-updated. First in file order wins, which is `units`' rule.
}
/// Push one file's records under the keys `affected` names (every key for
/// `None`), in the order the record holds them.
fn push_records(&mut self, id: usize, affected: Option<&Affected>) {
let file = FileId(id as u32);
let Some(facts) = self.facts.get(id) else { return };
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
}
/// The reverse inheritance edge, rebuilt whole: one entry per `extends`
/// written anywhere (a few thousand on opentitan), first in file order
/// winning, which is `units`' rule.
pub(super) fn merge_bases(&mut self) {
self.bases.clear();
for facts in &self.facts {
for (base, subclass) in &facts.subclasses {
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone());
}
}
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// Rebuild declaration-to-occurrence postings from compact per-file facts.
fn merge_references(&mut self) {
let mut sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>> = BTreeMap::new();
let mut ambiguous: HashSet<DefinitionKey> = HashSet::new();
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
ExternalTarget::Ambiguous(defs) => {
ambiguous.extend(defs.iter().map(DefinitionKey::of));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
}
self.reference_sites = sites;
self.ambiguous_references = ambiguous;
}
}
@@ -399,33 +392,37 @@ impl WorkspaceIndex {
/// file can leave every other key alone.
#[derive(Debug, Default)]
pub(super) struct Affected {
units: HashSet<String>,
pub(super) units: HashSet<String>,
/// Keys of the `members` table — the *unit* a member is exported by, not
/// the member itself. A whole unit's sub-table is the smallest thing worth
/// rebuilding: one file adding a member to a package cannot move any other
/// package.
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
pub(super) containers: HashSet<String>,
pub(super) modules: HashSet<String>,
pub(super) bases: HashSet<String>,
/// Keys of the `reexports` table — the package that writes the `export`,
/// never the package it takes the name from: a file changing what `a_pkg`
/// re-exports moves `a_pkg`'s edges and no one else's.
exporters: HashSet<String>,
macros: HashSet<String>,
pub(super) exporters: HashSet<String>,
pub(super) macros: HashSet<String>,
/// Keys of the `bases` table — the *extending* class, which is what a
/// member lookup up the `extends` chain asks it by.
pub(super) classes: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
pub(super) fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
pub(super) fn add(&mut self, facts: &FileFacts) {
self.units.extend(facts.units.iter().map(|decl| decl.name.clone()));
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.classes.extend(facts.subclasses.iter().map(|(_, class)| class.name.clone()));
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
@@ -0,0 +1,350 @@
//! The localized update's whole claim, attacked: after any sequence of
//! one-file updates, the index is the index a whole build over the same file
//! contents gives — postings, ambiguity, edges and the readers table that
//! decides which files the *next* update re-resolves included
//! (`docs/features/localized-reindex/README.md`).
//!
//! Each case is a design whose references reach across files through one of
//! the hops resolution takes — a port connection, a package import, a
//! re-export, an `extends` chain, a typedef alias, a hierarchical path through
//! instances, a qualified miss — and a sequence of edits to the file at the
//! far end of the hop, chosen so that a narrowing which forgot that hop would
//! leave a stale posting the fingerprint shows. The randomized sweep at the
//! bottom drives the same designs through seeded mutations.
use std::collections::BTreeMap;
use std::path::PathBuf;
use vlog_semantic::WorkspaceIndex;
fn build(files: &BTreeMap<String, String>) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
/// Apply `steps` one update at a time, checking the index against a whole
/// build after every one of them.
fn holds(initial: &[(&str, &str)], steps: &[(&str, &str)]) {
let mut files: BTreeMap<String, String> =
initial.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for (at, (path, text)) in steps.iter().enumerate() {
files.insert(path.to_string(), text.to_string());
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"step {at}: updating `{path}` must give the index a whole build would have"
);
}
}
const PORTS: [(&str, &str); 2] = [
("leaf.sv", "module leaf (input logic clk, output logic q);\nendmodule\n"),
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n"),
];
#[test]
fn a_port_connection_follows_every_edit_of_the_instantiated_module() {
holds(
&PORTS,
&[
// A body edit: the ports keep their spans, the module's extent grows.
("leaf.sv", "module leaf (input logic clk, output logic q);\n logic s;\nendmodule\n"),
// A comment above everything: every span moves.
("leaf.sv", "// moved\nmodule leaf (input logic clk, output logic q);\nendmodule\n"),
// A port renamed, then removed, then the module renamed away.
("leaf.sv", "module leaf (input logic clock, output logic q);\nendmodule\n"),
("leaf.sv", "module leaf (output logic q);\nendmodule\n"),
("leaf.sv", "module other (input logic clk, output logic q);\nendmodule\n"),
// And back, so a key that went missing comes home.
(PORTS[0].0, PORTS[0].1),
// The instantiating side moves too.
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.q(d), .clk(c));\nendmodule\n"),
],
);
}
const PACKAGES: [(&str, &str); 3] = [
("a_pkg.sv", "package a_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"),
(
"user.sv",
"module user;\n import b_pkg::*;\n word_t w;\n localparam int X = W + a_pkg::W;\nendmodule\n",
),
];
#[test]
fn an_import_and_a_reexport_follow_every_edit_of_the_package_at_the_end() {
holds(
&PACKAGES,
&[
("a_pkg.sv", "package a_pkg;\n // shifted\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("a_pkg.sv", "package a_pkg;\n localparam int W2 = 8;\n typedef logic [7:0] word_t;\nendpackage\n"),
// The middle package stops re-exporting, then starts again.
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\nendpackage\n"),
(PACKAGES[1].0, PACKAGES[1].1),
// The package at the end renamed: every qualified use becomes a miss.
("a_pkg.sv", "package c_pkg;\n localparam int W = 8;\nendpackage\n"),
(PACKAGES[0].0, PACKAGES[0].1),
],
);
}
const CLASSES: [(&str, &str); 3] = [
("base.sv", "class base_c;\n int m;\n function void f(); endfunction\nendclass\n"),
("mid.sv", "class mid_c extends base_c;\nendclass\n"),
("leaf_c.sv", "class leaf_c extends mid_c;\n function void g();\n m = 1;\n f();\n this.m = 2;\n endfunction\nendclass\n"),
];
#[test]
fn an_inherited_member_follows_every_edit_along_the_extends_chain() {
holds(
&CLASSES,
&[
// The member two hops up moves, is renamed, comes back.
(
"base.sv",
"class base_c;\n int pad;\n int m;\n function void f(); endfunction\nendclass\n",
),
("base.sv", "class base_c;\n int n;\n function void f(); endfunction\nendclass\n"),
(CLASSES[0].0, CLASSES[0].1),
// The middle of the chain changes what it extends.
("mid.sv", "class mid_c extends other_c;\nendclass\n"),
("mid.sv", "class mid_c;\nendclass\n"),
(CLASSES[1].0, CLASSES[1].1),
// The middle class declares the member itself, shadowing the base.
("mid.sv", "class mid_c extends base_c;\n int m;\nendclass\n"),
],
);
}
const ALIASES: [(&str, &str); 3] = [
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { hdr_t hdr; logic [31:0] data; } pkt_t;\nendpackage\n"),
("use.sv", "module use_it;\n import pkt_pkg::*;\n pkt_t p;\n assign p.hdr.addr = 8'h0;\nendmodule\n"),
];
#[test]
fn a_member_chain_through_struct_types_follows_every_edit_of_the_innermost_type() {
holds(
&ALIASES,
&[
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic v; logic [7:0] addr; } hdr_t;\nendpackage\n"),
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] address; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { logic [31:0] data; hdr_t hdr; } pkt_t;\nendpackage\n"),
(ALIASES[0].0, ALIASES[0].1),
],
);
}
#[test]
fn a_member_whose_type_alone_changes_moves_the_hop_through_it() {
// `hdr_t` and `oth_t` are the same length, so the member `hdr` keeps its
// span and only its declared type — the hop `p.hdr.addr` takes — moves.
let hdr = "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; } hdr_t;\n \
typedef struct packed { logic v; logic [7:0] addr; } oth_t;\nendpackage\n";
holds(
&[("hdr.sv", hdr), ALIASES[1], ALIASES[2]],
&[
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "oth_t hdr")),
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "nop_t hdr")),
ALIASES[1],
],
);
}
#[test]
fn a_unit_whose_kind_alone_changes_moves_a_path_rooted_at_it() {
// `module h_x` and `package h_x` put the name, and the member after it,
// at the same offsets: only the unit's kind moves, and a top-rooted
// hierarchical path roots only at a module.
holds(
&[
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
("h_xtb.sv", "module h_xtb;\n initial $display(h_x.s);\nendmodule\n"),
],
&[
("h_x.sv", "package h_x;\n logic s;\nendpackage\n"),
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
],
);
}
const HIERARCHY: [(&str, &str); 4] = [
("h_leaf.sv", "module h_leaf;\n logic sig;\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_leaf u_leaf ();\nendmodule\n"),
("h_top.sv", "module h_top;\n h_mid u_mid ();\nendmodule\n"),
(
"h_tb.sv",
"module h_tb;\n h_top dut ();\n initial $display(dut.u_mid.u_leaf.sig);\nendmodule\n",
),
];
#[test]
fn a_hierarchical_path_follows_every_edit_of_the_module_at_its_tail() {
holds(
&HIERARCHY,
&[
// The signal at the end moves, goes, comes back as another kind.
("h_leaf.sv", "module h_leaf;\n logic pad;\n logic sig;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n logic other;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n wire sig;\nendmodule\n"),
// An instance in the middle renamed, then its module swapped.
("h_mid.sv", "module h_mid;\n h_leaf u_leaf2 ();\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_top u_leaf ();\nendmodule\n"),
(HIERARCHY[1].0, HIERARCHY[1].1),
// The tail module turned into a port, which the connection
// surface answers first.
("h_leaf.sv", "module h_leaf (input logic sig);\nendmodule\n"),
],
);
}
const MISSES: [(&str, &str); 2] = [
("asker.sv", "module asker;\n localparam int K = later_pkg::K;\n later_m u ();\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
];
#[test]
fn a_use_that_found_nothing_is_answered_the_moment_another_file_declares_it() {
holds(
&MISSES,
&[
// The other file starts declaring both names, then twice over,
// then stops — a miss, a hit, an ambiguity, a miss.
("other.sv", "package later_pkg;\n localparam int K = 1;\nendpackage\nmodule later_m;\nendmodule\n"),
("other.sv", "package later_pkg;\n localparam int K = 1;\n localparam int K = 2;\nendpackage\nmodule later_m;\nendmodule\nmodule later_m;\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
],
);
}
#[test]
fn a_name_two_files_declare_stays_ambiguous_exactly_as_long_as_it_is() {
holds(
&[
("d1.sv", "module dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic a);\nendmodule\n"),
("u.sv", "module u;\n logic x;\n dup i (.a(x));\nendmodule\n"),
],
&[
("d1.sv", "module dup_one (input logic a);\nendmodule\n"),
("d1.sv", "// back\nmodule dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic b);\nendmodule\n"),
],
);
}
#[test]
fn a_define_a_broken_file_and_an_unchanged_save_all_hold() {
holds(
&[
("defs.svh", "`define W 8\n`define F(a) (a)\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
&[
("defs.svh", "`define W 16\n`define F(a, b) (a+b)\n"),
("defs.svh", "`undef W\n`define W 16\n"),
("m.sv", "module m;\n logic [`W-1:0] x\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
);
}
#[test]
fn an_unchanged_record_reports_that_nothing_moved() {
let files: BTreeMap<String, String> =
PORTS.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
let before = index.fingerprint();
assert!(!index.update_file(PathBuf::from(PORTS[0].0), PORTS[0].1), "same text, same record");
assert_eq!(index.fingerprint(), before);
// A comment after the last token moves no span the record holds.
let trailing = format!("{}// trailing\n", PORTS[0].1);
assert!(!index.update_file(PathBuf::from(PORTS[0].0), &trailing), "{trailing:?}");
let renamed = PORTS[0].1.replace("clk", "clock");
assert!(index.update_file(PathBuf::from(PORTS[0].0), &renamed), "a port renamed moves it");
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit of `text`: a line inserted, deleted, duplicated or swapped
/// with its neighbour, or one identifier-ish word renamed to another from
/// the design — the kinds of edit that move spans, names and whole
/// declarations.
fn mutate(text: &str, words: &[&str], rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(5) {
0 => lines.insert(at, " // a comment".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
_ => {
let from = words[rng.below(words.len())];
let to = words[rng.below(words.len())];
if let Some(line) = lines.iter_mut().find(|line| line.contains(from)) {
*line = line.replacen(from, to, 1);
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
#[test]
fn a_seeded_sweep_of_mutations_over_every_design_holds() {
let designs: [&[(&str, &str)]; 5] = [&PORTS, &PACKAGES, &CLASSES, &ALIASES, &HIERARCHY];
let words = [
"leaf", "clk", "q", "a_pkg", "b_pkg", "W", "word_t", "base_c", "mid_c", "m", "f", "hdr_t",
"addr", "pkt_t", "h_leaf", "u_leaf", "sig", "h_mid", "u_mid",
];
let mut checked = 0;
for seed in 1..=8u64 {
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15));
let mut files: BTreeMap<String, String> = BTreeMap::new();
for design in designs {
files.extend(design.iter().map(|(p, s)| (p.to_string(), s.to_string())));
}
let mut index = build(&files);
let paths: Vec<String> = files.keys().cloned().collect();
for step in 0..40 {
let path = &paths[rng.below(paths.len())];
let text = mutate(&files[path], &words, &mut rng);
files.insert(path.clone(), text.clone());
index.update_file(PathBuf::from(path), &text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"seed {seed}, step {step}: `{path}` became {text:?}"
);
checked += 1;
}
}
assert_eq!(checked, 320);
}
+953
View File
@@ -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, &notification);`:
`self.auto_styles.notice(&notification);`
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.
@@ -0,0 +1,449 @@
# linux-test-portability
## Goal
Every suite had only ever run on macOS arm64. Make `cargo clippy --all-targets
-- -D warnings` and `cargo test --workspace` pass on Linux x86-64 — in the CI
job image, as root (how the runner's jobs run) and as an unprivileged user —
while staying green on macOS, and do one cleaning round on the test code that
the Linux runs drive (TODO §70). Test code only: where a platform or user
genuinely cannot exercise what a test is about, the test detects it at run
time and stops with a message; it never asserts the opposite and never weakens
the assertion where it *can* run.
## Assumptions
- Root (CAP_DAC_OVERRIDE / CAP_DAC_READ_SEARCH) ignores file modes, so the
unreadable- and unwritable-path tests cannot build their path as root.
Not assumed from the uid: each test probes the exact behaviour it needs
(a mode-000 directory refuses `read_dir`, a mode-000 file refuses `open`,
a mode-555 directory refuses a new file) in a scratch path of its own,
then restores the mode.
- Case sensitivity is a property of the filesystem, not the OS. The one
runtime-probed case test (`file_ops.rs`) asks the filesystem
(`DEFS.svh` is a file when only `defs.svh` was written); the existing
`#[cfg(any(target_os = "macos", target_os = "windows"))]` case tests keep
their compile-time scope, whose reason is written at each.
- A skipped test still reports `ok` in `cargo test`; the `skipped: …` line
on stderr (visible with `--nocapture`) is how a run says so. std has no
runtime-skip outcome, and no dependency is added for one.
- The linear-time tests' bound is a ratio between sizes measured in the
same process moments apart, so it does not depend on the machine's speed;
it does assume load from the tests running beside it does not inflate the
largest size's *fastest of five* by more than ~3x relative to the
smallest's.
## Handshakes
- Consumes nothing new from production code. No production file, no
`verify.rs`, no workflow, version file or changelog changes.
- `tools/linux_check.sh` (the lead's): used as written in round 1; changed
in the fix round (QA finding 5, see the work log). Its usage line gained
`--dry-run`; the single-string form is unchanged.
- Scope extension granted by the lead in the fix round:
`crates/lucisv_server/src/server/tests/scan_trace.rs` (test file only).
- Requests: none.
## Status / TODO
- [x] Clippy clean on Linux and macOS: the three unused imports were the
only reports.
- [x] The eight permission-denied tests probe whether modes bind and stop
with a message when they do not.
- [x] The case-mismatch test probes the filesystem's case sensitivity.
- [x] The two linear-time tests bound growth, not wall-clock; shown to trip
on the quadratic conversion on macOS and on the Linux runner.
- [x] Cleaning round (see work log).
- [ ] Linux suite green as root (twice) and as `--user`. Observed: root
once green; `--user` once with one failure, the new flake
`scan_trace::the_stages_add_up_to_the_scan_they_describe` (open, see
the work log); the second root run and the flake's diagnosis were cut
off when ssh to luhpe stopped working.
- [x] `tools/gates.sh` green on macOS (see the work log for each run).
- [x] Fix round: `scan_trace` lower bound on the best of three sessions;
linear-time tests best of five; `tools/linux_check.sh` hardened.
- [ ] Open follow-up (QA finding 4, not changed on purpose):
`large.rs` `references_on_one_giant_line_locate_their_hits_in_linear_time`
times a copy of the `Server::large_scan` loop, not the production loop
at `server/large_file.rs:151`, so a per-hit rescan reintroduced there
would not be caught. Needs a test that drives the production path.
- [ ] Re-run on Linux once ssh to luhpe is back: everything in the fix round
and everything since 0.65.2 is unverified there (list in the work log).
## Work log
**2026-11-19 (dev).**
Baselines at 88546c8 (before any change). macOS `cargo test --workspace`:
93 result lines, **5307 passed, 0 failed, 57 ignored** (5364). Linux as uid
1001 (`tools/linux_check.sh --user`): **5298 passed, 3 failed, 57 ignored** —
the case-mismatch test and the two linear-time tests; every permission test
passed, which confirms the lead's hypothesis 1 (they fail only as root). The
Linux total is 6 lower than macOS's because six tests are compiled only on
macOS/Windows.
Causes, per failure:
1. *Clippy, three unused imports* (`hover.rs` `qa_hover_declarations`:
`FromStr`; `includes.rs` `qa_round2`: `super::*`, `fs`): their only users
are `#[cfg(any(target_os = "macos", target_os = "windows"))]` tests.
`qa_round2` holds nothing else, so the cfg moved onto the module (with the
reason as its doc comment) and off its two tests; in `hover.rs` the
`FromStr` import carries the same cfg as its one user.
2. *Eight permission tests* (hypothesis 1, confirmed): root opens, lists and
writes whatever the mode says. Each gets a probe of the behaviour it
relies on and returns early, saying `skipped: …`, when the probe is not
refused:
- `crates/lucisv/tests/cli.rs` — `listing_is_refused()` (mode-000 dir),
used by both walk-warning tests.
- `crates/lucisv_core/src/walk.rs` — `reading_is_refused(rel)` (mode-000
directory or file), used by the unreadable-directory and
unreadable-`.gitignore` tests.
- `crates/lucisv_mcp/src/apply.rs` — `creating_is_refused(dir)` (mode-555
dir). Only the *second* half of
`a_write_that_fails_after_another_landed_says_what_was_written` needs it:
the read-only-file refusal before it is decided from the mode bits
(`Permissions::readonly`), holds as root, and is still asserted there.
The same file is compiled into `tests/qa_m3.rs` via `#[path]`, so the
fix covers both targets.
- `crates/lucisv_mcp/tests/cache.rs` — `creating_is_refused` (mode 555,
the unwritable cache directory).
- `crates/lucisv_mcp/tests/qa_m6.rs` — `listing_is_refused` (mode 000).
- `crates/lucisv_server/src/state/tests/filelist.rs` —
`listing_is_refused()` (mode 000).
3. *Case-mismatch include* (hypothesis 2, confirmed: "must narrow in: []" on
Linux): on a case-sensitive filesystem `DEFS.svh` names no file, so there
is nothing to narrow in. The test now writes `defs.svh`, asks whether
`DEFS.svh` is a file, and stops with a message when it is not; the reason
is in its doc comment. On macOS it runs in full as before.
4. *Two `…_in_linear_time` tests* (hypothesis 3, confirmed, with a
correction). Not superlinear product code: run alone on the Linux runner
both are exactly 2x per 2x (locate 13.5 / 27.0 / 54.3 / 108.7 ms, colour
22.1 / 44.2 / 89.5 / 182.1 ms; three runs within 3%), and on macOS the
same (locate 3.4 / 6.7 / 13.6 / 26.2 ms, colour 5.6 / 11.0 / 22.6 /
44.7 ms). The trial's 4x for 100 → 200 hits (20.6 → 81.4 ms) and its
781 ms colour sample came from the full suite: the tests ran beside ~1 900
others on a 4-CPU cap, and a single sample per size took whatever load it
landed on. Alone on the runner they would even have met the old budgets
(108 < 150, 182 < 350 ms); in the suite they do not. The references test's
input grows hits *and* line length together, so the walker's work (each
byte once) is linear in `width` and the per-hit rescan's quadratic — the
test bounds the right thing.
Rewrite (`crates/lucisv_server/src/large.rs`): the fixtures are built
first; `fastest_of_three` times every size in three interleaved rounds and
keeps each size's minimum (load slows one sample of each size, not every
sample of one); `assert_grows_linearly` fails when the largest size (8x the
input) costs more than `GROWTH_SLACK` (3) × 8 = 24x the smallest. The
absolute `COLOUR_BUDGET_MS`/`LOCATE_BUDGET_MS` constants are gone. The
per-size `eprintln!` stays (the lex timing it also printed is dropped —
it was never asserted).
**Shown to trip.** Temporarily put the per-call converter back —
`positions.position(..)` for `walker.position(..)` at both sites in
`tokens::flatten` (`tokens.rs`), and `positions.range(*hit)` for
`walker.range(*hit)` in the references test's loop — and ran
`cargo test -p lucisv_server --bin lucisv-server large::tests:: -- --nocapture`:
- macOS: both FAILED — locate 6.3 / 24.9 / 99.1 / 395.8 ms, **62.8x**;
colour 34.3 / 129.2 / 511.9 / 2 060 ms, **60.0x** (limit 24x).
- Linux runner (root): both FAILED — locate 87.1 / 346.6 / 1 368.5 /
5 507.7 ms, **63.2x**; colour 383.9 / 1 539.2 / 6 503.1 / 27 667.6 ms,
**72.1x**.
Then restored both files from copies taken before the edit;
`git status` shows `tokens.rs` unmodified. With the walker: 8.0x / 8.0x on
macOS, 8.0x / 8.2x on Linux. Margin: ~3x on each side of the limit.
Cleaning round (test code only, driven by the tool reports):
- The unused imports above were everything clippy reported on either
platform; `cargo build`/`cargo test` reported no other test warnings.
- `walk.rs`'s `TempTree` was documented "removed on drop" but had no `Drop`
impl, so every walk test left its tree in the temp dir; added the
three-line `Drop` the comment describes (the test trees restore their
modes before returning, so removal succeeds).
- The other wall-clock assertions in the suites (`server/tests/startup.rs`,
`tests/e2e.rs`'s grace checks, `vlog_semantic/tests/workspace.rs`'s 5 s
build bound) passed on every Linux run here and are left as they are;
`large.rs`'s hundred-megabyte probe is `#[ignore]`d.
Final runs, all against the finished tree (every change above, including
`#[track_caller]` on `assert_grows_linearly`; nothing in `crates/` changed
after them, only this README and TODO.md):
- macOS `cargo test --workspace` (guarded): 93 result lines, **5307 passed,
0 failed, 57 ignored** — the baseline's count exactly.
- Linux root, then `--user` (2026-11-19, both finished before the ~05:00 ssh
outage), root: `cargo clippy --all-targets -- -D warnings`
exit 0, no diagnostics; `cargo test --workspace --no-fail-fast`: 93
result lines, **5301 passed, 0 failed, 57 ignored**.
- Linux `--user` (right after): clippy exit 0, no diagnostics; tests **5300
passed, 1 failed, 57 ignored** — the failure is
`server::tests::scan_trace::the_stages_add_up_to_the_scan_they_describe`
at `crates/lucisv_server/src/server/tests/scan_trace.rs:163`, the
`sum >= total * 0.5` assertion (the stages a `--verbose` scan's trace
names must cover at least half its wall-clock total). It passed in the
root run, in the lead's 88546c8 `--user` run, and 15 times out of 15 run
alone as `--user`; a repeat of the whole `lucisv_server` binary to catch
its numbers was cut off by the ssh outage (exit 137 from the ssh side, not
a guard kill). Reading: a wall-clock ratio over a ~20 ms scan, where a
preemption landing in the deliberately unattributed loop time (progress
callbacks, staging pushes) on the 4-CPU runner under the full suite's load
can tip it below half. **Open, not changed**: without its failing numbers
any change to the 0.5 would be a weakening without evidence.
- Not done: the second Linux root run the brief asks for.
- macOS after trunk's fast-forward to 0.65.2 (e9f5090; touched no file
this lane edits): `cargo fmt --all -- --check` exit 0, clippy clean,
`tools/gates.sh` **PASS** (`target/gates/20261119-050602/`: every step
pass; suites vlog_parser 521, vlog_semantic 418, vlog_refactor 743,
vlog_formatter 352, vlog_linter 672, lucisv_core 117, lucisv 143,
lucisv_server 1957, lucisv_mcp 383, all 0 failed; corpus 814/6, node
12/0). An earlier gates run (03:58) was cut off mid-`lucisv_mcp` when the
session restarted — not a guard kill — and is not counted. The Linux runs
above were against 88546c8 + this lane, not against 0.65.2.
**2026-11-19 (dev, fix round after QA's PASS WITH FINDINGS).** Tree: trunk
948f8a0 (0.65.3) + this lane. ssh to luhpe is down, so nothing in this
round ran on Linux.
1. *scan_trace flake* (QA finding 2). `the_stages_add_up_to_the_scan_they_describe`
now runs three verbose sessions over the same 40-file tree. It asserts
`total > 0` and `sum <= total * 1.02` on **every** session (structural:
the stages are disjoint pieces of the scan), and `sum/total >= 0.5` on
the **best** of the three (a stall in the ~35% unattributed loop time
spoils one sample, not all three). The reason is in the test's comment.
The stage list moved to a helper, `named_stage_sum`.
- Unmutated, macOS: 3 sample ratios 0.64 / 0.68 / 0.69.
- *Does it still bite?* Temporary production mutations, each built into a
copied test binary and then restored from a copy (`git status` clean for
both files after):
- `scan_trace.rs:321`, the `read` stage not recorded: 30/30 runs of the
copied binary FAILED (best 0.41–0.47). Of 3 runs through cargo, one
passed: the first, run just after the build.
- `state/rescan.rs:358`, the `parse` stage not recorded: **27/30** FAILED
(best 0.38–0.49), 3 passed. A per-sample count of the same mutant
(what the old single-session assertion would have checked):
87/90 samples under 0.5. So best of three trades some sensitivity to
one dropped mid-sized stage (~97% → 90% for `parse`, about a fifth of
the scan) for not flaking under load. A dropped stage under ~17% of
the scan is invisible to a 0.5 bound either way, as before.
- *Under load*, the way QA did it (guarded; the test binary looped 200x
while the whole `lucisv_server` binary looped beside it): 0/200 failed;
a second 200x run, with 8 full-suite iterations counted alongside: 0/200.
2. *`tools/linux_check.sh`* (QA finding 5).
- `set -o pipefail`, and tar's stderr is no longer hidden.
- One argument is a command line as before. Several are quoted with
`printf '%q '`, so `linux_check.sh grep -rn "two words" crates` keeps
`two words` whole.
- A fixed container name, `--name lucisv-linux-check`, so a second
concurrent run is refused by Docker; exit 125 prints a hint.
- The header says that untracked non-ignored files are sent and that
runs are one at a time.
- New `--dry-run`: builds the archive locally, prints its size and the
remote command, and contacts nothing.
Tested locally:
- `bash -n` ok (shellcheck is not installed).
- `--help` prints the whole header.
- `--dry-run` with one string and with several arguments: the remote
`CMD` shows the quoting kept.
- `LUCISV_LINUX_HOST=nonexistent.invalid`: exit 255, ssh's error shown.
- In a throwaway git repo with a tracked file deleted: `--dry-run` exit 1
and the real path exit non-zero, with `tar: b.txt: Cannot stat` shown;
restoring the file makes the dry run pass.
**The remote half is untested since this change**: the `--name`
refusal, the 125 hint, and the multi-argument `CMD` reaching
`bash -c` on luhpe.
3. *Linear-time headroom* (QA finding 3). `fastest_of_three` → `fastest_of_five`;
`GROWTH_SLACK` unchanged. QA's loaded loop (30 runs, 36 busy loops on 18
CPUs, load average ~40, guarded): 30/30 passed. Worst ratios: colour
**10.8x**, locate **8.5x** (limit 24x; QA saw 18.2x at three rounds).
Cost: on the quadratic code a failing run now takes 5/3 as long (Linux
root colour ~3 min, from the round-1 measurements).
Checks this round (macOS, tree 948f8a0 + lane):
- `cargo fmt --all -- --check` exit 0.
- `cargo clippy --all-targets -- -D warnings` exit 0.
- `tools/guard.sh -- cargo test -p lucisv_server`: 1848 + 106 + 3 + 0
passed, 0 failed (36 + 3 + 0 + 2 ignored).
- `tools/gates.sh` **PASS** (`target/gates/20261119-053236/`): every step
pass; suites 521/418/743/352/672/117/143/1957/383, all 0 failed; corpus
814/6; node 37/0.
Unverified on Linux (all of it rests on round 1, against 88546c8 + lane):
- the `scan_trace.rs` rewrite;
- best of five in `large.rs`;
- the new `linux_check.sh`;
- QA's `qa_m6.rs` doc-comment move;
- everything trunk added in 0.65.2 and 0.65.3;
- the second root run, which never happened in round 1 either.
## QA log
**2026-11-19 (QA, macOS arm64, 18 CPUs; tree = 948f8a0 + this lane).**
Verdict: **PASS WITH FINDINGS.** Linux was **not** independently verified.
*Scope.* Every hunk of `git diff -- crates/` is inside a `#[cfg(test)]`
module or a `tests/` file: `cli.rs`, `cache.rs`, `qa_m6.rs` (integration
tests), `walk.rs`/`apply.rs`/`file_ops.rs`/`large.rs` (inside `mod tests`),
`filelist.rs` (under `state/tests/`), `hover.rs` (an import in the
`#[cfg(test)] mod qa_hover_declarations`), `includes.rs` (the
`#[cfg(test)] mod qa_round2` attribute widened to
`all(test, any(macos, windows))`, the two per-test cfgs dropped — same
compiled set). `walk.rs`'s new `Drop for TempTree` sits in `mod tests`
(the struct is test-only). No `verify.rs`, no production line, `tokens.rs`
and `convert.rs` unmodified.
*No skip on macOS.* All 11 tests (plus `apply`'s copy in `tests/qa_m3.rs`
and `--bin lucisv-mcp`) run with `--nocapture`: all `ok`, no `skipped:`
line.
*Mutations* (copies in the scratchpad, restored with `cp`; `git diff --stat`
and the full `git diff` compared byte-for-byte with the pre-mutation
capture: identical):
| test | mutation | failed? | restored |
|---|---|---|---|
| cli `an_unreadable_directory_is_a_warning…` | `walk.rs` `entries`: `Err(_) => return` (no warning) | yes, cli.rs:2277 | yes |
| cli `the_walks_warnings_leave_check_modes…` | same | yes, cli.rs:2296 | yes |
| walk `an_unreadable_directory_is_skipped…` | same | yes, walk.rs:847 | yes |
| filelist `an_unreadable_directory_is_said_once…` | same | yes, filelist.rs:106 | yes |
| walk `an_unreadable_ignore_file_is_said…` | `walk.rs` `push_ignore`: drop the `say` | yes, walk.rs:864 | yes |
| apply `a_write_that_fails_after…` (bin + qa_m3) | `apply.rs:192` message `written`→`wrote` | yes, both targets, apply.rs:322 (the post-probe half) | yes |
| cache `an_unwritable_cache_directory…` | asserted count 1→2 | yes, cache.rs:276 | yes |
| qa_m6 `qa_a_cache_directory_without_permission…` | asserted count 1→2 | yes, qa_m6.rs:485 | yes |
| file_ops `a_case_mismatched_include…` | `read.contains` inverted | yes, file_ops.rs:729 | yes |
| large colour / locate | own mutation: a fresh walker per piece in `tokens::flatten`, a fresh walker per hit in the test's loop | yes: **74.0x** and **64.5x** (limit 24x) | yes; `tokens.rs` no diff; pass again at 8.1x/8.1x |
*Probe attacks.* No false skip found: every probe builds its scratch path
next to (same filesystem as) the test's own, under a pid(+counter)-unique
name (`filelist.rs`'s `modeprobe` is pid-only but has one caller); a setup
failure panics (`expect`/`unwrap`) instead of returning "not refused"; a
spurious error can only read as "refused", which runs the test (a loud
failure, not a masked one); there is no panic path between the chmod and
its restore; probes remove their paths (Drop or `remove_dir_all`). Root
with DAC capabilities gets "not refused" (dev-observed on Linux, not
re-run). 20 loops of the eight affected targets (cli walk, core walk,
mcp bin + qa_m3 apply, cache, qa_m6, server filelist, server file_ops):
**0/160 failures**, and no `lucisv*` temp dir or mode-000/555 path left
behind (walk.rs's new `Drop` works; before it, 18 walk dirs per run were
left in `$TMPDIR`).
*Linear-time tests.* Under load, best of three interleaved: 30 runs while
a release `cargo build` ran: 0/30 failed, ratios 7.9–8.5x; 30 runs with 36
busy loops on 18 CPUs (load ~30) as well: 0/30 failed, ratios **up to 18.2x
(colour) and 13.9x (locate)**, so only ~1.3x left under the 24x limit at
2x oversubscription. Judgement: a constant-factor regression of any size
(2.9x or 100x) passes by design: the ratio cannot see it, and the old
absolute budgets that could were dropped on purpose. n·log n passes
(~9.9x). A mixed cost slips through when its quadratic part is under ~28%
of the smallest size's cost (`8(1-q)+64q ≤ 24`). That is acceptable for a
test named "linear time" that guards against the per-call converter
coming back (60–74x).
*scan_trace flake (dev's open item) — reproduced on macOS.* I built an
instrumented test binary (a temporary `eprintln!` of sum/total, source
restored at once, `git diff` clean) and ran the test 200x under 36 busy
loops: 0/200 failed, sum/total 0.62–0.69, total 2.1–4.4 ms. Then 200x while
the whole `lucisv_server` suite looped beside it: **1/200 failed**: stages
**2.21 ms of total 5.10 ms (0.43)**. Two more runs came in at 0.54 and 0.67
with totals of 4.8 and 2.7 ms. Analysis: `total_ms` runs from
`ScanTrace::new` in `begin_scan` to `landed`. The named stages are disjoint
sub-intervals of it, so `sum ≤ total` is deterministic (up to `{:.2}`
rounding, 19 × 0.005 ms). But ~35% of an unloaded scan is deliberately
unattributed: the server's per-step `watching` callbacks, progress/log
sends and loop overhead in `server/index.rs` `scan_once`. A stall that
lands there grows `total` and no stage. The failing sample is exactly that:
the stage sum is normal (2.21 ms) and the 2.9 ms extra sits outside every
stage. With U≈0.35·T, one stall longer than ~0.3·T in unattributed code
trips the bound: ~0.75 ms on macOS, ~6 ms on the Linux runner's ~20 ms
scan, where CFS quota throttling under `--cpus` gives stalls of tens of
ms. So the lower bound is a statistical claim and is unsound under load on
any machine. **Recommended change** (outside this lane's files, not made
here): keep `sum <= total * 1.02` per scan, and assert the lower bound on
the best of three sessions. Run `Session::verbose_wide` three times and
require `max(sum/total) >= 0.5`, the same "load slows one sample, not
every sample" argument as `fastest_of_three`. The alternative is to drop
the lower bound and assert only that the CPU-bound stages (`discovery`,
`read`, `parse`) are each > 0.
*Gates (macOS, `tools/gates.sh`, `target/gates/20261119-052309/`):* PASS —
fmt, clippy, build, docs pass; suites vlog_parser 521/0, vlog_semantic
418/0, vlog_refactor 743/0, vlog_formatter 352/0, vlog_linter 672/0,
lucisv_core 117/0, lucisv 143/0, lucisv_server 1957/0, lucisv_mcp 383/0;
corpus 814/6; node 37/0. Separately `cargo fmt --all -- --check` exit 0,
`cargo clippy --all-targets -- -D warnings` exit 0 (only cargo's
pre-existing manifest `authors` notice), guarded `cargo test --workspace
--no-fail-fast`: 93 result lines, **5307 passed, 0 failed, 57 ignored**,
the dev's count exactly.
*Linux: NOT verified by QA.* `tools/linux_check.sh 'echo ok'` (once):
`Permission denied (publickey)`, exit 255; not retried. These results rest
on the dev's word alone: root clippy clean and 5301 passed/0 failed;
`--user` clippy clean and 5300 passed/1 failed (the scan_trace flake,
which is now reproduced on macOS). The second root run was never done.
Nothing here has run on Linux since the 0.65.2/0.65.3 fast-forwards.
*Findings.*
1. (low, fixed by QA) `crates/lucisv_mcp/tests/qa_m6.rs:447`: the new
helper was inserted between the test's doc comment and the test, so
`qa_a_cache_directory_without_permission…`'s four-line doc comment had
become the head of `listing_is_refused`'s doc. I moved it back above the
test; the diff now only adds the helper and the guard.
2. (medium, open, outside scope) `server/tests/scan_trace.rs:163`: the
flake above, with its reproduction and the recommended change.
3. (low) `large.rs` linear-time margin under heavy oversubscription:
18.2x of 24x seen. Watch it on the 4-CPU runner; if it flakes, raise
the number of rounds, not `GROWTH_SLACK`.
4. (low, pre-existing) `large.rs` `references_on_one_giant_line…` times a
copy of the `Server::large_scan` loop (`server/large_file.rs:151`), not
the production code, so a regression there is not caught. The mutation
had to go into the test's own loop.
5. (low) `tools/linux_check.sh` review:
- The pipeline has no `pipefail`, and tar's stderr goes to
`/dev/null`. A local `git ls-files`/tar failure, or a file that
vanished, gives a silently partial tree, and the run is judged on it.
A missing archive does fail remotely (`tar xzf` under `set -e`).
- `cmd=$*` drops argument quoting (`linux_check.sh grep "a b" f` runs
`grep a b f`). The documented single-string form is fine.
- `--others --exclude-standard` ships any untracked, non-ignored file
(a stray `.env`, key or dump) to luhpe, though only into a `--rm`
container, not the volume. Today that is just this README and the
script itself (16 KiB).
- Not safe to run concurrently: two runs share the
`lucisv-linux-check` volume, so they race on a cold rustup install
into `/cache`. A `--user` run's `chown -R /cache` flips ownership
under a running root build, and one run can execute test binaries
the other rebuilt from a different tree. A host-side `flock`, or a
fixed `docker run --name` so a second run fails fast, would close
this.
- The remote quoting is right: one `%q` for the one shell level on the
host, and `docker exec`/`docker run` pass argv with no shell. Exit
status propagates through ssh → docker → `bash -c`.
*Fixed by QA:* finding 1 only. *Unverified:* everything on Linux, as
above.
## Review
**Lead, 2026-11-19.** Accepted on macOS evidence; Linux line left open.
- Test code only, and QA checked every hunk for that. The risk in a lane like
this is a test that passes by no longer testing: QA's mutation table (every
modified test made to fail, every file restored byte-identically) and the
"none prints `skipped:` on macOS" run are what make it acceptable.
- I was wrong about the references test: I read 100→200 hits costing 4x as a
possible superlinear product bug and told the dev so. Measured alone it
doubles per doubling on both platforms; the 4x was the parallel suite. The
ratio assertion that replaced the wall-clock budget is the better test, and
it was shown to trip at ~60–74x on a quadratic implementation by dev and QA
independently.
- `scan_trace` was a pre-existing fragile test that Linux exposed and QA then
reproduced on macOS (2.21 ms of 5.10 ms). I extended scope to fix it. The
best-of-three lower bound costs sensitivity (the dev measured ~97% → ~90%
on a dropped `parse` stage) — accepted and written down, not hidden.
- **Not verified on Linux**: everything since round 1 — the `scan_trace`
rewrite, best-of-five in `large.rs`, the rewritten `tools/linux_check.sh`
(its remote half has never run), and all of 0.65.2–0.65.4. The owner's ssh
key expired mid-lane. TODO §70's Linux line and the `ci.yml` job stay
unticked until that run happens; the Linux job is not added blind.
- Open follow-up, recorded under Status: the references linear-time test
times a copy of `Server::large_scan`'s loop, not the production code.
File diff suppressed because it is too large. Load diff
+24
View File
@@ -1444,3 +1444,27 @@ A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms +
merge 204 ms; a cold one parses instead (1 387 ms). The rows are not
like-for-like with the server's (it scans in stages and answers during the
scan); they sit side by side so a regression in either shows.
### 2026-11-19 — localized reindex (TODO §71.1)
What one save costs the index on the full OpenTitan `hw` tree (4 058 files,
scope `workspace`, 10 buffers open), measured over LSP with the real release
server and in-process with `state::tests::reindex_perf` (release,
`--test-threads=1`); medians, the machine shared with another lane's builds.
Details and the method: `docs/features/localized-reindex/README.md`.
| | before (7408fac) | after |
|---|---:|---:|
| `reindex_one`, any edit, any file | 141–158 ms | — |
| …the watcher's echo of a save / an unchanged record | 153–176 ms, everything republished | 0.07–1.1 ms, nothing sent |
| …a local signal in a module (`uart_tx`, `prim_flop`) | 144–145 ms | 5.2 ms |
| …a package member added (`uart_reg_pkg`) | 148 ms | 11.7 ms |
| …a line above everything in `prim_flop.sv` (125 instantiating files) | 144 ms | 61 ms |
| watcher event for a `.sv` the scope cannot take | 746 ms whole rescan | 3.5 ms, nothing |
| whole merge (`absorb`, startup / cached rescan) | 135 / 165 ms | 158 / 189 ms |
| warm startup scan (fix round, QA's `perf.py`, two runs) | 1 113 / 1 124 ms | 1 171 / 1 148 ms |
| `prim_mubi_pkg` member added, 677 importers (fix round) | 162 ms | 92 ms |
| readers table | — | 13 806 keys, 69 222 entries |
| mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged |
Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`.
+29
View File
@@ -5,6 +5,35 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.65.7 — 2026-11-19
- **0.65.6, now for every platform.** 0.65.6 was never published — it did not
compile for Windows. This release carries its changes: saving no longer
re-indexes the workspace, no surprise "indexing" bar for generated or
out-of-scope files, and the line-length warning follows your formatting
style's width.
## 0.65.6 — 2026-11-19
- **Saving no longer re-indexes the workspace.** On a large project a save
used to cost a whole-index pass, twice (once for the save, once for VS
Code's file watcher). A typical edit now costs a few milliseconds, and a
save that changes nothing the index records costs nothing.
- **No more surprise "indexing" bar** for generated files, files outside the
filelist or folder scope, or files reached through a symlink.
- **The line-length warning follows your formatting style's width.**
## 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
- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a
+26 -3
View File
@@ -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
setup.
The current release is **0.65.4**. Its platform packages include
The current release is **0.65.7**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[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.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.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.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 |
@@ -404,8 +405,11 @@ The configuration ladder is:
1. The nearest `lucisv.toml` / `.lucisv.toml` discovered for the file.
2. `lucisv.lineLength` and `lucisv.indent` editor settings.
3. VS Code's tab size, for indentation only.
4. Built-in defaults: 100 columns and 2 spaces.
3. The indent and width of the style the file resolves to (`[format] style`
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
are always layered over the chosen scope, even when a scratch file is not in
@@ -436,6 +440,25 @@ default):
}
```
## Release 0.65.7 highlights
Version 0.65.7 is 0.65.6 built for every platform (0.65.6 was never published:
it did not compile for Windows): saving is cheap on large projects, because
the language server updates only what an edit can reach.
## Release 0.65.6 highlights
Version 0.65.6 makes saving cheap on large projects: the language server
updates only what an edit can reach instead of re-resolving the whole index —
on OpenTitan a typical save drops from about 160 ms (twice) to a few
milliseconds.
## 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
Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.65.4",
"version": "0.65.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.65.4",
"version": "0.65.7",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+24 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.65.4",
"version": "0.65.7",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -583,6 +583,29 @@
"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."
},
"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": {
"type": "boolean",
"default": false,
+5 -1
View File
@@ -119,7 +119,11 @@ for each workspace member in turn, the doc-tests (`cargo test --workspace
--doc`), the corpus gate (`scripts/corpus_gate.sh` over
`~/.cache/lucisv-corpus`, as CI runs it; skipped with a note when the corpus
is absent — fetch it once with `tools/corpus_fetch.sh ~/.cache/lucisv-corpus`)
and the extension's `node --test editors/vscode/*_test.js`. It prints one line
the extension's `node --test editors/vscode/*_test.js`, and `cross` — a
`cargo check` of the three binaries for Windows and Linux with the rustup
toolchain the release build uses (skipped with a note when it is absent;
added after 0.65.6 passed every other gate and then failed to compile for
Windows). It prints one line
per step start and end, then a table (step, result, seconds, passed/failed,
log); it exits non-zero if any step failed. A step the guard killed is
retried once and reported as `KILLED → retried → pass|fail` — a kill that
+21 -1
View File
@@ -12,6 +12,12 @@
# over ~/.cache/lucisv-corpus as CI does (skipped, with a
# note, when that directory is absent; -c overrides it)
# node node --test editors/vscode/*_test.js
# cross cargo check of the three shipped binaries for Windows and
# Linux with the rustup toolchain release.sh --cross uses
# (skipped, with a note, when that toolchain is absent).
# Platform-conditional code is compiled nowhere else before
# the release build: 0.65.6 passed every other gate and then
# failed to compile for Windows.
#
# Each step's output goes to its own log under the log dir (default
# target/gates/<timestamp>/, -o overrides); the terminal gets one line per
@@ -41,6 +47,9 @@ repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo_root" || exit 2
log_dir=
corpus=$HOME/.cache/lucisv-corpus
# The toolchain release.sh --cross builds with; the Homebrew rust on PATH has
# no std for other targets.
cross_toolchain=$HOME/.rustup/toolchains/stable-aarch64-apple-darwin
only=
skip=
@@ -84,7 +93,7 @@ all_steps() {
local c
echo fmt clippy build
for c in $(crates); do echo "suite:$c"; done
echo docs corpus node
echo docs corpus node cross
}
# Does step $1 match the comma list $2? "suites" matches every suite:<crate>.
@@ -119,6 +128,7 @@ limits() {
suite:*) echo "300 4" ;;
docs) echo "300 2" ;;
corpus) echo "900 6" ;;
cross) echo "900 6" ;;
esac
}
@@ -133,6 +143,9 @@ set_command() {
corpus) cmd=(bash -c 'cargo build --release -p lucisv && scripts/corpus_gate.sh "$1"'
corpus-gate "$corpus") ;;
node) cmd=(node --test editors/vscode/*_test.js) ;;
cross) cmd=(env RUSTC="$cross_toolchain/bin/rustc" "$cross_toolchain/bin/cargo" check
--target x86_64-pc-windows-gnu --target x86_64-unknown-linux-musl
-p lucisv -p lucisv_server -p lucisv_mcp) ;;
esac
}
@@ -201,6 +214,13 @@ for step in $steps; do
echo "skipped: no corpus at $corpus (tools/corpus_fetch.sh \"$corpus\")" >"$log"
echo " skip $step (no corpus at $corpus)"
rows="$rows$step|SKIPPED (no corpus)|0|-|$log
"
continue
fi
if [ "$step" = cross ] && [ ! -x "$cross_toolchain/bin/cargo" ]; then
echo "skipped: no rustup toolchain at $cross_toolchain (tools/RELEASING.md)" >"$log"
echo " skip $step (no rustup toolchain)"
rows="$rows$step|SKIPPED (no toolchain)|0|-|$log
"
continue
fi
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env bash
# Run a command against this working tree on Linux, inside the same job image
# the luhpe-linux-x64 Actions runner uses, without pushing anything.
#
# The tree is streamed over ssh into a throwaway container started by the
# runner's own Docker daemon on luhpe, so it runs under the runner's cpu and
# memory limits. What is sent: every tracked file as it is on disk, plus every
# UNTRACKED file git does not ignore (a stray .env or key file included -
# check `git status` first). A tracked file deleted from the working tree, or
# any other local tar error, fails the run before anything is judged; a
# partial tree is never shipped. The Rust toolchain and the cargo target
# directory are kept in a Docker volume between runs, so only the first run
# is a cold build.
#
# One run at a time: the runs share that volume (toolchain install, target
# dirs, a --user run's chown), so the container has a fixed name and a second
# run while one is in flight is refused by Docker ("name ... already in use").
# A run whose ssh dropped keeps its container until its command ends.
#
# Usage: tools/linux_check.sh [--user] [--dry-run] [--] <command...>
# tools/linux_check.sh 'cargo clippy --all-targets -- -D warnings'
# tools/linux_check.sh --user cargo test -p lucisv_core
# tools/linux_check.sh grep -rn "two words" crates
#
# One argument is a shell command line, run as written (pipes, ;, quotes).
# Several arguments are one command and its arguments, each kept whole.
# By default the command runs as root, which is how the runner's jobs run and
# so what CI will see. --user runs it as an unprivileged user instead: file
# permissions are enforced there, which root ignores. --dry-run builds the
# archive locally (to check the local half), prints its size and the remote
# command, and contacts nothing.
#
# Needs: ssh access to the host `luhpe` (LUCISV_LINUX_HOST overrides) and the
# gitea-runner container on it (docs: tools/RELEASING.md, "CI releases").
# Exit status is the command's, or non-zero if the archive or the
# connection failed.
set -eu -o pipefail
host=${LUCISV_LINUX_HOST:-luhpe}
image=docker.gitea.com/runner-images:ubuntu-latest
name=lucisv-linux-check
as_user=0
dry_run=0
while [ $# -gt 0 ]; do
case $1 in
--user) as_user=1; shift ;;
--dry-run) dry_run=1; shift ;;
--) shift; break ;;
-h|--help) sed -n '2,37p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) break ;;
esac
done
[ $# -ge 1 ] || { echo "usage: $0 [--user] [--dry-run] [--] <command...>" >&2; exit 2; }
if [ $# -eq 1 ]; then
cmd=$1
else
cmd=$(printf '%q ' "$@")
fi
repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo_root"
# Inside the container: unpack stdin to /w, make sure the toolchain is in the
# cache volume, then run the command as root or as uid 1001.
inner='
set -eu
export RUSTUP_HOME=/cache/rustup CARGO_HOME=/cache/cargo
mkdir -p /w && tar xzf - -C /w
if [ ! -x "$CARGO_HOME/bin/cargo" ]; then
curl --proto =https --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal -c clippy,rustfmt --no-modify-path >/dev/null 2>&1
fi
export PATH="$CARGO_HOME/bin:$PATH"
if [ "$AS_USER" = 1 ]; then
export CARGO_TARGET_DIR=/cache/target-user HOME=/tmp/home
mkdir -p "$CARGO_TARGET_DIR" "$HOME"
chown -R 1001:1001 /w /cache "$HOME"
cd /w && exec setpriv --reuid 1001 --regid 1001 --clear-groups bash -c "$CMD"
fi
export CARGO_TARGET_DIR=/cache/target-root
# An earlier --user run leaves the cache owned by uid 1001; root does not mind.
cd /w && exec bash -c "$CMD"
'
remote="docker exec -i gitea-runner docker run --rm -i --name $name \
-v lucisv-linux-check:/cache \
-e AS_USER=$as_user -e CMD=$(printf '%q' "$cmd") \
$image bash -c $(printf '%q' "$inner")"
# The tree as a gzipped tar on stdout. COPYFILE_DISABLE and --no-xattrs keep
# macOS tar from adding ._* entries and extended-attribute headers that GNU
# tar on the other side warns about. Errors are not hidden: with pipefail a
# file tar cannot read fails the whole run.
archive() {
git ls-files -z --cached --others --exclude-standard \
| COPYFILE_DISABLE=1 tar czf - --no-xattrs --null -T -
}
if [ "$dry_run" = 1 ]; then
bytes=$(archive | wc -c)
echo "archive: $((bytes)) bytes; would run on $host:"
echo "$remote"
exit 0
fi
status=0
archive | ssh -o BatchMode=yes "$host" "$remote" || status=$?
if [ "$status" = 125 ]; then
echo "linux_check: docker refused to start the container; if it says the name" \
"\"$name\" is in use, another run is in flight - wait for it." >&2
fi
exit "$status"
+73
View File
@@ -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