Rename the tool to lucisv (Language Utility for Coding In SystemVerilog)

This commit is contained in:
lucio committed 2026-08-25 23:36:00 -07:00
1 parent a284e33110
commit eeaffafd56
188 files changed
+2825 -2802

No files matched your search

Vendored
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -2,5 +2,5 @@
/corpus
/corpus-check-results.tsv
/dist
/.vfmt_cache
/.lucisv_cache
/.score-results.tsv
+33 -33
View File
@@ -1,6 +1,6 @@
# Changelog
All notable changes to vfmt are recorded here. Versions follow
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.
@@ -16,7 +16,7 @@ than its opener: VS Code re-indents every snippet line after the first with
the trigger line's own indentation, and the server was baking that
indentation in as well. Ghost bodies are now indented *relative* to the
trigger line — the editor's own `tabSize`/`insertSpaces` place them, so
`begin` and `end` align in any indent style (`vfmt.indent` no longer sizes
`begin` and `end` align in any indent style (`lucisv.indent` no longer sizes
them). The completion popup's multi-line skeletons had the same latent
double indent since 0.4.0; they keep their layout and now tell the editor
`insertTextMode: asIs` instead.
@@ -42,7 +42,7 @@ at the end of a line and its `end` does. Tab accepts as a snippet — the
cursor lands in the condition first and on the indented body line second.
This is LSP 3.18 `textDocument/inlineCompletion`: token-based triggers (a
comment, a string or `my_if` never fire), offered only while the construct
is genuinely unclosed, indented to the site. `vfmt.inlineTemplates: false`
is genuinely unclosed, indented to the site. `lucisv.inlineTemplates: false`
turns it off. The VS Code extension opts into the still-proposed client
feature; Neovim's built-in client does not speak it yet, and those users
keep the same skeletons in the completion list. Details:
@@ -60,7 +60,7 @@ independent old-algorithm oracles kept as regression tests.
## 0.5.0 — 2026-08-25
The navigation release. `0.3.0` taught vfmt to *change* a project and `0.4.0`
The navigation release. `0.3.0` taught lucisv to *change* a project and `0.4.0`
to complete what you are typing; this one is about reading one you did not
write — who instantiates this module, which file defines this macro, what does
this ordered connection actually connect, and what does this macro call turn
@@ -109,7 +109,7 @@ quoted path and `textDocument/definition` jumps to the file, resolved through
the including file's own directory and then each `+incdir+` of the configured
filelist in order (the `<angled>` form skips the first rung). The same graph
makes hover on `` `NAME`` prefer the definition the hovered file actually
*reaches* through its includes — the first thing vfmt has that can order two
*reaches* through its includes — the first thing lucisv has that can order two
definitions of one macro name. Where the graph orders nothing, the honest
all-candidates list from before still stands. Details:
[include-nav](docs/features/include-nav/README.md).
@@ -134,13 +134,13 @@ a name refers to. **All three are off by default** and are opted into with
`--select`: they are diagnose-only, they see one file at a time (a signal
driven by a cross-module connection is not yet visible to them), and a semantic
rule that cries wolf costs an engineer a debugging session and their trust in
the tool. A default `vfmt check` is byte-for-byte what it was, and pays nothing
the tool. A default `lucisv check` is byte-for-byte what it was, and pays nothing
for the analysis it does not run. Details:
[semantic-lints](docs/features/semantic-lints/README.md).
### `vfmt -f project.f`
### `lucisv -f project.f`
The CLI gets the front door the language server got in `0.3.0`: `vfmt -f
The CLI gets the front door the language server got in `0.3.0`: `lucisv -f
project.f` formats or checks exactly the files an EDA filelist names, nested
`-f` and `$VAR` expansion included. The flag is repeatable and combines with
positional paths; a path the filelist names is a named path, so `--exclude`
@@ -157,7 +157,7 @@ and the card says so; `` `"`` and ```` `` ```` pass through as written; string
literals and escaped identifiers are not substituted into. An argument count
that does not match the parameter list expands nothing at all rather than
guessing, and where hover lists several candidate definitions there is no
winner to expand. vfmt still does not preprocess — this is bookkeeping shown in
winner to expand. lucisv still does not preprocess — this is bookkeeping shown in
a tooltip, and the formatter cannot see it. Details:
[macro-expansion](docs/features/macro-expansion/README.md).
@@ -218,7 +218,7 @@ position, a declaration at both — and **by dialect**: a `.sv` file is offered
so nothing on the list is code the buffer's own compiler would reject. A client
that does not understand snippets gets the same skeleton with its defaults
filled in rather than a buffer full of `${1:…}`. Every template's untouched
expansion is parsed by vfmt's own parser in the test suite, which is what keeps
expansion is parsed by lucisv's own parser in the test suite, which is what keeps
the list honest. Details:
[completion-templates](docs/features/completion-templates/README.md).
@@ -240,17 +240,17 @@ only the first three of those have a visible default: `foreground4`, `5` and
`6` default to fully transparent and are left for themes to define, which most
themes never do. Any `begin`/`end` at nesting depth 3, 4 or 5 was therefore
painted transparent, and the keyword vanished from the screen. The rainbow now
uses its own colours, `vfmt.rainbow1` … `vfmt.rainbow6`, contributed by the
uses its own colours, `lucisv.rainbow1` … `lucisv.rainbow6`, contributed by the
extension with an opaque default for dark, light and both high-contrast themes;
they appear under Workbench → Appearance → Color Customizations like any other
theme colour, so a theme or a `workbench.colorCustomizations` entry can still
override them. Levels 1–3 keep VS Code's familiar bracket hues so nothing
changes for the depths that already worked.
The same round makes the other half of the story visible: `vfmt/scopePairs` now
The same round makes the other half of the story visible: `lucisv/scopePairs` now
also reports **unmatched** block delimiters — a `begin` whose `end` never
arrived, an `end` that closes nothing — and the extension paints them in a
bright error red (`vfmt.rainbowUnmatched`) instead of leaving them as ordinary
bright error red (`lucisv.rainbowUnmatched`) instead of leaving them as ordinary
uncoloured text. Typing a fresh `begin` now shows red until its `end` exists,
rather than showing nothing at all. Matched pairs, their nesting depths and the
missing-`end` warnings are unchanged. Details:
@@ -266,10 +266,10 @@ you are typing.
### Project scope: filelists
vfmt now accepts a standard EDA **filelist** (`-f` style: one path per line,
lucisv now accepts a standard EDA **filelist** (`-f` style: one path per line,
nested `-f`, `+incdir+`/`+define+`, `#` and `//` comments, `$VAR`/`${VAR}`
expansion, unknown `+args`/`-flags` skipped with a warning). When one is
configured — `vfmt.filelist` in the editor, or a `filelist` key in `vfmt.toml`
configured — `lucisv.filelist` in the editor, or a `filelist` key in `lucisv.toml`
— it defines *exactly* the set of files the language server indexes, which is
what a project with a build already says out loud. Without one the scope ladder
falls back to the workspace-folder walk, and, when no folder was opened at all,
@@ -290,7 +290,7 @@ collision with an existing name in any affected scope, on an invalid
identifier, and whenever any touched file would no longer parse — whole-edit-
or-nothing, the same contract the formatter has always had. Occurrences inside
a `` `define`` body or an `` `ifdef``-excluded arm are reported as a warning and
left alone, because vfmt does not preprocess. Details:
left alone, because lucisv does not preprocess. Details:
[rename](docs/features/refactor-rename/README.md).
### Module signature changes
@@ -341,19 +341,19 @@ files answer a request in about 300 µs. Details:
### Editors
One new setting, `vfmt.filelist`, forwarded like the rest of `vfmt.*`.
One new setting, `lucisv.filelist`, forwarded like the rest of `lucisv.*`.
Everything else in this release arrives through the server, so no editor
configuration changes.
## 0.2.0 — 2026-08-19
The first released version. `0.1.0` was the workspace's initial version number
and was never tagged or published, so these notes describe vfmt as it stands
and was never tagged or published, so these notes describe lucisv as it stands
rather than a delta against a shipped predecessor.
vfmt is a formatter, a linter and a language server for Verilog-2001 and the
lucisv is a formatter, a linter and a language server for Verilog-2001 and the
synthesizable SystemVerilog subset — one parser and one style engine behind a
CLI (`vfmt`) and an LSP binary (`vfmt-server`).
CLI (`lucisv`) and an LSP binary (`lucisv-server`).
### Formatter and the safety net
@@ -366,7 +366,7 @@ and trailing trivia and are never dropped. **Every format is verified at
runtime**: the output is re-lexed and its token stream (comments included)
compared against the input, then formatted a second time and checked for a
fixed point; if either check fails the output is discarded and the file is
left byte-for-byte untouched. `// verilog_format: off` / `// vfmt: off` fences
left byte-for-byte untouched. `// verilog_format: off` / `// lucisv: off` fences
return the enclosed items as their exact source bytes, indentation included.
Deep nesting is a normal parse error with a position rather than a stack
overflow. Details: [formatter](docs/features/formatter-bug-fixes/README.md),
@@ -380,13 +380,13 @@ overflow. Details: [formatter](docs/features/formatter-bug-fixes/README.md),
### Command line
`vfmt <paths>` formats files and directories in place. `--check` and `--diff`
`lucisv <paths>` formats files and directories in place. `--check` and `--diff`
are the CI modes (exit 1 if anything would change, nothing written); `-` reads
stdin, with `--stdin-filename` naming the buffer. Directory walks honor
`.gitignore` (a documented subset) and repeatable `--exclude` patterns, and run
on all cores — `--threads N` pins the worker count without changing a single
output byte, since results are collected in input order. Settings live in a
`vfmt.toml` / `.vfmt.toml` discovered upward from each input, ruff-style, with
`lucisv.toml` / `.lucisv.toml` discovered upward from each input, ruff-style, with
CLI flags taking precedence per setting; an unknown key or a bad value is a
hard error naming the file and line. The exit-code contract (0 / 1 / 2) is
frozen and documented. A panic on one file cannot take down the run. Details:
@@ -396,14 +396,14 @@ frozen and documented. A panic on one file cannot take down the run. Details:
### Linter
`vfmt check` is a ruff-shaped linter over the same files, the same walk and the
`lucisv check` is a ruff-shaped linter over the same files, the same walk and the
same config discovery as the formatter: a rule registry, `--select` / `--ignore`,
`--output-format json`, and fixes classified safe or unsafe with `--fix`
applying only the safe ones. Eight syntactic rules ship — `no-tabs`,
`no-trailing-whitespace`, `case-missing-default`, `always-ff-non-blocking`,
`always-comb-blocking`, `explicit-parameter-storage-type`, `module-filename`
and `unused-waiver`. Inline waivers use Verible's spelling
(`// vfmt: waive <rule>`, `waive-start` / `waive-stop`, with `verilog_lint:`
(`// lucisv: waive <rule>`, `waive-start` / `waive-stop`, with `verilog_lint:`
accepted as an alias), so code already annotated for Verible lints unedited.
`check` runs on the error-tolerant parser, so a file the formatter refuses is
still linted for what can be read. Violations inside a format fence are
@@ -414,30 +414,30 @@ uses. Details: [linter](docs/features/linter-core/README.md),
### Language server
`vfmt-server` speaks LSP over stdio from a single binary and serves every
`lucisv-server` speaks LSP over stdio from a single binary and serves every
editor the same answers: `textDocument/formatting` (honoring the file's own
`vfmt.toml`, which wins over the editor's tab size), parse **errors** and lint
`lucisv.toml`, which wins over the editor's tab size), parse **errors** and lint
**warnings** in one diagnostic publish per change, `codeAction` quick fixes
plus `source.fixAll.vfmt` for fix-on-save, `semanticTokens/full`, hover
plus `source.fixAll.lucisv` for fix-on-save, `semanticTokens/full`, hover
(declaration snippets and `` `define`` expansion, in-file and across the
workspace), go-to-definition, in-file references, and document and workspace
symbols. Underneath it are a single-file semantic model (scopes, symbols,
references) and a workspace index that resolves names arriving through package
imports and module instantiations across files. Not yet advertised, and said so
out loud: range formatting, cross-file references, completion, rename and
signature help. Details: [server](docs/features/vfmt-server/README.md),
signature help. Details: [server](docs/features/lucisv-server/README.md),
[lint wiring](docs/features/server-lint/README.md),
[semantic model](docs/features/vlog-semantic/README.md),
[workspace index](docs/features/workspace-index/README.md),
[define table](docs/features/define-table/README.md),
[name spans](docs/features/name-spans/README.md),
[shared core](docs/features/vfmt-core-lift/README.md).
[shared core](docs/features/lucisv-core-lift/README.md).
### Editors
A thin VS Code extension in `editors/vscode/` registers the file types
(`.v`/`.vh` → `verilog`, `.sv`/`.svh` → `systemverilog`) and starts the server;
it has one setting, `vfmt.serverPath`, and no language logic of its own —
it has one setting, `lucisv.serverPath`, and no language logic of its own —
everything a user sees comes from the server. Install it by building the
`.vsix` and sideloading it (`tools/release.sh`, then
`code --install-extension`); publishing to a marketplace is optional and
@@ -450,10 +450,10 @@ Details: [editor packaging](docs/features/editor-packaging/README.md).
### Real-world corpus
vfmt is measured against an 820-file corpus of open-source RTL
lucisv is measured against an 820-file corpus of open-source RTL
(picorv32, ibex, common_cells, OpenTitan) rather than against its own fixtures
alone. At this release **476 of 820 files (58.0%) parse and format cleanly,
with zero verification errors and zero crashes** — every file vfmt cannot
with zero verification errors and zero crashes** — every file lucisv cannot
handle is a documented parse error, never a corrupted output. The remaining
gap is unsupported syntax, ranked by measured impact in `README.md`'s roadmap:
classes/constraints (the largest block, and mostly DV rather than RTL), `bind`,
+3 -3
View File
@@ -1,6 +1,6 @@
# CLAUDE.md — rules for all agents working on vfmt
# CLAUDE.md — rules for all agents working on lucisv
vfmt is a ruff-style Verilog/SystemVerilog formatter/linter in Rust.
lucisv is a ruff-style Verilog/SystemVerilog formatter/linter in Rust.
Read `README.md` for architecture and `TODO.md` for the backlog before
doing anything.
@@ -15,7 +15,7 @@ doing anything.
ships WITH masked-corruption attack tests (crafted (input, corrupted
output) pairs the normalization could plausibly forgive, asserted
rejected) — written by the dev, re-attacked by QA. History: the one
real corruption vfmt ever produced (macro-items, 2026-08-19) slipped
real corruption lucisv ever produced (macro-items, 2026-08-19) slipped
through a normalization added without such tests.
## Simplicity first
Generated
+31 -31
View File
@@ -95,6 +95,37 @@ dependencies = [
"serde_repr",
]
[[package]]
name = "lucisv"
version = "0.7.0"
dependencies = [
"lucisv_core",
"rayon",
"vlog_formatter",
"vlog_linter",
"vlog_parser",
]
[[package]]
name = "lucisv_core"
version = "0.7.0"
[[package]]
name = "lucisv_server"
version = "0.7.0"
dependencies = [
"lsp-server",
"lsp-types",
"lucisv_core",
"serde",
"serde_json",
"vlog_formatter",
"vlog_linter",
"vlog_parser",
"vlog_refactor",
"vlog_semantic",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -215,37 +246,6 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vfmt"
version = "0.7.0"
dependencies = [
"rayon",
"vfmt_core",
"vlog_formatter",
"vlog_linter",
"vlog_parser",
]
[[package]]
name = "vfmt_core"
version = "0.7.0"
[[package]]
name = "vfmt_server"
version = "0.7.0"
dependencies = [
"lsp-server",
"lsp-types",
"serde",
"serde_json",
"vfmt_core",
"vlog_formatter",
"vlog_linter",
"vlog_parser",
"vlog_refactor",
"vlog_semantic",
]
[[package]]
name = "vlog_formatter"
version = "0.7.0"
+6 -6
View File
@@ -6,9 +6,9 @@ members = [
"crates/vlog_refactor",
"crates/vlog_formatter",
"crates/vlog_linter",
"crates/vfmt_core",
"crates/vfmt",
"crates/vfmt_server",
"crates/lucisv_core",
"crates/lucisv",
"crates/lucisv_server",
]
[workspace.package]
@@ -18,19 +18,19 @@ edition = "2021"
license = "MIT"
# `rayon` is sanctioned by TODO.md §3 (parallel file processing) and used by
# `vfmt` only. Pinned exactly, because a work-stealing scheduler is exactly
# `lucisv` only. Pinned exactly, because a work-stealing scheduler is exactly
# the kind of dependency whose minor releases can change thread behavior;
# justification in docs/features/parallel-files/README.md.
[workspace.dependencies]
rayon = "=1.12.0"
# The LSP stack, sanctioned by TODO.md §6 ("`tower-lsp` or `lsp-server`"), used
# by `vfmt_server` only. `lsp-server` is rust-analyzer's synchronous transport
# by `lucisv_server` only. `lsp-server` is rust-analyzer's synchronous transport
# (no async runtime); `lsp-types` is the protocol's data model, which is not
# something to hand-roll. All pinned exactly for the same reason `rayon` is: a
# wire protocol's Rust bindings change shape between minor releases. Transitive
# count, build scripts and the versions considered are audited in
# docs/features/vfmt-server/README.md.
# docs/features/lucisv-server/README.md.
lsp-server = "=0.10.0"
# `proposed` is what carries LSP 3.18's `textDocument/inlineCompletion` — the
# params, the client/server capability. Nothing else in the feature is used,
+83 -81
View File
@@ -1,4 +1,6 @@
# vfmt — a Verilog/SystemVerilog formatter and linter in Rust
# lucisv — Language Utility for Coding In SystemVerilog
A Verilog/SystemVerilog formatter and linter in Rust.
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
@@ -7,48 +9,48 @@ layout conventions and lint ergonomics borrowed from
```bash
# format files / directories in place (like `ruff format`)
vfmt rtl/ tb/top_tb.sv
lucisv rtl/ tb/top_tb.sv
# lint (like `ruff check`); `vfmt format ...` is the explicit spelling of the above
vfmt check rtl/
# lint (like `ruff check`); `lucisv format ...` is the explicit spelling of the above
lucisv check rtl/
# check mode for CI (exit 1 if anything would change)
vfmt --check rtl/
lucisv --check rtl/
# print a unified diff instead of rewriting (also exit 1 if anything would change)
vfmt --diff rtl/
lucisv --diff rtl/
# format exactly what an EDA `.f` filelist names (repeatable, adds to the rest)
vfmt -f project.f
vfmt check -f project.f -f tb/tb.f rtl/extra.sv
lucisv -f project.f
lucisv check -f project.f -f tb/tb.f rtl/extra.sv
# skip generated files while walking directories (repeatable)
vfmt --exclude '*_gen.sv' --exclude build rtl/
lucisv --exclude '*_gen.sv' --exclude build rtl/
# .gitignore is honored while walking; --no-gitignore turns that off
vfmt --no-gitignore rtl/
lucisv --no-gitignore rtl/
# files are formatted on all cores; pin the worker count for reproducible CI
vfmt --threads 1 rtl/
lucisv --threads 1 rtl/
# repeat runs skip files that are already formatted; --no-cache turns that off
vfmt --check rtl/
vfmt --no-cache --check rtl/
lucisv --check rtl/
lucisv --no-cache --check rtl/
# format only the lines you edited, leaving the rest of the file byte-for-byte
vfmt --lines 120-134 rtl/alu.sv
vfmt --lines 3-9,40 --check rtl/alu.sv
lucisv --lines 120-134 rtl/alu.sv
lucisv --lines 3-9,40 --check rtl/alu.sv
# ...or derive the ranges from git, so only your patch gets formatted
tools/vfmt-changed.sh # everything not yet committed
tools/vfmt-changed.sh --check origin/main
tools/lucisv-changed.sh # everything not yet committed
tools/lucisv-changed.sh --check origin/main
# ignore any vfmt.toml found next to the input
vfmt --no-config rtl/
# ignore any lucisv.toml found next to the input
lucisv --no-config rtl/
# pipe through stdin/stdout; --stdin-filename names the buffer in messages
cat foo.sv | vfmt -
cat foo.sv | vfmt --stdin-filename rtl/foo.sv -
cat foo.sv | lucisv -
cat foo.sv | lucisv --stdin-filename rtl/foo.sv -
```
### Exit codes (frozen contract — CI may depend on it)
@@ -68,21 +70,21 @@ Files are formatted on a worker pool, one thread per logical CPU by default.
matters for reproducible CI timing and for bisecting; it never changes what is
produced. **The thread count does not affect output**: results are collected
and reported in input order, so stdout, stderr and the exit code are
byte-identical at any `N`, and `vfmt --diff` stays one clean patch in input
byte-identical at any `N`, and `lucisv --diff` stays one clean patch in input
order. stdin mode is single-threaded.
### Cache
vfmt remembers which files it has already verified are formatted, so a repeat
lucisv remembers which files it has already verified are formatted, so a repeat
run over an unchanged tree skips them: the summary says `N files from cache`,
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
thread count, where parallelism has already taken the easy win).
An entry is keyed on **(content hash, `line-length`, `indent`, vfmt version)**
An entry is keyed on **(content hash, `line-length`, `indent`, lucisv version)**
per file, and only ever records the *already formatted* verdict — a file that
would be reformatted, or that failed, is re-checked on every run, so
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
text file in `.vfmt_cache/` (self-ignoring, like cargo's `target/`); deleting
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
default is relative to the current directory). Content hashing is 64-bit
@@ -91,7 +93,7 @@ states the collision posture, the semantics table and the concurrency story.
### Ignore files
While walking a directory, vfmt reads a `.gitignore` in every directory it
While walking a directory, lucisv reads a `.gitignore` in every directory it
enters and skips what those rules name. A deeper `.gitignore` is applied after
(and so overrides) a shallower one, and within one file the last matching line
wins — git's own precedence. `--no-gitignore` switches this off. A path named
@@ -106,11 +108,11 @@ git's "already-tracked files are never ignored" rule. See
## Configuration
Settings live in a `vfmt.toml` (or `.vfmt.toml`) file, ruff-style. For each
input, vfmt searches **upward from that path's directory** for one:
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
input, lucisv searches **upward from that path's directory** for one:
1. `vfmt.toml` in the directory — used if present;
2. else `.vfmt.toml` in the directory;
1. `lucisv.toml` in the directory — used if present;
2. else `.lucisv.toml` in the directory;
3. else, if the directory contains `.git`, stop: no config (the `.git` check
comes *after* 1–2, so a config file in the repo root is still found);
4. else repeat in the parent directory, up to the filesystem root.
@@ -121,7 +123,7 @@ one run. For stdin, the search starts at `--stdin-filename`'s directory, or
the current directory if that flag is absent. `--no-config` skips all of this.
```toml
# vfmt.toml — every key is optional
# lucisv.toml — every key is optional
line-length = 100 # 40..400, same as --line-length
indent = 2 # 1..8, same as --indent
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
@@ -131,20 +133,20 @@ filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
`filelist` names the project's sources the way the rest of the EDA world
already does — one path per line, `-f` to nest another filelist, `+incdir+`,
`+define+`, `#`/`//` comments, `$VAR` expansion, paths relative to the
filelist that names them. This **key** is read by `vfmt-server` only, where it
filelist that names them. This **key** is read by `lucisv-server` only, where it
defines exactly which files are indexed ([Editor setup](#editor-setup)): a
`vfmt rtl/` that quietly formatted a filelist's files instead of `rtl/`'s would
`lucisv rtl/` that quietly formatted a filelist's files instead of `rtl/`'s would
be a surprise. On the command line a filelist is named explicitly, with `-f`:
```bash
vfmt -f project.f # format exactly the files it names
vfmt check -f project.f rtl/ # ...added to whatever else is named
lucisv -f project.f # format exactly the files it names
lucisv check -f project.f rtl/ # ...added to whatever else is named
```
The listed paths are taken exactly as written — neither `--exclude` nor
`.gitignore` filters them, just as neither filters a file named on the command
line — and a file named twice over is processed once. A listed file that has
gone missing, an option vfmt does not know and an unset `$VAR` are warnings on
gone missing, an option lucisv does not know and an unset `$VAR` are warnings on
stderr that change no exit code; a filelist that cannot be read at all is an
error (exit 2) and nothing is processed. Details:
`docs/features/filelist/README.md` and `docs/features/cli-filelist/README.md`.
@@ -160,21 +162,21 @@ a silently ignored `line_length` typo costs more than a strict parser does.
## Linting
`vfmt check` runs a set of lint rules over the same files `vfmt`
`lucisv check` runs a set of lint rules over the same files `lucisv`
would format — same walk, same `--exclude`, same `.gitignore` handling, same
`vfmt.toml` discovery.
`lucisv.toml` discovery.
```bash
vfmt check rtl/ # FILE:LINE:COL: message [rule-name]
vfmt check --output-format json rtl/ # one JSON array, for editors and CI
vfmt check --select no-tabs rtl/ # only these rules (comma-separated)
vfmt check --ignore module-filename rtl/ # everything but these
vfmt check --fix rtl/ # apply the safe fixes, write files back
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --fix rtl/ # apply the safe fixes, write files back
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file vfmt cannot fully parse is still linted for
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
@@ -209,15 +211,15 @@ so `--fix` leaves every byte of a fenced region exactly as written.
### Waivers
```systemverilog
wire a; // vfmt: waive no-tabs suppresses that rule on this line
// vfmt: waive no-tabs alone on a line: suppresses the next line
// vfmt: waive-start no-tabs ... and everything through
// vfmt: waive-stop no-tabs ... this line
wire a; // lucisv: waive no-tabs suppresses that rule on this line
// lucisv: waive no-tabs alone on a line: suppresses the next line
// lucisv: waive-start no-tabs ... and everything through
// lucisv: waive-stop no-tabs ... this line
```
`verilog_lint:` is accepted in place of `vfmt:`, so code annotated for Verible
works unedited — including waivers naming Verible rules vfmt has not
implemented, which are ignored rather than reported. A waiver of vfmt's own
`verilog_lint:` is accepted in place of `lucisv:`, so code annotated for Verible
works unedited — including waivers naming Verible rules lucisv has not
implemented, which are ignored rather than reported. A waiver of lucisv's own
that suppresses nothing, names an unknown rule or is malformed is reported
under `unused-waiver`. External waiver files are not supported. Full rules:
`docs/features/linter-core/README.md`.
@@ -233,7 +235,7 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules |
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
| `crates/vfmt` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
Key ideas carried over from ruff/prettier:
@@ -252,7 +254,7 @@ Key ideas carried over from ruff/prettier:
## Style
Defaults follow Verible: **2-space indent**, **100-column lines** (both
configurable via `--indent` / `--line-length` or a `vfmt.toml`, see
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
[Configuration](#configuration)).
- One port / parameter / connection per line once a header doesn't fit
@@ -264,7 +266,7 @@ configurable via `--indent` / `--line-length` or a `vfmt.toml`, see
### Alignment is inferred, not imposed
Hand-aligned columns are how RTL is read, so vfmt reads the spacing you
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
already wrote and keeps your intent — Verible's rule, without the knobs.
Within a run of adjacent ANSI **port declarations**, **named connections**
(`.clk (clk)`) or **`parameter`/`localparam` declarations**, four or more
@@ -274,7 +276,7 @@ element per line. Anything else formats flush-left with a single separator,
exactly as it always has, so a file written without alignment never grows any.
```systemverilog
// written with aligned columns, so vfmt leaves them aligned — at the width
// written with aligned columns, so lucisv leaves them aligned — at the width
// the group actually needs, which is what makes two people's tables agree
module m (
input wire clk,
@@ -298,7 +300,7 @@ both layouts are fixed points of re-formatting:
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// vfmt: off` / `// vfmt: on` is an accepted alias.
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
```systemverilog
module m;
@@ -311,7 +313,7 @@ endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// vfmt: off for now` is an ordinary comment, not a fence. An
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
@@ -325,9 +327,9 @@ adoption path for a legacy tree: your patch comes out formatted and nothing
else moves, so review sees the change rather than a reflow.
```bash
vfmt --lines 120-134 rtl/alu.sv # one range
vfmt --lines 3-9,40 rtl/alu.sv # several, comma-separated
vfmt --lines 3-9 --lines 40 rtl/alu.sv # the same, repeated
lucisv --lines 120-134 rtl/alu.sv # one range
lucisv --lines 3-9,40 rtl/alu.sv # several, comma-separated
lucisv --lines 3-9 --lines 40 rtl/alu.sv # the same, repeated
```
The unit is one **item**. An item whose lines meet a range — a declaration, an
@@ -342,7 +344,7 @@ wins over any range.
`--lines` needs explicit file arguments (or `-`), never a directory, and
neither reads nor writes the cache: a partly-formatted file is not the
"already formatted" verdict the cache stores. It combines with `--check`,
`--diff`, `--stdout` and stdin. `tools/vfmt-changed.sh` turns `git diff` hunks
`--diff`, `--stdout` and stdin. `tools/lucisv-changed.sh` turns `git diff` hunks
into ranges. Full semantics, including what happens at a range boundary:
`docs/features/range-formatting/README.md`.
@@ -581,37 +583,37 @@ corpus baseline this ordering comes from:
files and moved the parse rate from 97.1% to 97.6%. Every file still
failing is in a deliberately unsupported category, except
`compare_helper.sv`, whose `` `X_EACH_CSR 1 `` needs a macro body from
another file — vfmt does not preprocess, so it stays a parse error
another file — lucisv does not preprocess, so it stays a parse error
Like ruff, `vfmt` refuses to output anything for a file it cannot fully
Like ruff, `lucisv` refuses to output anything for a file it cannot fully
parse, so it can never corrupt code.
## Editor setup
`vfmt-server` is a language server: one binary, LSP over stdio, the same
`lucisv-server` is a language server: one binary, LSP over stdio, the same
answers in every editor. It ships formatting, diagnostics as you type, semantic
highlighting, hover (including single-step `` `define`` expansion),
go-to-definition, references and document/workspace symbols — the full list,
and what is deliberately *not* advertised yet, is in
`docs/features/vfmt-server/README.md`.
`docs/features/lucisv-server/README.md`.
**The binary comes from the same build as the CLI**, and nothing downloads it
for you:
```bash
cargo build --release # target/release/vfmt-server (and target/release/vfmt)
cp target/release/vfmt-server ~/.local/bin/ # anywhere on PATH
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
```
Every editor below defaults to finding `vfmt-server` on `PATH`; each also
Every editor below defaults to finding `lucisv-server` on `PATH`; each also
accepts an absolute path if you would rather leave the binary in `target/`.
**VS Code** — a thin extension in `editors/vscode/` whose entire job is
registering the file types and starting the server:
```bash
tools/release.sh # builds dist/vfmt-<version>.vsix
code --install-extension dist/vfmt-0.5.0.vsix
tools/release.sh # builds dist/lucisv-<version>.vsix
code --install-extension dist/lucisv-0.5.0.vsix
```
Sideloading that `.vsix` is the supported install; the extension is not on any
@@ -625,19 +627,19 @@ the F5 development flow and troubleshooting.
```lua
vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog' } })
vim.lsp.config('vfmt', {
cmd = { 'vfmt-server' },
vim.lsp.config('lucisv', {
cmd = { 'lucisv-server' },
filetypes = { 'verilog', 'systemverilog' },
root_markers = { 'vfmt.toml', '.vfmt.toml', '.git' },
root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },
})
vim.lsp.enable('vfmt')
vim.lsp.enable('lucisv')
```
`nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents:
`editors/nvim/README.md`.
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `vfmt.toml`, or the editor setting `vfmt.filelist`
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
files it names. Otherwise the workspace folder, walked as the CLI walks it;
and with no folder open at all, the current file's own directory. Open buffers
@@ -650,9 +652,9 @@ to the folder walk, so the index is never silently empty.
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
One caveat, stated up front: the server does **not** read `vfmt.toml` yet, so
One caveat, stated up front: the server does **not** read `lucisv.toml` yet, so
formatting through an editor uses the defaults (100 columns, 2-space indent)
with the editor's tab size overriding the indent. `vfmt` on the command line
with the editor's tab size overriding the indent. `lucisv` on the command line
does read it.
## Contributing / workflow
@@ -663,7 +665,7 @@ expected; no PRs or review required.
## Building
```bash
cargo build --release # binaries at target/release/{vfmt,vfmt-server}
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo test # unit + snapshot + idempotency tests
```
@@ -679,8 +681,8 @@ them for your platform and hands you the files.
tools/release.sh # release binaries + the .vsix + SHA256SUMS, into dist/
```
`dist/` then holds `vfmt-<version>-<host-triple>`,
`vfmt-server-<version>-<host-triple>`, `vfmt-<version>.vsix` and `SHA256SUMS`
`dist/` then holds `lucisv-<version>-<host-triple>`,
`lucisv-server-<version>-<host-triple>`, `lucisv-<version>.vsix` and `SHA256SUMS`
(verify with `cd dist && shasum -a 256 -c SHA256SUMS`). Copy the two binaries
onto your `PATH` and sideload the extension with `code --install-extension`.
The script builds for the host triple only and publishes nothing anywhere.
@@ -688,5 +690,5 @@ The script builds for the host triple only and publishes nothing anywhere.
Release notes are in [`CHANGELOG.md`](CHANGELOG.md); the full checklist —
where the version number lives, how the `.vsix` is packaged, and what
marketplace publishing would take if it ever happens — is in
[`tools/RELEASING.md`](tools/RELEASING.md). vfmt is MIT licensed
[`tools/RELEASING.md`](tools/RELEASING.md). lucisv is MIT licensed
([`LICENSE`](LICENSE)).
+1 -1
View File
@@ -71,7 +71,7 @@ Theoretical ceiling with every cluster done: ~797/820 (97.2%).
trailing comma in a connection list) — not valid standalone Verilog;
will never pass and should not.
- `compare_helper.sv` (`assign x = `MACRO 1;`) — needs the macro's
expansion; vfmt deliberately does not read `` `define`` bodies for
expansion; lucisv deliberately does not read `` `define`` bodies for
parsing. Confirmed by the expressions-2 dev, being re-confirmed by the
round-2 mop-up.
+35 -35
View File
@@ -1,6 +1,6 @@
# TODO — best practices adopted from ruff and Verible
Curated backlog for vfmt, drawn from `astral-sh/ruff` (architecture, CLI/UX,
Curated backlog for lucisv, drawn from `astral-sh/ruff` (architecture, CLI/UX,
fix model) and `chipsalliance/verible` (formatter safety, alignment,
waivers, and especially test methodology). Items reference the current
draft's files. Roughly ordered by priority within each section.
@@ -29,13 +29,13 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
(README notes it); extend the same contract to the two checks above.
- [x] **[R] Panic containment.** ruff catches panics per-file and reports
them as errors instead of killing the whole run. Wrap per-file work in
`crates/vfmt/src/main.rs` with `std::panic::catch_unwind`.
`crates/lucisv/src/main.rs` with `std::panic::catch_unwind`.
- [x] **`@(* )` fails to lex** (bug-fix QA find): `(*` followed by anything
but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare
space inside `@( * )`-style spellings errors out. Make the attribute
scan back off when the contents are just `*`.
→ `docs/features/lexer-cleanup/README.md`, with the BOM and non-ASCII
message fixes and the `vfmt check` lex-error silence fix.
message fixes and the `lucisv check` lex-error silence fix.
- [x] **Recursion-depth limit in the parser.** Found by cli-polish QA:
~150 levels of expression nesting overflow the stack and abort the whole
process — uncatchable by `catch_unwind`, so mid-batch files after the
@@ -54,7 +54,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
## 2. Formatter features
- [x] **[V] Format-off fences.** Support `// verilog_format: off` /
`// verilog_format: on` (accept a `vfmt: off/on` alias). Verible
`// verilog_format: on` (accept a `lucisv: off/on` alias). Verible
implements this as "emit the original byte range verbatim" — the trivia
in `Meta` already carries comments, so detect fences during formatting in
`format.rs` and splice source text by span. Requires nodes to carry
@@ -66,12 +66,12 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
constructs intersecting the given line ranges; emit everything else
verbatim. This is what makes adoption in dirty legacy codebases possible
(Verible ships `git-verible-verilog-format.sh` on top of it). Follow-up:
a `vfmt --diff-base <rev>` or contrib script that derives ranges from
a `lucisv --diff-base <rev>` or contrib script that derives ranges from
`git diff`.
→ `crates/vlog_formatter/src/range.rs` (`format_range`, `LineRanges`), the
CLI's `--lines`, the server's `documentRangeFormattingProvider`, and
`tools/vfmt-changed.sh` for the `git diff` half of the follow-up (a
`--diff-base` flag inside vfmt is still open). The unit is one item;
`tools/lucisv-changed.sh` for the `git diff` half of the follow-up (a
`--diff-base` flag inside lucisv is still open). The unit is one item;
modules and packages are descended into so a three-line edit does not
reflow a two-thousand-line body; statements and generate regions are
deliberately atomic. Fences outrank ranges, the cache is bypassed, and the
@@ -140,24 +140,24 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
## 3. CLI / UX (mostly ruff)
- [x] **[R] Config file discovery.** Search upward from each input file for
`vfmt.toml` / `.vfmt.toml` (analog of `ruff.toml` / `pyproject.toml`).
`lucisv.toml` / `.lucisv.toml` (analog of `ruff.toml` / `pyproject.toml`).
Keys: `line-length`, `indent`, `exclude` globs. CLI flags override file
config. Keep Verible's philosophy of *few* knobs — don't grow a
clang-format-sized option surface.
→ `crates/vfmt_core/src/config.rs` (lifted from crates/vfmt by vfmt-core-lift); discovery rule, TOML subset and
→ `crates/lucisv_core/src/config.rs` (lifted from crates/lucisv by lucisv-core-lift); discovery rule, TOML subset and
precedence in `docs/features/config-discovery/README.md`.
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
parallelism over files. `main.rs` formats serially; use `rayon`
par_iter over the collected file list (formatting is already pure).
→ `crates/vfmt/src/main.rs`; pool sizing (8 MiB worker stacks, per the
→ `crates/lucisv/src/main.rs`; pool sizing (8 MiB worker stacks, per the
recursion-limit handshake), the reworked panic hook and the
ordered-reporting determinism argument in
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
count; output is byte-identical at any count. 3.6× on 10 cores.
- [x] **[R] Content-hash cache.** Skip files whose (content hash, config
hash, vfmt version) triple is unchanged, stored in `.vfmt_cache/`.
hash, lucisv version) triple is unchanged, stored in `.lucisv_cache/`.
Do this *after* parallelism; it matters for big monorepo RTL trees.
→ `crates/vfmt_core/src/cache.rs` (`--no-cache`, `--cache-dir`); the key
→ `crates/lucisv_core/src/cache.rs` (`--no-cache`, `--cache-dir`); the key
stores the resolved `line-length`/`indent` *values*, and only the
"already formatted" verdict is ever cached — a would-reformat or an
error is re-checked every run, so `--check`/`--diff` cannot go stale.
@@ -171,7 +171,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
directories (`collect_files` in `main.rs` currently walks everything,
including e.g. generated netlists).
→ `--exclude` shipped with cli-polish; `.gitignore` is hand-rolled in
`crates/vfmt_core/src/walk.rs` (anchoring, directory-only, `!` negation,
`crates/lucisv_core/src/walk.rs` (anchoring, directory-only, `!` negation,
nested files override) with a `--no-gitignore` escape hatch. The
supported subset and everything git does that this does not are listed
in `docs/features/parallel-files/README.md`.
@@ -179,24 +179,24 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
1 would-reformat / 2 error) — document it in README and freeze it; CI
scripts will depend on it.
## 4. Linter (`vfmt check`) — new crate `vlog_linter`
## 4. Linter (`lucisv check`) — new crate `vlog_linter`
Design it ruff-style from day one (shared parse, fix model), with
Verible's rule ergonomics (waivers, configurable rules).
- [x] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must
share `vlog_parser` output in a single invocation (`vfmt check --fix
--format` style workflows come free later). ~~*Not done:* `vfmt check`
- [x] **[R] One parse, two tools.** `lucisv check` and `lucisv format` must
share `vlog_parser` output in a single invocation (`lucisv check --fix
--format` style workflows come free later). ~~*Not done:* `lucisv check`
re-parses today (tolerantly, which the formatter does not), and nothing in
`vlog_linter`'s API prevents sharing a tree later — only `LintContext` would
change.~~
→ Delivered on the linter side (`docs/features/one-parse/README.md`):
`LintContext::from_parse` accepts pre-built products, `ParsedSource` is the
owned bundle, `vfmt check` parses once per file (one lex instead of two —
corpus check 266 → 208 ms single-threaded), and `vfmt_server` lints from the
owned bundle, `lucisv check` parses once per file (one lex instead of two —
corpus check 266 → 208 ms single-threaded), and `lucisv_server` lints from the
`Document` it already analyzed (didChange→publish 18 → 11 ms on picorv32.v).
Byte-identical output proven against a HEAD-worktree binary. The formatter
half stands unchanged by design: `vfmt format` needs the *strict* parse its
half stands unchanged by design: `lucisv format` needs the *strict* parse its
safety net is defined over, so a combined `check --fix --format` workflow
remains a future feature — but nothing in the API blocks it anymore.
- [x] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name,
@@ -209,7 +209,7 @@ Verible's rule ergonomics (waivers, configurable rules).
grammar and the corpus baseline in `docs/features/linter-core/README.md`.
- [x] **[V] Diagnostic format `FILE:LINE:COL: message [rule-name]`** plus
**[R]** `--output-format json` for tooling from the start.
→ `vfmt check`; text sorted by file then position, JSON one array on stdout
→ `lucisv check`; text sorted by file then position, JSON one array on stdout
(hand-rolled, no new dependency) with location, end_location, range and fix.
- [x] **[R] Fix applicability model.** ruff distinguishes *safe* vs
*unsafe* fixes (`--fix` vs `--unsafe-fixes`). Adopt it now — retrofitting
@@ -217,13 +217,13 @@ Verible's rule ergonomics (waivers, configurable rules).
→ `Fix { edits, applicability: Safe | Unsafe }` and `--fix` /
`--unsafe-fixes`. Only `no-tabs` and `no-trailing-whitespace` ship fixes
(both Safe); the unsafe path is plumbed and tested but no rule uses it yet.
- [ ] **[V] Waiver mechanisms:** inline `// vfmt: waive rule-name` (accept
- [ ] **[V] Waiver mechanisms:** inline `// lucisv: waive rule-name` (accept
`verilog_lint: waive` for migration), `waive-start`/`waive-stop` ranges,
and external waiver files (`waive --rule=X --line=N --location=glob`) for
code you can't touch. ruff's lesson: also warn about *unused* waivers.
- [x] inline `waive`, `waive-start`/`waive-stop`, both spellings, and the
`unused-waiver` pseudo-rule (unused, unknown rule, malformed, unmatched
`waive-stop`). A `verilog_lint:` waiver naming a rule vfmt lacks is
`waive-stop`). A `verilog_lint:` waiver naming a rule lucisv lacks is
ignored rather than reported, so Verible-annotated code lints unedited.
- [ ] external waiver files — needs a file format, a discovery rule and a
precedence story against inline waivers.
@@ -237,15 +237,15 @@ Verible's rule ergonomics (waivers, configurable rules).
in `crates/vlog_linter/src/naming.rs`; the justification, the parked rules and
the corpus baseline are in `docs/features/lint-rules-2/README.md`.
*Not* done: making the style **configurable per rule** — that needs the
`lint` key in `vfmt.toml`, still open below.
`lint` key in `lucisv.toml`, still open below.
- [x] **[V] `--generate_markdown`-style self-documentation** — generate the
rule reference from the registry so docs can't drift. ruff does the same
for its 900+ rules.
→ `vlog_linter::rules_markdown() -> String` renders the whole registry (name,
default on/off, fix applicability, summary, doc), with a golden shape test
and an "every registered rule appears" test. Renderable today via
`cargo run -p vlog_linter --example rules_markdown`; a `vfmt check
--rules-doc` flag is filed as a handshake for `crates/vfmt`.
`cargo run -p vlog_linter --example rules_markdown`; a `lucisv check
--rules-doc` flag is filed as a handshake for `crates/lucisv`.
- [ ] Seed rules (all syntactic, all from Verible's default set):
no-tabs, no-trailing-spaces, explicit-parameter-storage-type,
case-missing-default, always-ff-non-blocking / always-comb-blocking,
@@ -314,7 +314,7 @@ Adapt each:
- [x] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff
CI runs against big OSS codebases and diffs results between commits. Do
the same with permissively-licensed RTL: e.g. lowRISC Ibex, OpenTitan,
PULP cores, picorv32. Script: clone pinned revs, run vfmt over every
PULP cores, picorv32. Script: clone pinned revs, run lucisv over every
`.sv/.v`, report parse-success rate + equivalence/convergence failures;
fail CI on regression. Also the honest tracker for the "not yet
supported" list in README.
@@ -389,7 +389,7 @@ Adapt each:
whose digits are a macro (`` 32'h`DM_ADDR ``) are done; the
`lex-macro-number` bucket is gone. `compare_helper.sv` stays failing
and is not fixable: `` `X_EACH_CSR 1 `` needs the macro's body, which
lives in a file vfmt deliberately does not read. `directive-split` (14
lives in a file lucisv deliberately does not read. `directive-split` (14
files) is still the top blocker, and every remaining failure is in a
deliberately-unsupported category.
- [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets:
@@ -401,7 +401,7 @@ Adapt each:
## 6. LSP: full editor support (a first-class goal, not a maybe)
Goal (owner's requirement, 2026-08-19): vfmt becomes a language server
Goal (owner's requirement, 2026-08-19): lucisv becomes a language server
for VS Code and Vim/Neovim with feature parity, for Verilog/
SystemVerilog, with what the Python VS Code stack (ruff + Pylance)
offers over LSP — scoped to **synthesizable Verilog first**:
@@ -486,7 +486,7 @@ later:
normalization (backslash-newline removed, nothing else touched) and the
gaps — no `` `ifdef`` evaluation, no cross-file `` `include`` — in
`docs/features/define-table/README.md`. Hover itself waits on
`vfmt_server`; this is only the table.
`lucisv_server`; this is only the table.
- [x] **Workspace index for cross-file navigation.** Map module/package/
typedef names → (file, span) across all workspace files, so header
imports (`import pkg::*;`) and instantiations resolve to definitions
@@ -519,7 +519,7 @@ later:
were already indexed); what moved is 6 more files that now format, and with
them external candidates answered 93.6 % → **94.0 %** on cleanly-parsed
files (unresolved-external rate 1.3 % → **1.2 %**).
- [x] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over
- [x] **New crate `lucisv_server`** (analog of `ruff_server`): LSP over
stdio via `tower-lsp` or `lsp-server`. Order of capabilities:
1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`),
2. publish parse/lint diagnostics,
@@ -528,7 +528,7 @@ later:
(needs `vlog_semantic` + workspace index),
5. document/workspace symbols; then completion, rename, signature
help for instantiations.
→ `crates/vfmt_server`, binary `vfmt-server`, on `lsp-server` +
→ `crates/lucisv_server`, binary `lucisv-server`, on `lsp-server` +
`lsp-types` (synchronous, no async runtime). **Shipped:**
`textDocument/formatting`, `textDocument/rangeFormatting` (round 18, on §2's
`--lines`), parse diagnostics on didOpen/didChange/didSave,
@@ -540,12 +540,12 @@ later:
`vlog_linter`) **delivered**, cross-file references,
completion/rename/signature help. Byte↔UTF-16
position conversion, the state/staleness model and the dependency audit
are in `docs/features/vfmt-server/README.md`.
are in `docs/features/lucisv-server/README.md`.
- [x] **Editor packaging.** A minimal VS Code extension (launch the
server, register file types) and a documented Vim/Neovim `lspconfig`
snippet. No editor-specific features beyond launching.
→ `editors/vscode/` (41-line plain-JS `extension.js` on the official
`vscode-languageclient`, pinned `9.0.1`; one setting, `vfmt.serverPath`;
`vscode-languageclient`, pinned `9.0.1`; one setting, `lucisv.serverPath`;
`.v`/`.vh`→`verilog`, `.sv`/`.svh`→`systemverilog`; no grammar — semantic
tokens come from the server; no commands, no status bar) and
`editors/nvim/README.md` (`vim.lsp.config` for Neovim 0.11+, plus
@@ -620,7 +620,7 @@ section only tracks the milestones.
instantiates X / what X instantiates) over LSP callHierarchy.
- [x] **M12 `semantic-lints`** — unused-signal, undriven-net,
multiply-driven: the first semantic lint rules on `vlog_semantic`.
- [x] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line,
- [x] **M13 `cli-filelist`** — `lucisv -f files.f` on the command line,
reusing M1's parser; format/lint exactly the project's files.
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
(the define-table README's promised follow-up); version 0.5.0 with a
@@ -1,16 +1,16 @@
[package]
name = "vfmt"
name = "lucisv"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "A Verilog/SystemVerilog formatter, in the spirit of ruff"
[[bin]]
name = "vfmt"
name = "lucisv"
path = "src/main.rs"
[dependencies]
vfmt_core = { path = "../vfmt_core" }
lucisv_core = { path = "../lucisv_core" }
vlog_parser = { path = "../vlog_parser" }
vlog_formatter = { path = "../vlog_formatter" }
vlog_linter = { path = "../vlog_linter" }
@@ -1,24 +1,24 @@
//! Hand-rolled command line parsing for the `vfmt` binary.
//! Hand-rolled command line parsing for the `lucisv` binary.
use vfmt_core::cache;
use vfmt_core::config::FileConfig;
use lucisv_core::cache;
use lucisv_core::config::FileConfig;
use vlog_formatter::{Config, LineRanges};
/// Which tool this invocation runs.
///
/// A bare `vfmt <paths>` is [`Command::Format`], exactly as before
/// A bare `lucisv <paths>` is [`Command::Format`], exactly as before
/// subcommands existed; the word is only read when it is the **first**
/// argument, so `vfmt --check rtl/` and every other old command line means
/// argument, so `lucisv --check rtl/` and every other old command line means
/// what it always did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
/// `vfmt`, `vfmt format` — the formatter.
/// `lucisv`, `lucisv format` — the formatter.
Format,
/// `vfmt check` — the linter.
/// `lucisv check` — the linter.
Check,
}
/// How `vfmt check` renders its diagnostics.
/// How `lucisv check` renders its diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
/// `FILE:LINE:COL: message [rule-name]`, one per line.
@@ -37,13 +37,13 @@ pub struct Options {
pub diff: bool,
/// Print formatted output instead of rewriting files.
pub stdout: bool,
/// Ignore `vfmt.toml` / `.vfmt.toml` files entirely.
/// Ignore `lucisv.toml` / `.lucisv.toml` files entirely.
pub no_config: bool,
/// Ignore `.gitignore` files while walking directories.
pub no_gitignore: bool,
/// Neither read nor write the "already formatted" cache.
pub no_cache: bool,
/// Where that cache lives; `None` means `.vfmt_cache` in the current
/// Where that cache lives; `None` means `.lucisv_cache` in the current
/// directory.
pub cache_dir: Option<String>,
/// `--threads`: worker count for the file pool. `None` or `Some(0)`
@@ -132,18 +132,18 @@ impl Options {
/// Prints the `--help` text, including the frozen exit-code contract.
pub fn print_help() {
println!(
"vfmt — a Verilog/SystemVerilog formatter and linter
"lucisv — a Verilog/SystemVerilog formatter and linter
USAGE:
vfmt [OPTIONS] <file|dir>... format files in place
vfmt format [OPTIONS] <file|dir>... the same, spelled out
vfmt check [OPTIONS] <file|dir>... lint files
vfmt [OPTIONS] -f <filelist> format what an EDA .f filelist names
vfmt - read from stdin, write to stdout
lucisv [OPTIONS] <file|dir>... format files in place
lucisv format [OPTIONS] <file|dir>... the same, spelled out
lucisv check [OPTIONS] <file|dir>... lint files
lucisv [OPTIONS] -f <filelist> format what an EDA .f filelist names
lucisv - read from stdin, write to stdout
A subcommand is only recognized as the *first* argument, so every command
line that worked before subcommands existed still formats. To format a
file actually named `check`, write `vfmt format check` or `./check`.
file actually named `check`, write `lucisv format check` or `./check`.
OPTIONS:
--check don't write; exit 1 if any file would be reformatted
@@ -159,7 +159,7 @@ OPTIONS:
taken exactly as written — neither --exclude nor
.gitignore filters them, just as neither filters a
file named on the command line. A listed file that
is missing, an option vfmt does not know and an
is missing, an option lucisv does not know and an
unset $VAR are warnings on stderr and change no
exit code; a filelist that cannot be read at all
is an error and nothing is processed
@@ -167,8 +167,8 @@ OPTIONS:
also the directory config discovery starts from
--no-gitignore don't read .gitignore files while walking directories
--no-cache don't read or write the \"already formatted\" cache
--cache-dir <PATH> where that cache lives (default: .vfmt_cache in the
current directory). `vfmt check` accepts both flags
--cache-dir <PATH> where that cache lives (default: .lucisv_cache in the
current directory). `lucisv check` accepts both flags
and ignores them: linting is not cached
--threads <N> worker threads used to format files (default: one per
logical CPU). `--threads 1` formats on a single worker;
@@ -181,11 +181,11 @@ 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)
--no-config ignore vfmt.toml / .vfmt.toml files
--no-config ignore lucisv.toml / .lucisv.toml files
-h, --help show this help
-V, --version show version
CHECK OPTIONS (`vfmt check` only):
CHECK OPTIONS (`lucisv check` only):
--select <RULES> run only these rules (comma-separated, repeatable)
--ignore <RULES> drop these rules from the set that would run
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
@@ -194,14 +194,14 @@ CHECK OPTIONS (`vfmt check` only):
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
Suppress a finding with a comment: `// vfmt: waive <rule>` on the line
itself or on the line above it, or a `// vfmt: waive-start <rule>` /
`// vfmt: waive-stop <rule>` pair around a region. `verilog_lint:` is
accepted in place of `vfmt:`. A waiver that suppresses nothing is
Suppress a finding with a comment: `// lucisv: waive <rule>` on the line
itself or on the line above it, or a `// lucisv: waive-start <rule>` /
`// lucisv: waive-stop <rule>` pair around a region. `verilog_lint:` is
accepted in place of `lucisv:`. A waiver that suppresses nothing is
reported under the `unused-waiver` rule.
IGNORE FILES:
While walking a directory, vfmt reads a `.gitignore` in every directory it
While walking a directory, lucisv reads a `.gitignore` in every directory it
enters and skips what it names; a deeper file overrides a shallower one and
the last matching line wins. Supported: `#` comments, `*` inside one path
component, a leading or embedded `/` (anchors to that .gitignore's own
@@ -213,27 +213,27 @@ FILELISTS:
`-f project.f` reads the EDA filelist every Verilog build already has: one
source path per line, resolved against the directory of the filelist naming
it, plus `-f other.f` to nest another, `+incdir+`/`+define+` (accepted and
ignored — vfmt does not preprocess), `$VAR`/`${{VAR}}` expansion, and `//` or
ignored — lucisv does not preprocess), `$VAR`/`${{VAR}}` expansion, and `//` or
`#` comments. The files it names are added to whatever the command line
already names, in that order, and a file named twice over is processed once.
Paths containing whitespace cannot be listed: there is no quoting.
CACHE:
A file whose exact content vfmt has already verified is formatted — under
the same line-length, indent and vfmt version — is skipped on the next run
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
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 `.vfmt_cache/`;
is re-checked every run. The cache is one text file under `.lucisv_cache/`;
deleting it, or a corrupt one, costs a slow run and nothing else.
CONFIGURATION:
For each input, vfmt searches upward from its directory for `vfmt.toml`
or `.vfmt.toml` (the first found wins; the search also stops at a
For each input, lucisv searches upward from its directory for `lucisv.toml`
or `.lucisv.toml` (the first found wins; the search also stops at a
directory containing `.git`, after checking it). Recognized keys, all
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
read by vfmt-server only — the CLI reads a filelist only when `-f` names
one, so `vfmt rtl/` always means the directory it was given). A command
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). A command
line flag overrides the file.
RANGE FORMATTING:
@@ -365,7 +365,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
std::process::exit(0);
}
"-V" | "--version" => {
println!("vfmt {}", env!("CARGO_PKG_VERSION"));
println!("lucisv {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
}
"-" => opts.inputs.push("-".to_string()),
@@ -376,7 +376,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
if opts.inputs.is_empty() && opts.filelists.is_empty() {
return Err("no input files (try `vfmt --help`)".to_string());
return Err("no input files (try `lucisv --help`)".to_string());
}
// Repeating the flag is the same as one comma-separated list; both spell
// "these lines", and the ranges are merged either way.
@@ -409,7 +409,7 @@ fn split_rules(value: &str) -> Vec<String> {
}
/// Rejects a flag used with the wrong subcommand. A quiet no-op would be the
/// worse outcome: `vfmt check --diff` looking like it worked, having linted
/// worse outcome: `lucisv check --diff` looking like it worked, having linted
/// nothing.
fn check_flag_scopes(opts: &Options) -> Result<(), String> {
let lint_only = [
@@ -429,14 +429,14 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
Command::Format => {
for (given, flag) in lint_only {
if given {
return Err(format!("{flag} is only valid for `vfmt check`"));
return Err(format!("{flag} is only valid for `lucisv check`"));
}
}
}
Command::Check => {
for (given, flag) in format_only {
if given {
return Err(format!("{flag} is not valid for `vfmt check`"));
return Err(format!("{flag} is not valid for `lucisv check`"));
}
}
if opts.unsafe_fixes && !opts.fix {
@@ -521,7 +521,7 @@ mod tests {
fn the_cache_is_on_unless_switched_off() {
let opts = parse(&["rtl"]).unwrap();
assert!(opts.cache_enabled());
assert_eq!(opts.cache_dir(), ".vfmt_cache");
assert_eq!(opts.cache_dir(), ".lucisv_cache");
assert!(!parse(&["--no-cache", "rtl"]).unwrap().cache_enabled());
// `--stdout` has to print every file, so nothing may be skipped.
File renamed without changes.
@@ -1,4 +1,4 @@
//! The `vfmt check` driver: lint files, print diagnostics, apply fixes.
//! The `lucisv check` driver: lint files, print diagnostics, apply fixes.
//!
//! Everything about *which* files are linted — the walk, `--exclude`,
//! `.gitignore`, config discovery — is the formatter's, unchanged: `check`
@@ -107,7 +107,7 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
// A file that does not lex still gets its text-level findings — those
// rules ran — but every token- and AST-level rule silently saw nothing,
// so the file must not pass as checked. It is an error (exit 2), exactly
// as `vfmt format` treats the same file.
// as `lucisv format` treats the same file.
let error = lex_error.map(|e| format!("{path}: {e}"));
Report { path, index, violations, fixed, error }
}
@@ -126,7 +126,7 @@ fn run_rules(
// lent to the context. Under `--fix` each *round* re-enters through this
// function with rewritten text — that re-parse is inherent (the old
// products describe text that no longer exists), so only the first round
// saves a parse; a plain `vfmt check` always does.
// saves a parse; a plain `lucisv check` always does.
let parsed = ParsedSource::parse(src);
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
// The indent width the formatter would use is also the width a tab
@@ -140,7 +140,7 @@ fn run_rules(
///
/// `off` means hands-off across both tools. The formatter emits a fenced
/// region as the exact source bytes it was written with; a linter that
/// rewrote those same bytes would make the fence a promise only half of vfmt
/// rewrote those same bytes would make the fence a promise only half of lucisv
/// keeps. The violation is still **reported** — a finding is information, and
/// silencing it is what waivers are for — it just loses its automatic fix.
///
@@ -383,7 +383,7 @@ mod tests {
#[test]
fn fixes_outside_a_fence_survive_the_filter() {
// Line 2 is fenced, line 4 is not; both have a tab worth fixing.
let text = "module m;\n// vfmt: off\n\ta = 1;\n// vfmt: on\n\tb = 2;\nendmodule\n";
let text = "module m;\n// lucisv: off\n\ta = 1;\n// lucisv: on\n\tb = 2;\nendmodule\n";
let fenced = text.find("\ta = 1").unwrap_or(0) as u32;
let free = text.find("\tb = 2").unwrap_or(0) as u32;
let violations = vec![
@@ -418,14 +418,14 @@ mod tests {
// Error recovery can swallow the structure `fence::collect` hangs a
// region on; the union's scan half still finds it. Owned by
// `fence::protected_regions` now — this is the CLI end of it.
let text = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
let text = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\n// lucisv: on\nendmodule\n";
let tab = text.find("\ta = 1").unwrap_or(0);
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
}
#[test]
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
let text = "module m;\n// vfmt: off\n\ta = 1;\nendmodule\n";
let text = "module m;\n// lucisv: off\n\ta = 1;\nendmodule\n";
let tab = text.find("\ta = 1").unwrap_or(0);
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
}
@@ -433,10 +433,10 @@ mod tests {
#[test]
fn an_ordinary_comment_is_not_a_fence() {
for text in [
"module m;\n// vfmt: off-by-one\n\ta = 1;\nendmodule\n",
"module m;\n// lucisv: off-by-one\n\ta = 1;\nendmodule\n",
"module m;\n// just a note\n\ta = 1;\nendmodule\n",
// A stray `on` opens nothing.
"module m;\n// vfmt: on\n\ta = 1;\nendmodule\n",
"module m;\n// lucisv: on\n\ta = 1;\nendmodule\n",
] {
let tab = text.find("\ta = 1").unwrap_or(0);
assert_eq!(fixable_outside_fences(text, &tab_violation(tab)).len(), 1, "{text:?}");
@@ -1,13 +1,13 @@
//! vfmt — a Verilog/SystemVerilog formatter and linter in the spirit of
//! lucisv — a Verilog/SystemVerilog formatter and linter in the spirit of
//! `ruff format` and `ruff check`.
//!
//! Usage:
//! vfmt [OPTIONS] <file|dir>... format files in place
//! vfmt --check <file|dir>... exit 1 if anything would change
//! vfmt --diff <file|dir>... print a unified diff of what would change
//! vfmt check <file|dir>... lint files (exit 1 if anything is found)
//! vfmt -f files.f format what an EDA `.f` filelist names
//! vfmt - read stdin, write stdout
//! lucisv [OPTIONS] <file|dir>... format files in place
//! lucisv --check <file|dir>... exit 1 if anything would change
//! lucisv --diff <file|dir>... print a unified diff of what would change
//! lucisv check <file|dir>... lint files (exit 1 if anything is found)
//! lucisv -f files.f format what an EDA `.f` filelist names
//! lucisv - read stdin, write stdout
//!
//! Exit codes: 0 nothing to do, 1 `--check`/`--diff` found changes or `check`
//! found violations, 2 an error occurred (the affected files are left
@@ -27,10 +27,10 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use vfmt_core::cache::{content_hash, Cache, Entry};
use vfmt_core::config::Discovery;
use vfmt_core::filelist;
use vfmt_core::walk::{collect_files, EXTENSIONS};
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::Discovery;
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
@@ -57,7 +57,7 @@ fn main() -> ExitCode {
}
}
/// `vfmt check`: the linter over the same file set the formatter would take.
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
Ok(rules) => rules,
@@ -195,7 +195,7 @@ struct FileResult {
outcome: Outcome,
/// Hash of content verified to be already formatted. `None` for every
/// other verdict: a would-reformat or an error is never cached,
/// because the fix for both is outside vfmt.
/// because the fix for both is outside lucisv.
clean: Option<u64>,
}
@@ -266,7 +266,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
/// The cache entry for content formatted under `config`. The *values* are
/// the key, not the config file that produced them, so identical settings
/// from different `vfmt.toml` files share entries.
/// from different `lucisv.toml` files share entries.
fn entry_for(content: u64, config: &Config) -> Entry {
Entry { content, line_length: config.max_width, indent: config.indent_width }
}
@@ -320,7 +320,7 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
/// Every file the `-f` filelists name, in flag order then list order.
///
/// The one place `gather` speaks to the user: a filelist's warnings — a
/// listed file that is gone, an option vfmt does not know, an unset `$VAR`,
/// listed file that is gone, an option lucisv does not know, an unset `$VAR`,
/// a `-f` chain nested too deep — have to be said even though the run
/// succeeds, so they go to stderr and change no exit code. Only the filelist
/// itself being unreadable is an error, and it aborts the run here, before
@@ -348,9 +348,9 @@ fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `vfmt_core`'s own normalization: symlinks are
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path vfmt reports.
/// the path lucisv reports.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -421,12 +421,12 @@ fn format_contained(
thread_local! {
/// True while this thread is inside `catch_panic`, which is how the
/// panic hook knows to keep quiet: vfmt reports contained panics
/// panic hook knows to keep quiet: lucisv reports contained panics
/// itself, in its own error style.
static CONTAINED: Cell<bool> = const { Cell::new(false) };
}
/// Installs vfmt's panic hook. Called once at startup, before any worker
/// Installs lucisv's panic hook. Called once at startup, before any worker
/// thread exists, because swapping the process-global hook per call would
/// race once files are formatted in parallel. A panic outside
/// `catch_panic` — a real bug in the driver — still reaches the default
@@ -1,4 +1,4 @@
//! End-to-end tests that drive the real `vfmt` binary.
//! End-to-end tests that drive the real `lucisv` binary.
//!
//! Fixtures use the most trivial Verilog possible so these tests stay
//! stable while the formatter's layout rules evolve.
@@ -8,7 +8,7 @@ use std::path::PathBuf;
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
const VFMT: &str = env!("CARGO_BIN_EXE_vfmt");
const LUCISV: &str = env!("CARGO_BIN_EXE_lucisv");
/// Formats to `FORMATTED`: the only change is the newline before `endmodule`.
const UNFORMATTED: &str = "module m;endmodule\n";
const FORMATTED: &str = "module m;\nendmodule\n";
@@ -31,7 +31,8 @@ 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!("vfmt-cli-{}-{tag}-{n}", std::process::id()));
let path =
std::env::temp_dir().join(format!("lucisv-cli-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
@@ -61,9 +62,9 @@ impl Drop for TempDir {
}
}
/// Runs vfmt with the cache switched off. Every test here shares one
/// Runs lucisv with the cache switched off. Every test here shares one
/// working directory (the crate's), so a default-on cache would put a
/// `.vfmt_cache/` in the source tree *and* let one test's run change what
/// `.lucisv_cache/` in the source tree *and* let one test's run change what
/// another observes. The cache tests opt back in with `run_raw` and their
/// own `--cache-dir`.
fn run(args: &[&str]) -> Output {
@@ -80,27 +81,27 @@ fn with_no_cache<'a>(args: &[&'a str]) -> Vec<&'a str> {
args
}
/// Runs vfmt exactly as given, cache and all.
/// Runs lucisv exactly as given, cache and all.
fn run_raw(args: &[&str]) -> Output {
Command::new(VFMT).args(args).output().expect("run vfmt")
Command::new(LUCISV).args(args).output().expect("run lucisv")
}
/// Runs vfmt exactly as given, from `dir` — the cache's default location
/// Runs lucisv exactly as given, from `dir` — the cache's default location
/// is relative to the working directory.
fn run_in(dir: &TempDir, args: &[&str]) -> Output {
Command::new(VFMT).args(args).current_dir(&dir.path).output().expect("run vfmt")
Command::new(LUCISV).args(args).current_dir(&dir.path).output().expect("run lucisv")
}
fn run_with_stdin(args: &[&str], input: &str) -> Output {
let mut child = Command::new(VFMT)
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn vfmt");
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
child.wait_with_output().expect("run vfmt")
child.wait_with_output().expect("run lucisv")
}
fn code(out: &Output) -> i32 {
@@ -427,9 +428,9 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("sub/vfmt.toml", "indent = 8\n");
dir.write("sub/deeper/vfmt.toml", "indent = 2\n");
dir.write("lucisv.toml", "indent = 4\n");
dir.write("sub/lucisv.toml", "indent = 8\n");
dir.write("sub/deeper/lucisv.toml", "indent = 2\n");
for n in 0..12 {
dir.write(&format!("root{n:02}.sv"), UNINDENTED);
dir.write(&format!("sub/mid{n:02}.sv"), UNINDENTED);
@@ -550,7 +551,7 @@ fn help_documents_the_exit_codes() {
#[test]
fn a_config_file_is_found_by_searching_upward() {
let dir = TempDir::new("configup");
dir.write("vfmt.toml", "indent = 4\nline-length = 40\n");
dir.write("lucisv.toml", "indent = 4\nline-length = 40\n");
dir.write("a/b/x.sv", UNINDENTED);
dir.write("a/b/wide.sv", WIDE);
@@ -562,9 +563,9 @@ fn a_config_file_is_found_by_searching_upward() {
dir.read("a/b/wide.sv"),
"module m (\n input wire aaaa,\n input wire bbbb\n);\nendmodule\n"
);
// Both names work; `.vfmt.toml` is the fallback within one directory.
// Both names work; `.lucisv.toml` is the fallback within one directory.
dir.write("a/b/x.sv", UNINDENTED);
std::fs::rename(dir.path.join("vfmt.toml"), dir.path.join(".vfmt.toml")).expect("rename");
std::fs::rename(dir.path.join("lucisv.toml"), dir.path.join(".lucisv.toml")).expect("rename");
assert_eq!(code(&run(&[&dir.root()])), 0);
assert_eq!(dir.read("a/b/x.sv"), INDENT_4);
}
@@ -572,9 +573,9 @@ fn a_config_file_is_found_by_searching_upward() {
#[test]
fn each_file_gets_the_config_of_its_own_directory() {
let dir = TempDir::new("configper");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("lucisv.toml", "indent = 4\n");
dir.write("root.sv", UNINDENTED);
dir.write("sub/vfmt.toml", "indent = 8\n");
dir.write("sub/lucisv.toml", "indent = 8\n");
dir.write("sub/deep/inner.sv", UNINDENTED);
dir.write("other/plain.sv", UNINDENTED);
@@ -594,7 +595,7 @@ fn each_file_gets_the_config_of_its_own_directory() {
#[test]
fn a_cli_flag_overrides_the_config_file() {
let dir = TempDir::new("configcli");
dir.write("vfmt.toml", "indent = 4\nline-length = 40\n");
dir.write("lucisv.toml", "indent = 4\nline-length = 40\n");
dir.write("x.sv", UNINDENTED);
dir.write("wide.sv", WIDE);
@@ -608,7 +609,7 @@ fn a_cli_flag_overrides_the_config_file() {
fn no_config_ignores_config_files_entirely() {
let dir = TempDir::new("noconfig");
// Not even parsed: --no-config reads nothing from disk.
dir.write("vfmt.toml", "this file is not valid at all\n");
dir.write("lucisv.toml", "this file is not valid at all\n");
dir.write("x.sv", UNINDENTED);
let out = run(&["--no-config", &dir.root()]);
@@ -619,23 +620,23 @@ fn no_config_ignores_config_files_entirely() {
#[test]
fn a_broken_config_exits_2_before_writing_anything() {
let dir = TempDir::new("configbad");
dir.write("vfmt.toml", "indent = 4\nline_length = 80\n");
dir.write("lucisv.toml", "indent = 4\nline_length = 80\n");
dir.write("x.sv", UNINDENTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 2, "a config error is an error, not a warning");
assert_eq!(dir.read("x.sv"), UNINDENTED, "nothing is written when the config is broken");
let err = stderr(&out);
assert!(err.contains("vfmt.toml:2:"), "the error names the file and line: {err}");
assert!(err.contains("lucisv.toml:2:"), "the error names the file and line: {err}");
assert!(err.contains("unknown key `line_length`"), "{err}");
for (contents, expected) in [
("indent = 99\n", "between 1 and 8"),
("line-length = wide\n", "expects an integer"),
("[tool.vfmt]\nindent = 2\n", "tables"),
("[tool.lucisv]\nindent = 2\n", "tables"),
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
] {
dir.write("vfmt.toml", contents);
dir.write("lucisv.toml", contents);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 2, "{contents}");
assert!(stderr(&out).contains(expected), "{contents}: {}", stderr(&out));
@@ -646,7 +647,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
#[test]
fn config_excludes_are_added_to_cli_excludes() {
let dir = TempDir::new("configexclude");
dir.write("vfmt.toml", "exclude = [ \"*_gen.sv\", \"build\" ] # generated\n");
dir.write("lucisv.toml", "exclude = [ \"*_gen.sv\", \"build\" ] # generated\n");
dir.write("keep.sv", UNINDENTED);
dir.write("skip_gen.sv", UNINDENTED);
dir.write("build/inner.sv", UNINDENTED);
@@ -663,7 +664,7 @@ fn config_excludes_are_added_to_cli_excludes() {
#[test]
fn stdin_discovers_config_from_stdin_filename() {
let dir = TempDir::new("configstdin");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("lucisv.toml", "indent = 4\n");
let buffer = format!("{}/rtl/buffer.sv", dir.root());
let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED);
@@ -681,7 +682,7 @@ fn stdin_discovers_config_from_stdin_filename() {
assert_eq!(stdout(&out), INDENT_2, "--no-config applies to stdin too");
// A broken config is an error in stdin mode too, and nothing is echoed.
dir.write("vfmt.toml", "indent = 4\nbogus = 1\n");
dir.write("lucisv.toml", "indent = 4\nbogus = 1\n");
let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED);
assert_eq!(code(&out), 2);
assert_eq!(stdout(&out), "", "no output when the config is broken");
@@ -691,7 +692,7 @@ fn stdin_discovers_config_from_stdin_filename() {
#[test]
fn the_search_stops_at_a_git_directory_after_checking_it() {
let dir = TempDir::new("configgit");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("lucisv.toml", "indent = 4\n");
std::fs::create_dir_all(dir.path.join("repo/.git")).expect("create .git");
dir.write("repo/rtl/x.sv", UNINDENTED);
@@ -702,13 +703,13 @@ fn the_search_stops_at_a_git_directory_after_checking_it() {
// A config file *in* the repo root is still found: `.git` only stops
// the walk after its own directory has been checked.
dir.write("repo/rtl/x.sv", UNINDENTED);
dir.write("repo/vfmt.toml", "indent = 8\n");
dir.write("repo/lucisv.toml", "indent = 8\n");
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("repo/rtl/x.sv"), "module m;\n wire x;\nendmodule\n");
}
// -------------------------------------------------------------- vfmt check
// -------------------------------------------------------------- lucisv check
/// Two findings: a tab on line 2 and a module/file-name mismatch.
const LINTY: &str = "module foo;\n\twire a;\nendmodule\n";
@@ -868,7 +869,7 @@ fn check_select_and_ignore_pick_the_rule_set() {
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
let path = dir.write("foo.sv", "module foo;\n\twire a; // vfmt: waive no-tabs\nendmodule\n");
let path = dir.write("foo.sv", "module foo;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
let out = run(&["check", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
@@ -912,7 +913,7 @@ fn check_reuses_the_walk_and_its_exclusions() {
#[test]
fn check_expands_tabs_to_the_configured_indent() {
let dir = TempDir::new("check-indent");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("lucisv.toml", "indent = 4\n");
let path = dir.write("foo.sv", "module foo;\n\twire a;\nendmodule\n");
let out = run(&["check", "--fix", &path]);
@@ -990,24 +991,24 @@ fn flags_of_the_other_tool_are_rejected() {
] {
let out = run(&args);
assert_eq!(code(&out), 2, "{args:?} must not be accepted by the formatter");
assert!(stderr(&out).contains("only valid for `vfmt check`"), "{}", stderr(&out));
assert!(stderr(&out).contains("only valid for `lucisv check`"), "{}", stderr(&out));
}
for flag in ["--check", "--diff", "--stdout"] {
let out = run(&["check", flag, &path]);
assert_eq!(code(&out), 2, "{flag} must not be accepted by the linter");
assert!(stderr(&out).contains("not valid for `vfmt check`"), "{}", stderr(&out));
assert!(stderr(&out).contains("not valid for `lucisv check`"), "{}", stderr(&out));
}
let out = run(&["check", "--unsafe-fixes", &path]);
assert_eq!(code(&out), 2, "--unsafe-fixes without --fix is a mistake");
}
/// A fenced region (tab + trailing whitespace, deliberately hand-aligned) and
/// an unfenced one with the same problems. `vfmt format` emits the fenced
/// bytes verbatim; `vfmt check --fix` must do the same.
/// an unfenced one with the same problems. `lucisv format` emits the fenced
/// bytes verbatim; `lucisv check --fix` must do the same.
const FENCED: &str = "module foo;\n\
// vfmt: off\n\
// lucisv: off\n\
\tlocalparam int A = 1; \n\
// vfmt: on\n\
// lucisv: on\n\
\tlocalparam int B = 2; \n\
endmodule\n";
@@ -1043,7 +1044,7 @@ fn check_reports_inside_a_fence_but_never_fixes_there() {
#[test]
fn a_fence_holds_even_in_a_file_that_does_not_parse() {
let dir = TempDir::new("check-fence-broken");
let src = "module foo;\n @@@ not verilog;\n // vfmt: off\n\tlocalparam int A = 1; \n // vfmt: on\nendmodule\n";
let src = "module foo;\n @@@ not verilog;\n // lucisv: off\n\tlocalparam int A = 1; \n // lucisv: on\nendmodule\n";
let path = dir.write("foo.sv", src);
let out = run(&["check", "--fix", &path]);
@@ -1062,7 +1063,7 @@ fn a_fence_holds_even_in_a_file_that_does_not_parse() {
// ---------------------------------------------------------------------------
/// The version stamped into every cache entry: the workspace version, which
/// `vfmt_core` reads with the same `env!`.
/// `lucisv_core` reads with the same `env!`.
const VERSION: &str = env!("CARGO_PKG_VERSION");
impl TempDir {
@@ -1084,7 +1085,7 @@ fn cache_line(
indent: usize,
version: &str,
) -> String {
let hash = vfmt_core::cache::content_hash(content.as_bytes());
let hash = lucisv_core::cache::content_hash(content.as_bytes());
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
}
@@ -1182,23 +1183,23 @@ fn a_hit_skips_the_work_entirely() {
#[test]
fn a_config_file_change_invalidates_the_entry_too() {
let dir = TempDir::new("cache-tomlchange");
dir.write("vfmt.toml", "indent = 2\n");
dir.write("lucisv.toml", "indent = 2\n");
let path = dir.write("a.sv", INDENT_2);
let cache = dir.cache();
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
dir.write("vfmt.toml", "indent = 4\n");
dir.write("lucisv.toml", "indent = 4\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 1, "the resolved settings are the key: {}", stderr(&out));
// …and an equivalent config written a different way is still a hit.
dir.write("vfmt.toml", "indent = 2 # back again\n");
dir.write("lucisv.toml", "indent = 2 # back again\n");
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
}
#[test]
fn an_entry_from_another_vfmt_version_is_ignored() {
fn an_entry_from_another_lucisv_version_is_ignored() {
let dir = TempDir::new("cache-version");
let path = dir.write("a.sv", UNFORMATTED);
let cache = dir.cache();
@@ -1328,7 +1329,7 @@ fn the_default_cache_lives_in_the_working_directory_and_ignores_itself() {
let out = run_in(&dir, &["--check", "."]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let cache_dir = dir.path.join(".vfmt_cache");
let cache_dir = dir.path.join(".lucisv_cache");
assert!(cache_dir.join("cache").is_file(), "the default cache is cwd-relative");
assert_eq!(
std::fs::read_to_string(cache_dir.join(".gitignore")).unwrap(),
@@ -1472,7 +1473,7 @@ fn lines_refuses_a_directory_and_a_bad_range() {
// The linter has no line ranges.
let out = run(&["check", "--lines", "2", &dir.write("c.sv", THREE)]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("`vfmt check`"), "{}", stderr(&out));
assert!(stderr(&out).contains("`lucisv check`"), "{}", stderr(&out));
}
#[test]
@@ -1501,15 +1502,15 @@ fn lines_neither_reads_nor_writes_the_cache() {
}
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
let mut child = Command::new(VFMT)
let mut child = Command::new(LUCISV)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn vfmt");
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
child.wait_with_output().expect("run vfmt")
child.wait_with_output().expect("run lucisv")
}
// --- `-f`, the EDA filelist (docs/features/cli-filelist/README.md) ---------
@@ -1695,5 +1696,5 @@ fn help_documents_the_filelist_flag() {
let text = stdout(&run(&["--help"]));
assert!(text.contains("FILELISTS:"), "{text}");
assert!(text.contains("-f <FILELIST>"), "{text}");
assert!(text.contains("read by vfmt-server only"), "the toml key stays server-only: {text}");
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
}
@@ -1,12 +1,12 @@
[package]
name = "vfmt_core"
name = "lucisv_core"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Config discovery and file walking, shared by the vfmt CLI and the vfmt language server"
description = "Config discovery and file walking, shared by the lucisv CLI and the lucisv language server"
[lib]
name = "vfmt_core"
name = "lucisv_core"
path = "src/lib.rs"
[dependencies]
@@ -13,12 +13,12 @@ use std::fmt::Write as _;
use std::path::{Path, PathBuf};
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".vfmt_cache";
pub const DEFAULT_DIR: &str = ".lucisv_cache";
/// The entry file inside the cache directory.
const FILE: &str = "cache";
/// vfmt's version, part of every entry: a new release may format the same
/// lucisv's version, part of every entry: a new release may format the same
/// bytes differently, so another version's entries are ignored.
const VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -57,7 +57,7 @@ impl Cache {
}
/// True when `path`'s current content was already verified formatted
/// under these settings by this version of vfmt.
/// under these settings by this version of lucisv.
pub fn is_clean(&self, path: &Path, entry: Entry) -> bool {
key(path).and_then(|k| self.entries.get(k)) == Some(&entry)
}
@@ -140,10 +140,10 @@ fn key(path: &Path) -> Option<&str> {
Some(text)
}
/// Parses the store. `None` means "this file is not something vfmt wrote"
/// Parses the store. `None` means "this file is not something lucisv wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
/// another vfmt version are dropped individually; that is staleness, not
/// another lucisv version are dropped individually; that is staleness, not
/// corruption.
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
@@ -179,7 +179,7 @@ mod tests {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("vfmt-cache-{}-{tag}-{n}", std::process::id()));
std::env::temp_dir().join(format!("lucisv-cache-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
@@ -1,4 +1,4 @@
//! `vfmt.toml` / `.vfmt.toml` discovery and its TOML-subset parser.
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a three-key config file needs is supported (comments,
//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is
@@ -10,7 +10,7 @@ use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
/// Config file names, in the order a directory is probed.
const NAMES: [&str; 2] = ["vfmt.toml", ".vfmt.toml"];
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
@@ -50,7 +50,7 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
if line.starts_with('[') {
return Err("tables (`[section]`) are unsupported in vfmt.toml".to_string());
return Err("tables (`[section]`) are unsupported in lucisv.toml".to_string());
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -110,7 +110,7 @@ fn parse_array(value: &str) -> Result<Vec<String>, String> {
let inner = value
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.ok_or("multi-line arrays are unsupported in vfmt.toml; write `[ \"a\", \"b\" ]`")?;
.ok_or("multi-line arrays are unsupported in lucisv.toml; write `[ \"a\", \"b\" ]`")?;
let mut items: Vec<&str> = inner.split(',').map(str::trim).collect();
if items.last() == Some(&"") {
// Either an empty array or a permitted trailing comma.
@@ -125,7 +125,7 @@ fn parse_string(value: &str) -> Result<String, String> {
.and_then(|rest| rest.strip_suffix('"'))
.ok_or_else(|| format!("expected a quoted string, found `{value}`"))?;
if inner.contains('"') || inner.contains('\\') {
return Err("quotes and escapes inside strings are unsupported in vfmt.toml".to_string());
return Err("quotes and escapes inside strings are unsupported in lucisv.toml".to_string());
}
Ok(inner.to_string())
}
@@ -292,7 +292,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn a_relative_filelist_resolves_against_the_config_files_directory() {
let tree = TempTree::new();
tree.write("vfmt.toml", "filelist = \"rtl/files.f\"\n");
tree.write("lucisv.toml", "filelist = \"rtl/files.f\"\n");
let deep = tree.write("a/b/x.sv", "");
let mut discovery = Discovery::new(true);
let found = discovery.for_file(&deep).unwrap();
@@ -302,7 +302,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn an_absolute_filelist_is_left_alone() {
let tree = TempTree::new();
tree.write("vfmt.toml", "filelist = \"/opt/project/files.f\"\n");
tree.write("lucisv.toml", "filelist = \"/opt/project/files.f\"\n");
let file = tree.write("x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(
@@ -366,7 +366,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn unsupported_toml_is_named_not_ignored() {
assert!(err("[tool.vfmt]\nindent = 2").contains("tables"));
assert!(err("[tool.lucisv]\nindent = 2").contains("tables"));
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
assert!(err("indent").contains("expected `key = value`"));
@@ -387,7 +387,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn new() -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("vfmt-config-{}-{n}", std::process::id()));
let path =
std::env::temp_dir().join(format!("lucisv-config-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
@@ -418,7 +419,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn searches_upward_from_the_files_directory() {
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
let deep = tree.write("a/b/c/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4));
@@ -427,8 +428,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn the_nearest_config_wins_and_does_not_merge() {
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\nline-length = 120\n");
tree.write("a/vfmt.toml", "indent = 8\n");
tree.write("lucisv.toml", "indent = 4\nline-length = 120\n");
tree.write("a/lucisv.toml", "indent = 8\n");
let near = tree.write("a/x.sv", "");
let far = tree.write("b/x.sv", "");
let mut discovery = Discovery::new(true);
@@ -442,26 +443,26 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn dotted_name_is_the_fallback_in_one_directory() {
let tree = TempTree::new();
tree.write(".vfmt.toml", "indent = 3\n");
tree.write(".lucisv.toml", "indent = 3\n");
let only_dotted = tree.write("x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&only_dotted).unwrap().indent, Some(3));
tree.write("vfmt.toml", "indent = 5\n");
tree.write("lucisv.toml", "indent = 5\n");
let mut discovery = Discovery::new(true);
assert_eq!(
discovery.for_file(&only_dotted).unwrap().indent,
Some(5),
"vfmt.toml is preferred when both are present"
"lucisv.toml is preferred when both are present"
);
}
#[test]
fn git_stops_the_walk_but_only_after_its_own_directory() {
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
tree.dir("repo/.git");
tree.write("repo/vfmt.toml", "indent = 8\n");
tree.write("repo/lucisv.toml", "indent = 8\n");
let inside = tree.write("repo/rtl/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(
@@ -473,7 +474,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
// With no config in the repo root, the walk stops there rather
// than escaping into the parent's config.
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
tree.dir("repo/.git");
let inside = tree.write("repo/rtl/x.sv", "");
let mut discovery = Discovery::new(true);
@@ -484,7 +485,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn a_git_file_stops_the_walk_too() {
// Submodules and worktrees have a `.git` *file*, not a directory.
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
tree.write("repo/.git", "gitdir: ../.git/modules/repo\n");
let inside = tree.write("repo/x.sv", "");
let mut discovery = Discovery::new(true);
@@ -494,7 +495,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn disabled_discovery_reads_nothing() {
let tree = TempTree::new();
tree.write("vfmt.toml", "this is not even valid\n");
tree.write("lucisv.toml", "this is not even valid\n");
let file = tree.write("x.sv", "");
let mut discovery = Discovery::new(false);
assert_eq!(discovery.for_file(&file).unwrap(), FileConfig::default());
@@ -503,7 +504,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn a_broken_config_is_an_error_naming_file_and_line() {
let tree = TempTree::new();
let config = tree.write("vfmt.toml", "indent = 2\nbogus = 1\n");
let config = tree.write("lucisv.toml", "indent = 2\nbogus = 1\n");
let file = tree.write("x.sv", "");
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
assert!(message.starts_with(&format!("{}:2: ", config.display())), "{message}");
@@ -513,7 +514,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn the_cache_answers_for_every_directory_on_the_walked_chain() {
let tree = TempTree::new();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
let deep = tree.write("a/b/c/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4));
@@ -523,15 +524,15 @@ exclude = [ \"build\", \"*_gen.sv\", ]
// Deleting the file afterwards proves the second lookup is served
// from the cache and not from disk.
std::fs::remove_file(tree.path.join("vfmt.toml")).expect("remove config");
std::fs::remove_file(tree.path.join("lucisv.toml")).expect("remove config");
assert_eq!(discovery.for_file(&tree.path.join("a/b/y.sv")).unwrap().indent, Some(4));
}
#[test]
fn a_directory_input_resolves_from_itself() {
let tree = TempTree::new();
tree.write("a/vfmt.toml", "indent = 8\n");
tree.write("vfmt.toml", "indent = 4\n");
tree.write("a/lucisv.toml", "indent = 8\n");
tree.write("lucisv.toml", "indent = 4\n");
let dir = tree.dir("a");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_input(&dir).unwrap().indent, Some(8));
@@ -542,7 +543,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
let tree = TempTree::new();
let mut discovery = Discovery::new(true);
discovery.cwd = tree.path.clone();
tree.write("vfmt.toml", "indent = 4\n");
tree.write("lucisv.toml", "indent = 4\n");
tree.write("a/b/x.sv", "");
assert_eq!(discovery.for_file(Path::new("./a/b/x.sv")).unwrap().indent, Some(4));
assert_eq!(discovery.for_file(Path::new("a/b/../b/x.sv")).unwrap().indent, Some(4));
@@ -4,7 +4,7 @@
//! One source path per line, `-f` to nest another filelist, `+incdir+` and
//! `+define+` recorded for later, `//` and `#` comments, `$VAR` expansion.
//! Nothing here fails on bad content: a filelist that names a deleted file,
//! nests one that cannot be read, carries a flag vfmt does not know, or nests
//! nests one that cannot be read, carries a flag lucisv does not know, or nests
//! `-f` past [`MAX_NESTING_DEPTH`] still produces the files it did name, plus
//! a warning for each problem. See `docs/features/filelist/README.md`.
@@ -258,7 +258,7 @@ mod tests {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("vfmt-filelist-{}-{n}", std::process::id()));
std::env::temp_dir().join(format!("lucisv-filelist-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
@@ -552,10 +552,10 @@ rtl/b.sv // the trailing form
// and a wrong closure there would be invisible to every other test.
let tree = TempTree::new();
tree.source("a.sv");
let f = tree.write("files.f", "${VFMT_FILELIST_UNSET_PROBE}a.sv\n");
let f = tree.write("files.f", "${LUCISV_FILELIST_UNSET_PROBE}a.sv\n");
let list = read(&f).expect("readable");
assert_eq!(names(&list), ["a.sv"]);
assert!(list.warnings[0].contains("VFMT_FILELIST_UNSET_PROBE"), "{:?}", list.warnings);
assert!(list.warnings[0].contains("LUCISV_FILELIST_UNSET_PROBE"), "{:?}", list.warnings);
}
#[test]
@@ -1,13 +1,13 @@
//! The parts of vfmt that decide *which* files are processed and *with what
//! settings*, shared by the `vfmt` CLI and the `vfmt-server` language server.
//! The parts of lucisv that decide *which* files are processed and *with what
//! settings*, shared by the `lucisv` CLI and the `lucisv-server` language server.
//!
//! `config` and `walk` were lifted out of `crates/vfmt` unchanged so the two
//! `config` and `walk` were lifted out of `crates/lucisv` unchanged so the two
//! front ends cannot silently disagree: an editor's format-on-save must find
//! the same `vfmt.toml` and skip the same files as CI's `vfmt --check`.
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
//! `cache` answers the third question of the same family — whether a file
//! needs to be processed at all, and `filelist` answers the first one the way
//! an EDA project already does, from a `.f` file. See
//! `docs/features/vfmt-core-lift/README.md`, and
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
@@ -4,7 +4,7 @@
use std::path::{Path, PathBuf};
/// File extensions vfmt formats when walking a directory.
/// File extensions lucisv formats when walking a directory.
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
/// The name of the per-directory ignore file that is honoured by default.
@@ -1,15 +1,15 @@
[package]
name = "vfmt_server"
name = "lucisv_server"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "vfmt-server"
name = "lucisv-server"
path = "src/main.rs"
[dependencies]
vfmt_core = { path = "../vfmt_core" }
lucisv_core = { path = "../lucisv_core" }
vlog_parser = { path = "../vlog_parser" }
vlog_semantic = { path = "../vlog_semantic" }
vlog_refactor = { path = "../vlog_refactor" }
@@ -110,7 +110,7 @@ fn units_of(index: &WorkspaceIndex) -> Vec<Candidate> {
}
/// Every `` `define`` the workspace declares. `` `undef`` entries are skipped:
/// vfmt does not preprocess, so it cannot say where a name stopped being
/// lucisv does not preprocess, so it cannot say where a name stopped being
/// defined, and offering the name is the honest answer either way.
fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
let mut out: Vec<Macro> = Vec::new();
@@ -1,5 +1,5 @@
//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one
//! `source.fixAll.vfmt` that applies all of them in a single pass.
//! `source.fixAll.lucisv` that applies all of them in a single pass.
//!
//! Only **Safe** fixes are offered. `--unsafe-fixes` is a flag a CLI user types
//! on purpose; a lightbulb in an editor is not that, and a fix that may change
@@ -17,14 +17,14 @@ use crate::convert::Positions;
use crate::state::Document;
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
/// an editor's fix-on-save can name vfmt without also running another server's
/// an editor's fix-on-save can name lucisv without also running another server's
/// fixer.
pub const FIX_ALL: &str = "source.fixAll.vfmt";
pub const FIX_ALL: &str = "source.fixAll.lucisv";
/// The actions available for `range` in a buffer.
///
/// `only` is the client's filter; it is honored here rather than left to the
/// client, because a fix-on-save request asks for `source.fixAll.vfmt` alone
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
/// and computing every quick fix for it would be work nobody reads.
pub fn code_actions(
uri: &Uri,
@@ -86,7 +86,7 @@ fn quick_fix(
/// One action applying every Safe fix in the buffer, as a whole-document edit.
///
/// **One pass, deliberately.** `vfmt check --fix` loops fix → re-lint until
/// **One pass, deliberately.** `lucisv check --fix` loops fix → re-lint until
/// nothing changes, because a pass skips a fix overlapping one already applied
/// (a line ending in a tab needs two rounds: `no-tabs` and
/// `no-trailing-whitespace` both want those bytes). An editor does not need
@@ -110,7 +110,7 @@ fn fix_all(
}
let edit = TextEdit { range: positions.whole_document(), new_text: fixed.output };
Some(CodeAction {
title: "vfmt: fix all auto-fixable lint violations".to_string(),
title: "lucisv: fix all auto-fixable lint violations".to_string(),
kind: Some(CodeActionKind::new(FIX_ALL)),
// No `diagnostics` list: one pass skips fixes that overlap an applied
// one, so this action cannot honestly name the findings it resolves.
@@ -128,11 +128,11 @@ fn workspace_edit(uri: &Uri, edits: Vec<TextEdit>) -> WorkspaceEdit {
/// is what the user would put in a waiver.
fn title(violation: &Violation) -> String {
let what = rule_by_name(violation.rule).map_or(violation.message.as_str(), |r| r.summary());
format!("vfmt: {what} [{}]", violation.rule)
format!("lucisv: {what} [{}]", violation.rule)
}
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
/// the kinds it selects (`source` selects `source.fixAll.vfmt`), and no filter
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
/// at all selects everything.
pub fn wanted(only: Option<&[CodeActionKind]>, kind: &CodeActionKind) -> bool {
let Some(only) = only else { return true };
@@ -216,12 +216,12 @@ mod tests {
let ws = workspace(text);
let actions = actions_of(&ws);
let fix = actions.iter().find(|a| a.kind == Some(CodeActionKind::QUICKFIX)).expect("one");
assert_eq!(fix.title, "vfmt: use spaces, not tabs [no-tabs]");
assert_eq!(fix.title, "lucisv: use spaces, not tabs [no-tabs]");
assert_eq!(fix.is_preferred, Some(true));
let diagnostics = fix.diagnostics.as_ref().expect("the finding it resolves");
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
// The edit must reproduce what `vfmt check --fix` would have written.
// The edit must reproduce what `lucisv check --fix` would have written.
let expected = vlog_linter::apply_fixes(
text,
&run(text, Some("/rtl/m.sv".into()), &default_rules()),
@@ -301,7 +301,8 @@ mod tests {
}
/// A tab inside a fence and a tab outside one, both `no-tabs` findings.
const FENCED: &str = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
const FENCED: &str =
"module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
#[test]
fn a_violation_inside_a_fence_gets_a_diagnostic_but_no_quick_fix() {
@@ -339,7 +340,7 @@ mod tests {
.expect("a fixAll action");
let output = applied(FENCED, all);
assert_eq!(
output, "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n wire b;\nendmodule\n",
output, "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n wire b;\nendmodule\n",
"the fenced line is byte-identical, the free one is fixed"
);
// And the fenced bytes really are the input's own, tab included.
@@ -357,7 +358,7 @@ mod tests {
#[test]
fn a_waived_violation_offers_no_fix() {
let text = "module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n";
let text = "module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n";
let ws = workspace(text);
assert!(actions_of(&ws).is_empty(), "a waiver silences the lightbulb too");
}
@@ -371,7 +372,7 @@ mod tests {
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
// `source` is a prefix filter for `source.fixAll.vfmt`.
// `source` is a prefix filter for `source.fixAll.lucisv`.
let source = [CodeActionKind::SOURCE];
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
// And an unrelated filter selects nothing.
@@ -317,7 +317,7 @@ fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
}
/// How generated text is indented at `offset`: the line's own indentation, and
/// one step as `vfmt.indent` spells it.
/// one step as `lucisv.indent` spells it.
///
/// Private again as of 2026-08-25. `inline.rs` used to share it, so that ghost
/// text and the completion list could not indent the same body differently;
@@ -906,7 +906,7 @@ endmodule
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_completion_{}_{name}", std::process::id()));
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -1168,7 +1168,7 @@ endmodule
// appear is the tabstop syntax that would eat it.
assert!(!text.contains("${"), "no tabstop may survive here: {text}");
assert!(text.contains(".\\my-port$1 (\\my-port$1 )"), "{text}");
let probe = format!("module vfmt_probe;\n{text}\nendmodule\n");
let probe = format!("module lucisv_probe;\n{text}\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
@@ -1736,8 +1736,8 @@ endmodule
// A buffer that is not on disk: it overlays the walk, so the corpus is
// never written to.
let top = "module vfmt_probe;\n logic clk;\n assign x = pr\nendmodule\n";
let uri = path_to_uri(&corpus.join("vfmt_probe.sv")).expect("uri");
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find("= pr").expect("needle") + 4) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
@@ -4,7 +4,7 @@
//! speaks UTF-16 code units within a line. The two agree only on ASCII, which
//! is why getting this wrong survives to production. The exact rules — mid-
//! character clamping, surrogate halves, CRLF — are in
//! `docs/features/vfmt-server/README.md`.
//! `docs/features/lucisv-server/README.md`.
use lsp_types::{Position, Range};
use vlog_parser::{LineIndex, TextRange};
@@ -6,7 +6,7 @@ use crate::state::Document;
/// The source string every diagnostic this server publishes carries, so a
/// user can tell ours from another server's.
pub const SOURCE: &str = "vfmt";
pub const SOURCE: &str = "lucisv";
/// Everything the server has to say about a buffer: the parse errors first,
/// then the lint warnings.
@@ -95,7 +95,7 @@ mod tests {
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].range.start.line, 1, "the broken line, 0-based");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].source.as_deref(), Some("vfmt"));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
@@ -128,7 +128,7 @@ mod tests {
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("vfmt")));
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
}
@@ -3,7 +3,7 @@
//! One step means one thing: the definition's body with the call site's
//! arguments substituted for the parameters. A nested `` `INNER`` inside the
//! body stays exactly as written — expanding it too would be preprocessing,
//! and TODO.md §7 says vfmt does not preprocess. So this module is the same
//! and TODO.md §7 says lucisv does not preprocess. So this module is the same
//! kind of bookkeeping `vlog_parser::defines` is: it never touches the
//! formatter, never rewrites the buffer, and its only consumer is the hover
//! card. See `docs/features/macro-expansion/README.md` for the full rule
File renamed without changes.
@@ -10,24 +10,24 @@
use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextEdit};
use vfmt_core::config::{Discovery, FileConfig};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use crate::settings::ClientSettings;
use crate::state::Document;
/// Indent widths a client may ask for. The same 1..8 range `vfmt.toml`'s own
/// Indent widths a client may ask for. The same 1..8 range `lucisv.toml`'s own
/// `indent` key allows, so the two agree.
const INDENT_RANGE: std::ops::RangeInclusive<u32> = 1..=8;
/// What to format a buffer with, and the config problem to tell the user
/// about. The two are separate because a broken `vfmt.toml` must not stop the
/// about. The two are separate because a broken `lucisv.toml` must not stop the
/// buffer from being formatted.
pub struct Settings {
/// The settings to format with — the fallback defaults when `problem` is
/// set.
pub config: Config,
/// The `vfmt.toml` error governing this buffer, if there is one.
/// The `lucisv.toml` error governing this buffer, if there is one.
pub problem: Option<String>,
}
@@ -35,11 +35,11 @@ pub struct Settings {
///
/// Precedence, highest first:
///
/// 1. **`vfmt.toml`** — a checked-in config is the project speaking, and it
/// 1. **`lucisv.toml`** — a checked-in config is the project speaking, and it
/// must stay authoritative or format-on-save would disagree with CI's
/// `vfmt --check`. That divergence is the exact thing lifting the config
/// into `vfmt_core` exists to remove.
/// 2. **The client's `vfmt.*` settings** (`settings.rs`) — typed on purpose
/// `lucisv --check`. That divergence is the exact thing lifting the config
/// into `lucisv_core` exists to remove.
/// 2. **The client's `lucisv.*` settings** (`settings.rs`) — typed on purpose
/// into an editor's settings UI, so more deliberate than a tab size, but
/// it is one user's editor and the repository outranks it.
/// 3. **`FormattingOptions::tab_size`** — sent on every request whether or
@@ -49,7 +49,7 @@ pub struct Settings {
/// 4. **The built-in default.**
///
/// Each rung applies only where every rung above it is silent, so a project
/// with no `vfmt.toml` and no `vfmt.*` settings behaves exactly as it did
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
/// before either existed.
pub fn settings_for(
doc: &Document,
@@ -109,7 +109,7 @@ pub fn range_formatting(
///
/// A `textDocument/codeAction` request carries no `FormattingOptions`, so there
/// is no client `tabSize` to consider here — the precedence is the same ladder
/// `settings_for` documents with rung 3 missing: `vfmt.toml` > `vfmt.indent` >
/// `settings_for` documents with rung 3 missing: `lucisv.toml` > `lucisv.indent` >
/// the built-in default. A broken config is silent on this path: the
/// formatting path is where the user is told about it, and warning from a
/// lightbulb the editor requests on every cursor move would be noise.
@@ -123,7 +123,7 @@ pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
/// has no directory to search from, so it gets no config.
fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
let Some(path) = path else { return (FileConfig::default(), None) };
// A fresh `Discovery` per request, so a `vfmt.toml` edited while the
// A fresh `Discovery` per request, so a `lucisv.toml` edited while the
// server runs takes effect at the next format. One file read on an
// explicit, user-initiated request is cheaper than any cache invalidation
// scheme that could be wrong.
@@ -133,16 +133,16 @@ fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
}
}
/// Fold the config file, the pushed `vfmt.*` settings and the client's tab
/// Fold the config file, the pushed `lucisv.*` settings and the client's tab
/// options into formatter settings, in the precedence `settings_for`
/// documents. Written weakest-first, so the last writer wins.
///
/// The client's `tab_size` is taken only when the request is sane: a client
/// asking for hard tabs, or for a 40-space indent, is asking for something
/// vfmt does not do, and silently honoring half of it is worse than ignoring
/// it. `vfmt.lineLength` has no `FormattingOptions` analog at all — the
/// lucisv does not do, and silently honoring half of it is worse than ignoring
/// it. `lucisv.lineLength` has no `FormattingOptions` analog at all — the
/// protocol carries no line-length option — so before it existed there was no
/// way to set a width from an editor without a `vfmt.toml`.
/// 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) {
@@ -184,7 +184,7 @@ mod tests {
FormattingOptions { tab_size, insert_spaces, ..Default::default() }
}
/// No `vfmt.*` settings pushed — what every test predating them assumes.
/// No `lucisv.*` settings pushed — what every test predating them assumes.
fn none() -> ClientSettings {
ClientSettings::default()
}
@@ -222,7 +222,7 @@ mod tests {
formatting(doc, &settings_for(doc, client, options).config)
}
/// A scratch directory holding a `vfmt.toml` and one source file, so
/// A scratch directory holding a `lucisv.toml` and one source file, so
/// discovery runs against a real tree. Removed on drop.
struct Tree {
path: PathBuf,
@@ -233,13 +233,13 @@ mod tests {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("vfmt_server_fmt_{}_{n}", std::process::id()));
std::env::temp_dir().join(format!("lucisv_server_fmt_{}_{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
// A `.git` marker stops discovery here, so a `vfmt.toml` in a real
// A `.git` marker stops discovery here, so a `lucisv.toml` in a real
// ancestor of the temp dir can never leak into these tests.
std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git");
std::fs::write(path.join("vfmt.toml"), config).expect("write config");
std::fs::write(path.join("lucisv.toml"), config).expect("write config");
Tree { path }
}
@@ -317,11 +317,11 @@ mod tests {
#[test]
fn a_config_file_beats_the_editors_tab_size() {
// The precedence decision, pinned: `tab_size` is the editor's default
// unless the user changed it, and a checked-in `vfmt.toml` is always
// unless the user changed it, and a checked-in `lucisv.toml` is always
// deliberate. See `settings_for`.
let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() };
let config = config_from(&file, &none(), &options(2, true));
assert_eq!(config.indent_width, 4, "vfmt.toml wins over tab_size");
assert_eq!(config.indent_width, 4, "lucisv.toml wins over tab_size");
assert_eq!(config.max_width, 120, "line-length has no client analog at all");
// Where the config is silent the tab size still beats the default.
let only_width = FileConfig { line_length: Some(120), ..Default::default() };
@@ -329,7 +329,7 @@ mod tests {
}
#[test]
fn a_vfmt_toml_governs_the_buffer_it_sits_above() {
fn a_lucisv_toml_governs_the_buffer_it_sits_above() {
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
// The client asks for 2, the config says 4: the config wins.
@@ -341,13 +341,13 @@ mod tests {
}
#[test]
fn a_broken_vfmt_toml_reports_a_problem_and_formats_with_defaults() {
fn a_broken_lucisv_toml_reports_a_problem_and_formats_with_defaults() {
let tree = Tree::new("indent = 4\nbogus = 1\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let settings = settings(&ws, &uri, &options(2, true));
let problem = settings.problem.expect("a broken config must be reported");
assert!(problem.contains("unknown key `bogus`"), "{problem}");
assert!(problem.contains("vfmt.toml:2"), "the message names file and line: {problem}");
assert!(problem.contains("lucisv.toml:2"), "the message names file and line: {problem}");
// Nothing from the broken file is used, not even the key that parsed.
assert_eq!(settings.config.indent_width, Config::default().indent_width);
// And the buffer is still formatted: an editor must not hard-fail on a
@@ -359,7 +359,7 @@ mod tests {
#[test]
fn a_lint_fixs_indent_comes_from_the_config_or_the_built_in_default() {
// A code action has no `tabSize` to consider, so a quick fix that
// writes spaces where a tab was gets the buffer's own `vfmt.toml`.
// writes spaces where a tab was gets the buffer's own `lucisv.toml`.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
@@ -393,7 +393,7 @@ mod tests {
// the precedence ladder, one rung at a time
// ------------------------------------------------------------------
/// `vfmt.*` settings as a client would push them.
/// `lucisv.*` settings as a client would push them.
fn pushed(line_length: Option<usize>, indent: Option<usize>) -> ClientSettings {
ClientSettings { line_length, indent, ..Default::default() }
}
@@ -401,13 +401,13 @@ mod tests {
#[test]
fn rung_1_a_config_file_beats_a_pushed_setting() {
// The whole reason the ladder is in this order: a checked-in
// `vfmt.toml` is the project speaking, and format-on-save must agree
// with what `vfmt --check` does in CI.
// `lucisv.toml` is the project speaking, and format-on-save must agree
// with what `lucisv --check` does in CI.
let tree = Tree::new("indent = 4\nline-length = 120\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
let client = pushed(Some(80), Some(8));
let settings = settings_with(&ws, &uri, &client, &options(2, true));
assert_eq!(settings.config.indent_width, 4, "vfmt.toml wins");
assert_eq!(settings.config.indent_width, 4, "lucisv.toml wins");
assert_eq!(settings.config.max_width, 120, "for line-length too");
let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats");
assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n");
@@ -416,7 +416,7 @@ mod tests {
#[test]
fn rung_2_a_pushed_setting_beats_the_editors_tab_size() {
// `tabSize` arrives on every request whether the user chose it or
// not; `vfmt.indent` was typed on purpose.
// not; `lucisv.indent` was typed on purpose.
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
let client = pushed(None, Some(4));
let settings = settings_with(&ws, &uri, &client, &options(2, true));
@@ -446,7 +446,7 @@ mod tests {
#[test]
fn each_key_climbs_the_ladder_independently() {
// A `vfmt.toml` naming only `indent` must not also claim the width:
// A `lucisv.toml` naming only `indent` must not also claim the width:
// the pushed `lineLength` is still the best answer for that key.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
@@ -458,7 +458,7 @@ mod tests {
#[test]
fn a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config() {
// The protocol has no line-length option at all, so before
// `vfmt.lineLength` a config-less project could not narrow its lines
// `lucisv.lineLength` a config-less project could not narrow its lines
// from the editor. This is the new capability, at the level that
// actually reflows text.
let long = "module m;\n assign a = bbbbbbbbbbbb + cccccccccccc + dddddddddddd + eeeeeeeeeeee;\nendmodule\n";
@@ -472,7 +472,7 @@ mod tests {
#[test]
fn an_untitled_buffer_honours_pushed_settings() {
// It has no directory to discover a `vfmt.toml` from, so rung 2 is the
// It has no directory to discover a `lucisv.toml` from, so rung 2 is the
// highest rung it has — and before this feature it had only `tabSize`.
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
let mut ws = Workspace::default();
@@ -485,8 +485,8 @@ mod tests {
#[test]
fn a_lint_fix_climbs_the_same_ladder_without_rung_3() {
// A code action has no `tabSize`, so `vfmt.indent` is the only thing
// under a `vfmt.toml` here.
// A code action has no `tabSize`, so `lucisv.indent` is the only thing
// under a `lucisv.toml` here.
let tree = Tree::new("indent = 4\n");
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
@@ -497,7 +497,7 @@ mod tests {
#[test]
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
// Nothing from a broken `vfmt.toml` is used, so the next rung down is
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
// the one that answers — which is now the pushed settings, not the
// built-in default.
let tree = Tree::new("indent = 4\nbogus = 1\n");
@@ -279,7 +279,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_hierarchy_{}_{name}", std::process::id()));
.join(format!("lucisv_server_hierarchy_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -499,7 +499,7 @@ endmodule
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
tree.write("files.f", "sub.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
@@ -757,7 +757,7 @@ endmodule
// Unlike `inlay.rs` (which treats an `ifdef`-carrying list as an
// uncertainty and stays silent, see docs/features/inlay-hints —
// "ifdef" QA finding), this feature's README documents no `ifdef`
// policy at all. The answer is arguably the honest one — vfmt cannot
// policy at all. The answer is arguably the honest one — lucisv cannot
// know which arm is live, and showing both is not a *wrong* single
// claim the way a mis-ordered port hint would be — but it should be
// stated as an Assumption rather than left silent. See QA log.
@@ -3,7 +3,7 @@
//! Four things can be under the cursor, tried in this order: a macro usage, a
//! reference resolved in this file, a reference the workspace answered, and a
//! declaration itself. The order and the rendering rules are in
//! `docs/features/vfmt-server/README.md`.
//! `docs/features/lucisv-server/README.md`.
//!
//! A macro card also shows what the hovered use expands to in one step, when
//! that is more than the body it already prints — `crate::expand` and
@@ -245,7 +245,7 @@ mod tests {
fn temp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("vfmt_server_hover_{tag}_{}", std::process::id()));
std::env::temp_dir().join(format!("lucisv_server_hover_{tag}_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
dir
@@ -625,7 +625,7 @@ mod qa_findings {
/// the dev shipped in this file only exercise the quoted form.
#[test]
fn an_angled_include_narrows_hover_same_as_a_quoted_one() {
let dir = std::env::temp_dir().join(format!("vfmt_qa_hover_sys_{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_sys_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("inc")).expect("mkdir");
fs::write(dir.join("inc/uvm_macros.svh"), "`define W 8\n").expect("write");
@@ -684,7 +684,7 @@ mod qa_findings {
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatched_include_still_counts_as_reachable() {
let dir = std::env::temp_dir().join(format!("vfmt_qa_hover_case_{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_qa_hover_case_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("mkdir");
fs::write(dir.join("Defs.svh"), "`define W 8\n").expect("write");
@@ -210,7 +210,7 @@ impl IncludeGraph {
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
/// compares equal to the same file's path in the index. Symlinks are
/// deliberately not resolved, matching `vfmt_core`'s lexical rule.
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
@@ -352,7 +352,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_includes_{}_{name}", std::process::id()));
.join(format!("lucisv_server_includes_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -608,7 +608,7 @@ mod tests {
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
/// timing assertions in a shared runner are flaky by nature. Run with
/// `cargo test --release -p vfmt_server --bin vfmt-server perf -- --ignored --nocapture`.
/// `cargo test --release -p lucisv_server --bin lucisv-server perf -- --ignored --nocapture`.
mod perf {
use super::*;
@@ -693,7 +693,7 @@ mod qa_scope_probe {
/// list — but pinned here since it was previously untested.
#[test]
fn a_link_resolves_to_a_file_the_filelist_never_names() {
let dir = std::env::temp_dir().join(format!("vfmt_qa_outscope_{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_qa_outscope_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("inc")).expect("mkdir");
// defs.svh exists on disk but is not named in files.f.
@@ -734,7 +734,8 @@ mod qa_round2 {
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn three_files_colliding_on_one_folded_spelling_stay_ambiguous() {
let dir = std::env::temp_dir().join(format!("vfmt_qa_r2_threeway_{}", std::process::id()));
let dir =
std::env::temp_dir().join(format!("lucisv_qa_r2_threeway_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("mkdir");
let top = dir.join("top.sv");
@@ -765,7 +766,8 @@ mod qa_round2 {
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[test]
fn a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged() {
let dir = std::env::temp_dir().join(format!("vfmt_qa_r2_outscope_{}", std::process::id()));
let dir =
std::env::temp_dir().join(format!("lucisv_qa_r2_outscope_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("mkdir");
let top = dir.join("top.sv");
@@ -235,7 +235,7 @@ endmodule
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_inlay_{}_{name}", std::process::id()));
.join(format!("lucisv_server_inlay_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -727,7 +727,7 @@ endmodule
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
/// timing assertions in a shared CI runner are flaky by nature. Run with
/// `cargo test --release -p vfmt_server --bin vfmt-server qa_perf -- --ignored --nocapture`.
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
mod qa_perf {
use super::*;
@@ -371,7 +371,7 @@ fn rest_of_line_is_blank(text: &str, offset: u32) -> bool {
///
/// So the server says "one step in" and the editor says where and how wide:
/// `\t` is the one character `normalizeIndentation` re-spells as the user's
/// own `editor.tabSize`/`insertSpaces`. The consequence is that `vfmt.indent`
/// own `editor.tabSize`/`insertSpaces`. The consequence is that `lucisv.indent`
/// does **not** decide the width of an accepted snippet — the editor's
/// settings do, which is the more correct answer for text the editor is
/// writing. There is no plain-text spelling here: unlike a completion item, an
@@ -531,7 +531,7 @@ mod tests {
#[test]
fn the_indent_setting_no_longer_reaches_a_snippet() {
// `vfmt.indent` still decides what the *formatter* writes and what the
// `lucisv.indent` still decides what the *formatter* writes and what the
// completion popup inserts; an accepted inline snippet is laid out by
// the editor's own tab settings, because the editor re-spells the
// leading whitespace on insert whatever the server sent.
@@ -986,9 +986,11 @@ endmodule
match trigger.keyword {
"module" => format!("{text}\n"),
"generate" | "always" | "always_ff" => {
format!("module vfmt_probe;\n {text}\nendmodule\n")
format!("module lucisv_probe;\n {text}\nendmodule\n")
}
_ => {
format!("module lucisv_probe;\n always @(*) begin\n {text}\n end\nendmodule\n")
}
_ => format!("module vfmt_probe;\n always @(*) begin\n {text}\n end\nendmodule\n"),
}
}
@@ -1,9 +1,9 @@
//! Lint findings, and the diagnostics they become.
//!
//! `vlog_linter` is the same engine `vfmt check` runs, with the same default
//! `vlog_linter` is the same engine `lucisv check` runs, with the same default
//! rule set — an editor that disagreed with CI about what a violation is would
//! be worse than one that showed none. Selection (`--select`/`--ignore`) has no
//! `vfmt.toml` key yet, so there is nothing here to configure; see
//! `lucisv.toml` key yet, so there is nothing here to configure; see
//! `docs/features/server-lint/README.md`.
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
@@ -39,12 +39,12 @@ pub fn violations(doc: &Document) -> Vec<Violation> {
/// The findings a code action may offer a fix for, with their fixes built for
/// `tab_width`.
///
/// The code-action path passes the indent width of the `vfmt.toml` governing
/// the buffer, so a quick fix that replaces a tab writes exactly what `vfmt`
/// The code-action path passes the indent width of the `lucisv.toml` governing
/// the buffer, so a quick fix that replaces a tab writes exactly what `lucisv`
/// would have written there.
///
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
/// region is dropped here, so the editor keeps the same promise `vfmt check
/// region is dropped here, so the editor keeps the same promise `lucisv check
/// --fix` does: **reported, never auto-fixed**. The diagnostic still reaches
/// the user — [`violations`] is the publishing path and is not filtered — it
/// just has no lightbulb. Which bytes count as fenced is
@@ -115,14 +115,14 @@ mod tests {
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("vfmt"));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n");
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
assert!(diagnostics(ws.document(&uri).expect("open")).is_empty());
}
@@ -171,7 +171,7 @@ mod tests {
fn a_violation_inside_a_fence_is_reported_but_not_fixable() {
// `off` means hands-off for the editor too: the warning is published,
// the fix is withheld.
let text = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
let text = "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
@@ -187,7 +187,7 @@ mod tests {
// Error recovery can swallow the item structure `fence::collect` hangs
// a region on — the buffers the server sees mid-keystroke are exactly
// that population, and the shared filter's scan half covers them.
let text = "module m;\n@@@ junk;\n// vfmt: off\n\twire a;\n// vfmt: on\nendmodule\n";
let text = "module m;\n@@@ junk;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
assert!(
File renamed without changes.
@@ -1,10 +1,10 @@
//! `vfmt-server` — the vfmt language server, speaking LSP over stdio.
//! `lucisv-server` — the lucisv language server, speaking LSP over stdio.
//!
//! One binary for every editor: VS Code through a thin extension, Vim/Neovim
//! through built-in LSP config. No editor-specific logic lives below the
//! protocol layer, and no language logic lives in it — every answer comes from
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
//! `docs/features/vfmt-server/README.md`.
//! `docs/features/lucisv-server/README.md`.
mod candidates;
mod code_action;
@@ -123,7 +123,7 @@ fn capabilities() -> ServerCapabilities {
// Every action is returned complete; there is nothing to resolve.
resolve_provider: None,
})),
// The port refactorings. `vfmt.addPort` needs a declaration typed by
// The port refactorings. `lucisv.addPort` needs a declaration typed by
// the user, which no code action can carry, and a Vim user has no
// lightbulb at all — so all three are commands as well.
execute_command_provider: Some(ExecuteCommandOptions {
@@ -167,7 +167,7 @@ fn capabilities() -> ServerCapabilities {
call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
// Ghost text for `if (` and `begin`, LSP 3.18. `true` rather than
// options: there is nothing to configure on the server side, and the
// one thing a user can say — `vfmt.inlineTemplates` — is a setting the
// one thing a user can say — `lucisv.inlineTemplates` — is a setting the
// handler reads, not a registration option. The VS Code client only
// sends the request after opting into `ProposedFeatures`, so an
// extension older than this server simply never asks.
@@ -191,7 +191,7 @@ fn initialize_result() -> lsp_types::InitializeResult {
lsp_types::InitializeResult {
capabilities: capabilities(),
server_info: Some(lsp_types::ServerInfo {
name: "vfmt-server".to_string(),
name: "lucisv-server".to_string(),
version: Some(env!("CARGO_PKG_VERSION").to_string()),
}),
// `lsp-types`' `proposed` feature adds an `offsetEncoding` field here
@@ -360,7 +360,11 @@ mod tests {
fn every_advertised_command_is_one_the_server_runs() {
let options = capabilities().execute_command_provider.expect("commands");
assert_eq!(options.commands, ports::commands());
assert!(options.commands.iter().all(|c| c.starts_with("vfmt.")), "{:?}", options.commands);
assert!(
options.commands.iter().all(|c| c.starts_with("lucisv.")),
"{:?}",
options.commands
);
}
#[test]
@@ -228,7 +228,7 @@ mod tests {
fn temp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("vfmt_server_nav_{tag}_{}", std::process::id()));
std::env::temp_dir().join(format!("lucisv_server_nav_{tag}_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
dir
@@ -2,7 +2,7 @@
//! stack over the token stream.
//!
//! One engine, three consumers, all below: `textDocument/documentHighlight`,
//! the missing-closer warnings, and `vfmt/scopePairs`, which feeds the
//! the missing-closer warnings, and `lucisv/scopePairs`, which feeds the
//! extension's rainbow colouring. Matching runs over `Document.tokens`
//! rather than the text, so a `// end` in a comment or a `"begin"` in a string
//! cannot be mistaken for a keyword: the lexer has already thrown comments out
@@ -396,7 +396,7 @@ fn covers(span: TextRange, offset: u32) -> bool {
}
// ----------------------------------------------------------------------
// vfmt/scopePairs — the extension's rainbow
// lucisv/scopePairs — the extension's rainbow
// ----------------------------------------------------------------------
/// The custom request the VS Code extension polls for rainbow colouring.
@@ -406,9 +406,9 @@ fn covers(span: TextRange, offset: u32) -> bool {
/// different ranges. A custom method needs no capability — a client that does
/// not know it simply never sends it, and one that does gets an error if this
/// server is too old, which is the same handshake a capability would give.
pub const SCOPE_PAIRS_METHOD: &str = "vfmt/scopePairs";
pub const SCOPE_PAIRS_METHOD: &str = "lucisv/scopePairs";
/// `vfmt/scopePairs` params — the document to describe, and nothing else.
/// `lucisv/scopePairs` params — the document to describe, and nothing else.
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScopePairsParams {
@@ -424,7 +424,7 @@ pub struct ScopePair {
pub depth: u32,
}
/// The `vfmt/scopePairs` result. An object rather than a bare array so a later
/// The `lucisv/scopePairs` result. An object rather than a bare array so a later
/// round can add a field without breaking a client that ignores it.
#[derive(serde::Serialize)]
pub struct ScopePairs {
@@ -1438,7 +1438,7 @@ mod tests {
}
// ------------------------------------------------------------------
// vfmt/scopePairs
// lucisv/scopePairs
// ------------------------------------------------------------------
#[test]
@@ -1598,7 +1598,7 @@ mod tests {
}
// ------------------------------------------------------------------
// vfmt/scopePairs — unmatched block delimiters
// lucisv/scopePairs — unmatched block delimiters
// ------------------------------------------------------------------
/// The unmatched ranges of a buffer as `(line, character)` starts.
@@ -1736,7 +1736,7 @@ mod tests {
let warnings = missing_end_diagnostics(&doc);
assert_eq!(warnings.len(), 1);
assert_eq!(warnings[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(warnings[0].source.as_deref(), Some("vfmt"));
assert_eq!(warnings[0].source.as_deref(), Some("lucisv"));
assert_eq!(warnings[0].range.start.line, 1, "the `initial begin` line");
assert_eq!(warnings[0].message, "`begin` has no matching `end` — is an `end` missing?");
}
@@ -8,8 +8,8 @@
//!
//! **Why commands as well as code actions.** Adding a port needs a
//! declaration typed by the user, and a code action carries no input — so
//! `vfmt.addPort` is the API a UI calls once it has asked. `vfmt.removePort`
//! and `vfmt.propagatePorts` take a position and exist for the same reason a
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
//! See `docs/features/refactor-ports/README.md`.
@@ -32,14 +32,14 @@ use crate::uri::{path_to_uri, uri_to_path};
/// The kind every port refactoring is filed under, so a client can ask for
/// them alone.
pub const REFACTOR_PORTS: &str = "refactor.rewrite.vfmt.ports";
pub const REFACTOR_PORTS: &str = "refactor.rewrite.lucisv.ports";
/// Add a port: `[uri, module-name-or-position, "input logic [7:0] cfg"]`.
pub const ADD_PORT: &str = "vfmt.addPort";
pub const ADD_PORT: &str = "lucisv.addPort";
/// Remove the port at a position: `[uri, position]`.
pub const REMOVE_PORT: &str = "vfmt.removePort";
pub const REMOVE_PORT: &str = "lucisv.removePort";
/// Connect an instantiation's missing ports: `[uri, position]`.
pub const PROPAGATE_PORTS: &str = "vfmt.propagatePorts";
pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts";
/// Every command this server executes.
pub fn commands() -> Vec<String> {
@@ -115,12 +115,12 @@ pub fn execute(
let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?;
vlog_refactor::propagate_ports(&sources, &path, offset)?
}
other => return Err(format!("`{other}` is not a vfmt command.")),
other => return Err(format!("`{other}` is not a lucisv command.")),
};
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// What the second argument of `vfmt.addPort` said.
/// What the second argument of `lucisv.addPort` said.
enum ModuleArgument {
Name(String),
Position(Position),
@@ -142,13 +142,13 @@ fn module_argument(argument: Option<&Value>) -> ModuleArgument {
fn target(ws: &Workspace, argument: Option<&Value>) -> Result<(Uri, PathBuf), String> {
let uri: Uri =
argument.and_then(|value| serde_json::from_value(value.clone()).ok()).ok_or_else(|| {
"a vfmt port command wants a document URI as its first argument.".to_string()
"a lucisv port command wants a document URI as its first argument.".to_string()
})?;
let path = ws
.document(&uri)
.and_then(|doc| doc.path.clone())
.or_else(|| uri_to_path(&uri))
.ok_or_else(|| "vfmt can only refactor inside a saved file.".to_string())?;
.ok_or_else(|| "lucisv can only refactor inside a saved file.".to_string())?;
Ok((uri, path))
}
@@ -167,8 +167,9 @@ fn offset_of(ws: &Workspace, uri: Option<&Value>, position: Position) -> Result<
match ws.document(&uri) {
Some(doc) => Ok(doc.positions().offset(position)),
None => {
let text =
ws.text_of(&path).ok_or_else(|| format!("vfmt cannot read {}.", path.display()))?;
let text = ws
.text_of(&path)
.ok_or_else(|| format!("lucisv cannot read {}.", path.display()))?;
let index = LineIndex::new(&text);
Ok(Positions::new(&text, &index).offset(position))
}
@@ -182,7 +183,7 @@ pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<Work
for (path, edits) in &refactoring.edits {
let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else {
return Err(format!(
"vfmt could not address {} as a document; no edits were made.",
"lucisv could not address {} as a document; no edits were made.",
path.display()
));
};
@@ -215,7 +216,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_ports_{}_{name}", std::process::id()));
.join(format!("lucisv_server_ports_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -348,7 +349,7 @@ mod tests {
let actions = code_actions(&ws, &sub_uri, offset);
assert_eq!(actions.len(), 1, "{actions:#?}");
let CodeActionOrCommand::CodeAction(action) = &actions[0] else { panic!("an action") };
assert_eq!(action.title, "vfmt: remove port `rst` (updates 1 instantiation)");
assert_eq!(action.title, "lucisv: remove port `rst` (updates 1 instantiation)");
assert_eq!(action.kind, Some(CodeActionKind::new(REFACTOR_PORTS)));
let edit = action.edit.as_ref().expect("an edit");
assert_eq!(edits_for(edit, &sub_uri).len(), 2, "the comma and the port itself");
@@ -360,8 +361,8 @@ mod tests {
let tree = Tree::new("unknown");
let (ws, uri, _) = opened(&tree);
let arguments = vec![serde_json::to_value(&uri).expect("uri")];
let message = execute(&ws, "vfmt.nope", &arguments).expect_err("unknown");
assert!(message.contains("not a vfmt command"), "{message}");
let message = execute(&ws, "lucisv.nope", &arguments).expect_err("unknown");
assert!(message.contains("not a lucisv command"), "{message}");
}
#[test]
@@ -54,7 +54,7 @@ pub fn rename(
// text nobody has.
let (Some(target), Some(text)) = (path_to_uri(path), ws.text_of(path)) else {
return Err(format!(
"vfmt could not address {} as a document; no edits were made.",
"lucisv could not address {} as a document; no edits were made.",
path.display()
));
};
@@ -74,7 +74,7 @@ pub fn rename(
Ok((WorkspaceEdit::new(changes), refactoring.warnings))
}
const UNSAVED: &str = "vfmt can only rename inside a saved file.";
const UNSAVED: &str = "lucisv can only rename inside a saved file.";
#[cfg(test)]
mod tests {
@@ -91,7 +91,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_rename_{}_{name}", std::process::id()));
.join(format!("lucisv_server_rename_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -3,7 +3,7 @@
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
//! messages over a channel. Everything below is synchronous and un-cancellable
//! — Verilog files are small, every handler is milliseconds, and a worker pool
//! would buy nothing yet. See `docs/features/vfmt-server/README.md`.
//! would buy nothing yet. See `docs/features/lucisv-server/README.md`.
use std::collections::HashSet;
use std::error::Error;
@@ -59,13 +59,13 @@ pub struct ClientAbilities {
pub struct Server {
connection: Connection,
workspace: Workspace,
/// Documents whose `vfmt.toml` problem has already been reported. Cleared
/// Documents whose `lucisv.toml` problem has already been reported. Cleared
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `vfmt.filelist` can replace it: the watched filelist path is
/// changed `lucisv.filelist` can replace it: the watched filelist path is
/// part of the registration, so a new path needs a new registration.
watchers: Option<String>,
/// Numbers the file-watcher registrations, so a replacement can name the
@@ -220,7 +220,7 @@ impl Server {
let only = p.context.only;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
// A code-action request carries no `tabSize`, so the width a
// `no-tabs` fix writes comes from the buffer's own `vfmt.toml`
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
// or from the built-in default.
let tab_width =
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
@@ -357,7 +357,7 @@ impl Server {
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);
// A broken `vfmt.toml` is a warning, not a failure: the CLI exits 2 on
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
// one, but an editor that refuses to format because of a typo in a
// config file is an editor the user turns off. The buffer is formatted
// with the built-in defaults, and the reason is said once per change of
@@ -380,13 +380,13 @@ impl Server {
self.edits(result)
}
/// Say once per change of a file that its `vfmt.toml` could not be read.
/// Say once per change of a file that its `lucisv.toml` could not be read.
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
if let Some(problem) = problem {
if self.config_warnings.insert(uri.clone()) {
self.show_message(
MessageType::WARNING,
format!("vfmt: {problem} — formatting with default settings"),
format!("lucisv: {problem} — formatting with default settings"),
);
}
}
@@ -406,7 +406,7 @@ impl Server {
Ok(Some(edit)) => to_value(vec![edit]),
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
Err(message) => {
self.show_message(MessageType::ERROR, format!("vfmt: cannot format — {message}"));
self.show_message(MessageType::ERROR, format!("lucisv: cannot format — {message}"));
to_value(Vec::<lsp_types::TextEdit>::new())
}
}
@@ -450,7 +450,7 @@ impl Server {
self.set_document(p.text_document.uri.clone(), text);
}
// A save is one of the things that rebuild the index; the
// others are a change to `vfmt.exclude`/`vfmt.filelist`
// others are a change to `lucisv.exclude`/`lucisv.filelist`
// below, and a watched file changing on disk. The
// staleness window that is left is in the feature README.
self.reindex();
@@ -468,7 +468,7 @@ impl Server {
}
}
}
// The `vfmt.*` settings, pushed at startup and on every change.
// The `lucisv.*` settings, pushed at startup and on every change.
// Nothing here trusts the payload — `settings::from_payload`
// drops whatever it cannot use.
DidChangeConfiguration::METHOD => {
@@ -532,7 +532,7 @@ impl Server {
/// Ask the client something. The answer is ignored (see `run`), but the id
/// must still be unique — a repeated one is a protocol error.
fn send_request(&mut self, method: &str, params: impl serde::Serialize) {
let id = RequestId::from(format!("vfmt-{}", self.request_ids));
let id = RequestId::from(format!("lucisv-{}", self.request_ids));
self.request_ids += 1;
let request = Request::new(id, method.to_string(), params);
// A closed channel means the client is gone; there is nobody left to
@@ -542,7 +542,7 @@ 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
/// new `vfmt.exclude`/`vfmt.filelist`, or a watched file changing on disk.
/// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk.
fn reindex(&mut self) {
let warnings = self.workspace.rebuild_index();
self.report_scope(warnings);
@@ -553,29 +553,32 @@ impl Server {
/// Say what went wrong while working out which files to index — a
/// filelist naming a file that has moved, an unset variable, an option
/// vfmt does not know.
/// lucisv does not know.
///
/// Every one is logged, but only the first is *shown*: a filelist that has
/// drifted from the tree can easily carry forty stale paths, and forty
/// popups would be worse than the problem. Said once per rebuild, which is
/// once per save — the same rhythm the `vfmt.toml` warning has.
/// once per save — the same rhythm the `lucisv.toml` warning has.
fn report_scope(&self, warnings: Vec<String>) {
for warning in &warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams { typ: MessageType::WARNING, message: format!("vfmt: {warning}") },
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
let Some(first) = warnings.first() else { return };
let rest = warnings.len() - 1;
let message = match rest {
0 => format!("vfmt: {first}"),
_ => format!("vfmt: {first} (and {rest} more — see the vfmt log)"),
0 => format!("lucisv: {first}"),
_ => format!("lucisv: {first} (and {rest} more — see the lucisv log)"),
};
self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message });
}
/// Replace a buffer's text, re-arming its `vfmt.toml` warning: the user
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
/// has moved on, and a config problem is worth saying once more.
fn set_document(&mut self, uri: Uri, text: String) {
self.config_warnings.remove(&uri);
@@ -639,7 +642,7 @@ impl Failure {
}
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
Failure::Request(message) => {
(lsp_server::ErrorCode::RequestFailed as i32, format!("vfmt: {message}"))
(lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}"))
}
};
Response::new_err(id, code, message)
@@ -681,7 +684,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_watch_{}_{name}", std::process::id()));
.join(format!("lucisv_server_watch_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -808,7 +811,7 @@ mod tests {
requests[0].1,
serde_json::json!({
"registrations": [{
"id": "vfmt-watched-files-0",
"id": "lucisv-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": {
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
@@ -823,7 +826,7 @@ mod tests {
let tree = Tree::new("registerfilelist");
tree.package("rtl/a.sv", "a");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let session = Session::new(vec![tree.path.clone()], true);
let requests = session.requests();
@@ -838,9 +841,9 @@ mod tests {
);
}
/// A `vfmt.filelist` push, in the shape a client sends it.
/// A `lucisv.filelist` push, in the shape a client sends it.
fn filelist_push(path: &str) -> Value {
serde_json::json!({ "settings": { "vfmt": { "filelist": path } } })
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
}
#[test]
@@ -860,10 +863,10 @@ mod tests {
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
assert_eq!(requests[0].1["unregisterations"][0]["id"], "vfmt-watched-files-0");
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-0");
assert_eq!(requests[1].0, RegisterCapability::METHOD);
let registration = &requests[1].1["registrations"][0];
assert_eq!(registration["id"], "vfmt-watched-files-1", "a fresh id");
assert_eq!(registration["id"], "lucisv-watched-files-1", "a fresh id");
assert_eq!(
registration["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("files.f").to_str().expect("utf-8").to_string()
@@ -877,7 +880,7 @@ mod tests {
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
let requests = session.requests();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert_eq!(requests[0].1["unregisterations"][0]["id"], "vfmt-watched-files-1");
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-1");
assert_eq!(
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
tree.path.join("other.f").to_str().expect("utf-8").to_string()
@@ -947,7 +950,7 @@ mod tests {
tree.package("rtl/a.sv", "a");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
@@ -1010,7 +1013,7 @@ mod tests {
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.write("files.f", "rtl/a.sv\n");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut session = Session::new(vec![tree.path.clone()], true);
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
@@ -1,8 +1,8 @@
//! The `vfmt.*` settings a client pushes over `workspace/didChangeConfiguration`.
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`.
//!
//! These are the editor's copy of what `vfmt.toml` carries — the same keys, so
//! These are the editor's copy of what `lucisv.toml` carries — the same keys, so
//! a user with no config file in the tree can still say "indent 4" from their
//! editor's settings UI. The three formatting ones never *beat* a `vfmt.toml`:
//! editor's settings UI. The three formatting ones never *beat* a `lucisv.toml`:
//! see the precedence ladder in `format::settings_for` and
//! `docs/features/editor-settings/README.md`. `filelist` is the exception, and
//! deliberately so — it names a *scope* rather than a style, and the person
@@ -18,37 +18,37 @@ use serde_json::Value;
/// Accepted `line-length`, and accepted `indent`.
///
/// Duplicated from `vfmt_core::config`'s parser, which spells the same bounds
/// Duplicated from `lucisv_core::config`'s parser, which spells the same bounds
/// inline in `parse_entry` and exports no constant for them. A client's value
/// must be exactly as acceptable as the same value written in a `vfmt.toml`,
/// must be exactly as acceptable as the same value written in a `lucisv.toml`,
/// or the two front ends would disagree about what is valid;
/// `the_accepted_ranges_are_the_ones_vfmt_toml_accepts` asserts that against
/// `the_accepted_ranges_are_the_ones_lucisv_toml_accepts` asserts that against
/// the real parser rather than against a copied number.
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// The `vfmt.*` settings in force, after validation. Every field is "no
/// The `lucisv.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ClientSettings {
/// `vfmt.lineLength`.
/// `lucisv.lineLength`.
pub line_length: Option<usize>,
/// `vfmt.indent`.
/// `lucisv.indent`.
pub indent: Option<usize>,
/// `vfmt.exclude`, appended to the config's excludes in the workspace scan.
/// `lucisv.exclude`, appended to the config's excludes in the workspace scan.
pub exclude: Vec<String>,
/// `vfmt.filelist`: the `.f` file that defines the index's scope, absolute
/// `lucisv.filelist`: the `.f` file that defines the index's scope, absolute
/// or relative to the workspace root. Empty means "unset", which is what
/// the VS Code default is — see `docs/features/filelist/README.md`.
pub filelist: Option<String>,
/// `vfmt.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
}
/// Read the `vfmt` section out of a `workspace/didChangeConfiguration` payload.
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
/// the settings UI, but the notification is just JSON on a socket, and other
@@ -59,17 +59,17 @@ pub struct ClientSettings {
/// `tabSize`, for the same reason: silently honouring half of a nonsensical
/// request is worse than ignoring it.
pub fn from_payload(settings: &Value) -> ClientSettings {
// `{"settings": {"vfmt": {...}}}` — the shape
// `synchronize.configurationSection: 'vfmt'` produces. A payload without
// `{"settings": {"lucisv": {...}}}` — the shape
// `synchronize.configurationSection: 'lucisv'` produces. A payload without
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(vfmt) = settings.get("vfmt") else { return ClientSettings::default() };
let Some(lucisv) = settings.get("lucisv") else { return ClientSettings::default() };
ClientSettings {
line_length: bounded(vfmt.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(vfmt.get("indent"), INDENT_RANGE),
exclude: strings(vfmt.get("exclude")),
filelist: path(vfmt.get("filelist")),
inline_templates: flag(vfmt.get("inlineTemplates")),
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
inline_templates: flag(lucisv.get("inlineTemplates")),
}
}
@@ -81,7 +81,7 @@ fn flag(value: Option<&Value>) -> Option<bool> {
value?.as_bool()
}
/// A non-empty JSON string, or nothing. The empty string is `vfmt.filelist`'s
/// A non-empty JSON string, or nothing. The empty string is `lucisv.filelist`'s
/// default and means "no filelist", not "the filelist named by the empty
/// path"; anything that is not a string is dropped like every other
/// wrong-typed value here.
@@ -120,13 +120,13 @@ mod tests {
}
/// The payload shape `vscode-languageclient` actually sends for
/// `synchronize.configurationSection: 'vfmt'` — the whole section, with
/// `synchronize.configurationSection: 'lucisv'` — the whole section, with
/// every key present at its default. Verified against the real library in
/// `node_modules`; see the feature README's Handshakes.
fn vscode_payload(line_length: Value, indent: Value, exclude: Value) -> Value {
json!({
"vfmt": {
"serverPath": "vfmt-server",
"lucisv": {
"serverPath": "lucisv-server",
"rainbowBeginEnd": true,
"lineLength": line_length,
"indent": indent,
@@ -139,9 +139,9 @@ mod tests {
#[test]
fn a_filelist_is_taken_when_it_names_something() {
let found = settings(json!({ "vfmt": { "filelist": "rtl/files.f" } }));
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
assert_eq!(found.filelist.as_deref(), Some("rtl/files.f"));
let found = settings(json!({ "vfmt": { "filelist": " /abs/files.f " } }));
let found = settings(json!({ "lucisv": { "filelist": " /abs/files.f " } }));
assert_eq!(
found.filelist.as_deref(),
Some("/abs/files.f"),
@@ -154,10 +154,10 @@ mod tests {
// `""` is the setting's own default: it must mean "no filelist", not
// "a filelist whose path is empty".
for bad in [json!(""), json!(" "), json!(null), json!(3), json!(["a.f"]), json!(true)] {
let found = settings(json!({ "vfmt": { "filelist": bad } }));
let found = settings(json!({ "lucisv": { "filelist": bad } }));
assert_eq!(found.filelist, None, "filelist {bad} must be ignored");
}
assert_eq!(settings(json!({ "vfmt": {} })).filelist, None, "and so must its absence");
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
}
#[test]
@@ -177,14 +177,14 @@ mod tests {
#[test]
fn inline_templates_is_a_boolean_and_nothing_else() {
let found = settings(json!({ "vfmt": { "inlineTemplates": false } }));
let found = settings(json!({ "lucisv": { "inlineTemplates": false } }));
assert_eq!(found.inline_templates, Some(false));
let found = settings(json!({ "vfmt": { "inlineTemplates": true } }));
let found = settings(json!({ "lucisv": { "inlineTemplates": true } }));
assert_eq!(found.inline_templates, Some(true));
// Absence is not `false`: the feature is on unless a client says no.
assert_eq!(settings(json!({ "vfmt": {} })).inline_templates, None);
assert_eq!(settings(json!({ "lucisv": {} })).inline_templates, None);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "vfmt": { "inlineTemplates": bad } }));
let found = settings(json!({ "lucisv": { "inlineTemplates": bad } }));
assert_eq!(found.inline_templates, None, "inlineTemplates {bad} must be ignored");
}
}
@@ -208,7 +208,7 @@ mod tests {
fn a_missing_key_is_not_an_opinion() {
// A hand-written Neovim `settings` table names only what it cares
// about; the keys it leaves out must stay silent, not become 0.
let found = settings(json!({ "vfmt": { "indent": 4 } }));
let found = settings(json!({ "lucisv": { "indent": 4 } }));
assert_eq!(found.indent, Some(4));
assert_eq!(found.line_length, None);
assert!(found.exclude.is_empty());
@@ -217,27 +217,27 @@ mod tests {
#[test]
fn out_of_range_numbers_are_ignored() {
for bad in [json!(0), json!(9), json!(100), json!(-1)] {
let found = settings(json!({ "vfmt": { "indent": bad } }));
let found = settings(json!({ "lucisv": { "indent": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
}
for bad in [json!(0), json!(39), json!(401), json!(-40)] {
let found = settings(json!({ "vfmt": { "lineLength": bad } }));
let found = settings(json!({ "lucisv": { "lineLength": bad } }));
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
}
#[test]
fn the_range_edges_are_accepted() {
let found = settings(json!({ "vfmt": { "indent": 1, "lineLength": 40 } }));
let found = settings(json!({ "lucisv": { "indent": 1, "lineLength": 40 } }));
assert_eq!((found.indent, found.line_length), (Some(1), Some(40)));
let found = settings(json!({ "vfmt": { "indent": 8, "lineLength": 400 } }));
let found = settings(json!({ "lucisv": { "indent": 8, "lineLength": 400 } }));
assert_eq!((found.indent, found.line_length), (Some(8), Some(400)));
}
#[test]
fn wrong_types_are_ignored_rather_than_coerced() {
for bad in [json!("4"), json!(true), json!([4]), json!({ "n": 4 }), json!(4.5)] {
let found = settings(json!({ "vfmt": { "indent": bad, "lineLength": bad } }));
let found = settings(json!({ "lucisv": { "indent": bad, "lineLength": bad } }));
assert_eq!(found.indent, None, "indent {bad} must be ignored");
assert_eq!(found.line_length, None, "lineLength {bad} must be ignored");
}
@@ -245,22 +245,22 @@ mod tests {
#[test]
fn an_exclude_that_is_not_a_list_of_strings_contributes_nothing() {
assert!(settings(json!({ "vfmt": { "exclude": "vendor" } })).exclude.is_empty());
assert!(settings(json!({ "vfmt": { "exclude": 3 } })).exclude.is_empty());
assert!(settings(json!({ "vfmt": { "exclude": null } })).exclude.is_empty());
assert!(settings(json!({ "lucisv": { "exclude": "vendor" } })).exclude.is_empty());
assert!(settings(json!({ "lucisv": { "exclude": 3 } })).exclude.is_empty());
assert!(settings(json!({ "lucisv": { "exclude": null } })).exclude.is_empty());
// A mixed array keeps the strings and drops the rest.
let found = settings(json!({ "vfmt": { "exclude": ["ok", 3, null, "fine"] } }));
let found = settings(json!({ "lucisv": { "exclude": ["ok", 3, null, "fine"] } }));
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
}
#[test]
fn the_accepted_ranges_are_the_ones_vfmt_toml_accepts() {
// The bounds above are copied from `vfmt_core::config`, which exports
fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() {
// The bounds above are copied from `lucisv_core::config`, which exports
// no constant for them. Rather than trust the copy, ask the real
// parser: every edge this module accepts must parse, and every value
// it rejects must be rejected there too. If `vfmt.toml` ever widens a
// it rejects must be rejected there too. If `lucisv.toml` ever widens a
// range, this fails and says so.
let ok = |text: &str| vfmt_core::config::parse(text).is_ok();
let ok = |text: &str| lucisv_core::config::parse(text).is_ok();
assert!(ok("indent = 1") && ok("indent = 8"), "the indent edges");
assert!(!ok("indent = 0") && !ok("indent = 9"), "just outside indent");
assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges");
@@ -296,7 +296,7 @@ endmodule
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_signature_{}_{name}", std::process::id()));
.join(format!("lucisv_server_signature_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -1,6 +1,6 @@
//! What the server remembers: one analysis per open buffer, one index for the
//! workspace. The invalidation rules are in
//! `docs/features/vfmt-server/README.md`; the short version is that a buffer's
//! `docs/features/lucisv-server/README.md`; the short version is that a buffer's
//! analysis is rebuilt on every change and the index only on save.
use std::collections::HashMap;
@@ -14,8 +14,8 @@ use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
use vfmt_core::config::Discovery;
use vfmt_core::walk::{collect_files, EXTENSIONS};
use lucisv_core::config::Discovery;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use crate::candidates::Candidates;
use crate::convert::Positions;
@@ -113,7 +113,7 @@ pub struct Workspace {
/// What every in-scope file `` `include``s, and the `+incdir+`s an
/// include is looked for in. Rebuilt with `index`, from the same list.
includes: IncludeGraph,
/// The last `vfmt.*` settings a client pushed. Default until it does.
/// The last `lucisv.*` settings a client pushed. Default until it does.
client: ClientSettings,
}
@@ -148,7 +148,7 @@ impl Workspace {
!self.roots.is_empty()
}
/// The `vfmt.*` settings in force, for the resolution points in
/// The `lucisv.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
@@ -252,7 +252,7 @@ impl Workspace {
/// The files the index covers, and what the user should be told about how
/// they were chosen. The scope ladder, highest first:
///
/// 1. **A filelist** — `vfmt.filelist`, else a `filelist` key in the
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
/// config governing a workspace root. It names *exactly* the files to
/// index; the project said so, and guessing past it would defeat the
/// point of having one.
@@ -272,7 +272,7 @@ impl Workspace {
let Some(path) = self.filelist_path() else {
return Scope { files: self.default_files(), ..Default::default() };
};
match vfmt_core::filelist::read(&path) {
match lucisv_core::filelist::read(&path) {
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
Err(problem) => Scope {
files: self.default_files(),
@@ -298,7 +298,7 @@ impl Workspace {
});
}
let mut discovery = Discovery::new(true);
// A broken `vfmt.toml` names no filelist, exactly as it contributes no
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
// excludes below: the user hears about it when they format.
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
}
@@ -340,7 +340,7 @@ impl Workspace {
/// Every source file under the roots, found by the CLI's own walk: the
/// same extensions, the same `.gitignore` handling, and the `exclude`
/// patterns of the config governing each root. What `vfmt` skips, the
/// patterns of the config governing each root. What `lucisv` skips, the
/// index skips.
fn walked_files(&self) -> Vec<PathBuf> {
let mut discovery = Discovery::new(true);
@@ -349,13 +349,13 @@ impl Workspace {
// The walk names its inputs as strings; every root came from a
// `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `vfmt.toml` must not stop the server from indexing: an
// 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(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `vfmt.exclude` is *appended*, never substituted —
// 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.
@@ -419,7 +419,7 @@ mod tests {
#[test]
fn an_open_buffer_overrides_disk_in_the_index() {
let dir = std::env::temp_dir().join(format!("vfmt_server_state_{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
let path = dir.join("pkg.sv");
@@ -447,7 +447,7 @@ mod tests {
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("vfmt_server_scan_{}_{name}", std::process::id()));
.join(format!("lucisv_server_scan_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
@@ -492,14 +492,14 @@ mod tests {
#[test]
fn the_scan_honours_the_root_configs_excludes() {
let tree = Tree::new("excludes");
tree.write("vfmt.toml", "exclude = [\"vendor\"]\n");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "vfmt.toml excludes apply");
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
}
#[test]
@@ -507,7 +507,7 @@ mod tests {
// Exit 2 is the CLI's answer to a broken config; a server that indexed
// nothing because of a typo would look simply broken instead.
let tree = Tree::new("brokencfg");
tree.write("vfmt.toml", "bogus = 1\n");
tree.write("lucisv.toml", "bogus = 1\n");
tree.package("kept.sv", "kept");
let mut ws = Workspace::default();
@@ -515,7 +515,7 @@ mod tests {
assert_eq!(ws.index().member("kept", "K").len(), 1);
}
/// `vfmt.exclude` as a client would push it.
/// `lucisv.exclude` as a client would push it.
fn excluding(patterns: &[&str]) -> ClientSettings {
ClientSettings {
exclude: patterns.iter().map(|p| p.to_string()).collect(),
@@ -541,11 +541,11 @@ mod tests {
#[test]
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
// The failure this guards: a user setting `vfmt.exclude` in their
// The failure this guards: a user setting `lucisv.exclude` in their
// editor and thereby putting the project's vendored code — which the
// checked-in `vfmt.toml` excludes — back into the index for them only.
// checked-in `lucisv.toml` excludes — back into the index for them only.
let tree = Tree::new("bothexcludes");
tree.write("vfmt.toml", "exclude = [\"vendor\"]\n");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
tree.package("scratch/wip.sv", "scratch_pkg");
@@ -602,7 +602,7 @@ mod tests {
assert_eq!(ws.client_settings().line_length, Some(120));
}
/// `vfmt.filelist` as a client would push it.
/// `lucisv.filelist` as a client would push it.
fn using_filelist(path: &str) -> ClientSettings {
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
}
@@ -631,7 +631,7 @@ mod tests {
// The point of a filelist: a file sitting in the tree that the project
// does not build is not indexed, however much the walk would find it.
let tree = filelist_tree("filelistkey");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
let warnings = ws.open_roots(vec![tree.path.clone()]);
@@ -642,7 +642,7 @@ mod tests {
#[test]
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
let tree = filelist_tree("filelistsetting");
tree.write("vfmt.toml", "filelist = \"files.f\"\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
tree.write("other.f", "rtl/unlisted.sv\n");
// Relative: against the workspace root, not the current directory.
@@ -171,7 +171,7 @@ mod tests {
#[test]
fn workspace_symbols_find_declarations_across_files() {
let dir = std::env::temp_dir().join(format!("vfmt_server_wsym_{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_server_wsym_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("a.sv"), "module alpha;\nendmodule\n").expect("write");
@@ -426,11 +426,11 @@ mod tests {
/// be handed to a whole-file parser.
fn planted(gate: Gate, text: &str) -> Vec<String> {
let statement =
format!("module vfmt_probe;\n always @(*) begin\n{text}\n end\nendmodule\n");
format!("module lucisv_probe;\n always @(*) begin\n{text}\n end\nendmodule\n");
let tail = format!(
"module vfmt_probe;\n always @(*) begin\n if (1) begin\n end\n{text}\n end\nendmodule\n"
"module lucisv_probe;\n always @(*) begin\n if (1) begin\n end\n{text}\n end\nendmodule\n"
);
let item = format!("module vfmt_probe;\n{text}\nendmodule\n");
let item = format!("module lucisv_probe;\n{text}\nendmodule\n");
match gate {
Gate::Statement => vec![statement],
Gate::ElseTail => vec![tail],
@@ -2,7 +2,7 @@
//!
//! Classification comes from the lexer's token stream, refined for plain
//! identifiers by `vlog_semantic`. The full mapping table is in
//! `docs/features/vfmt-server/README.md`.
//! `docs/features/lucisv-server/README.md`.
use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
use vlog_parser::token::{Token, TokenKind};
File renamed without changes.
@@ -1,4 +1,4 @@
//! `workspace/didChangeWatchedFiles`: the index's answer to changes vfmt never
//! `workspace/didChangeWatchedFiles`: the index's answer to changes lucisv never
//! saw an editor make.
//!
//! Until this, the index was rebuilt on save and (with no workspace root) on
@@ -16,13 +16,13 @@ use lsp_types::{
InitializeParams, Registration, Unregistration,
};
use vfmt_core::walk::EXTENSIONS;
use lucisv_core::walk::EXTENSIONS;
use crate::uri::uri_to_path;
/// Every source file the workspace walk would take, in one glob.
///
/// Deliberately the same four extensions as `vfmt_core::walk::EXTENSIONS` and
/// Deliberately the same four extensions as `lucisv_core::walk::EXTENSIONS` and
/// nothing else: a watcher wide enough to cover a build directory or a
/// `target/` tree would hand us thousands of events that cannot change the
/// index. `pinned_to_the_extensions_the_walk_takes` asserts the two agree.
@@ -48,7 +48,7 @@ pub fn dynamic_registration(params: &InitializeParams) -> bool {
/// plus the configured filelist's own path when there is one.
///
/// `serial` numbers the registration so a later one can unregister it by name;
/// a re-registration is what a change of `vfmt.filelist` needs, because the
/// a re-registration is what a change of `lucisv.filelist` needs, because the
/// path being watched is part of the registration itself.
///
/// No `kind` is set on either watcher, which the protocol defines as
@@ -93,7 +93,7 @@ fn watcher(pattern: String) -> FileSystemWatcher {
}
fn registration_id(serial: u32) -> String {
format!("vfmt-watched-files-{serial}")
format!("lucisv-watched-files-{serial}")
}
/// Whether a notification's events touch anything the index reads.
@@ -162,7 +162,7 @@ mod tests {
assert_eq!(
value,
serde_json::json!({
"id": "vfmt-watched-files-0",
"id": "lucisv-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }] },
})
@@ -176,7 +176,7 @@ mod tests {
assert_eq!(
value,
serde_json::json!({
"id": "vfmt-watched-files-2",
"id": "lucisv-watched-files-2",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [
{ "globPattern": "**/*.{v,vh,sv,svh}" },
@@ -196,7 +196,7 @@ mod tests {
fn an_unregistration_names_the_same_id_and_method() {
let registration = registration(7, None);
let undo = unregistration(registration.id.clone());
assert_eq!(undo.id, "vfmt-watched-files-7");
assert_eq!(undo.id, "lucisv-watched-files-7");
assert_eq!(undo.method, registration.method);
}
@@ -52,7 +52,7 @@ fn read_message(input: &mut impl BufRead) -> Option<serde_json::Value> {
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vfmt_server_e2e_{}_{name}", std::process::id()));
let dir = std::env::temp_dir().join(format!("lucisv_server_e2e_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
dir
@@ -64,7 +64,7 @@ fn temp_dir(name: &str) -> PathBuf {
/// processes the messages in order and exits on `exit`, so stdout closes and
/// the read terminates on its own.
fn talk(session: &str) -> Vec<serde_json::Value> {
let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server"))
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -79,7 +79,7 @@ fn talk(session: &str) -> Vec<serde_json::Value> {
}
/// An `initialize` + `didOpen` + one `textDocument/formatting` + shutdown
/// session against a scratch workspace holding `config` as its `vfmt.toml`.
/// session against a scratch workspace holding `config` as its `lucisv.toml`.
/// The client asks for a 2-space indent, which is what an editor default
/// looks like.
fn format_session(dir: &Path, file: &Path, ids: &[u32]) -> Vec<serde_json::Value> {
@@ -120,9 +120,9 @@ fn new_text(messages: &[serde_json::Value], id: u32) -> String {
const UNFORMATTED: &str = "module m;\nwire a;\nendmodule\n";
#[test]
fn a_vfmt_toml_governs_formatting_over_the_editors_tab_size() {
fn a_lucisv_toml_governs_formatting_over_the_editors_tab_size() {
let dir = temp_dir("config");
std::fs::write(dir.join("vfmt.toml"), "indent = 4\n").expect("write config");
std::fs::write(dir.join("lucisv.toml"), "indent = 4\n").expect("write config");
let file = dir.join("m.sv");
std::fs::write(&file, UNFORMATTED).expect("write");
@@ -141,9 +141,9 @@ fn a_vfmt_toml_governs_formatting_over_the_editors_tab_size() {
}
#[test]
fn a_broken_vfmt_toml_warns_once_and_still_formats() {
fn a_broken_lucisv_toml_warns_once_and_still_formats() {
let dir = temp_dir("brokenconfig");
std::fs::write(dir.join("vfmt.toml"), "indent = 4\nbogus = 1\n").expect("write config");
std::fs::write(dir.join("lucisv.toml"), "indent = 4\nbogus = 1\n").expect("write config");
let file = dir.join("m.sv");
std::fs::write(&file, UNFORMATTED).expect("write");
@@ -163,7 +163,7 @@ fn a_broken_vfmt_toml_warns_once_and_still_formats() {
assert_eq!(warnings[0]["params"]["type"], 2, "a warning, not an error");
let text = warnings[0]["params"]["message"].as_str().expect("a message");
assert!(text.contains("unknown key `bogus`"), "{text}");
assert!(text.contains("vfmt.toml:2"), "the message names file and line: {text}");
assert!(text.contains("lucisv.toml:2"), "the message names file and line: {text}");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -196,7 +196,7 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
)),
// "Select line 3", the way an editor sends it: end at the start of 4.
request(2, 2, 0, 3, 0),
// A cursor on `endmodule`, which is already written as vfmt writes it.
// A cursor on `endmodule`, which is already written as lucisv writes it.
request(3, 4, 0, 4, 9),
request(4, 0, 0, 99, 0),
// A cursor on the emoji comment: a leading comment belongs to its
@@ -265,7 +265,7 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
)),
// And the fix-on-save request an editor sends: one kind only.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.vfmt"]}}}}}}"#
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.lucisv"]}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
@@ -279,7 +279,7 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
let kinds = &initialize["result"]["capabilities"]["codeActionProvider"]["codeActionKinds"];
let kinds = kinds.as_array().expect("the kinds are listed, not just `true`");
assert!(kinds.iter().any(|k| k == "quickfix"), "{kinds:#?}");
assert!(kinds.iter().any(|k| k == "source.fixAll.vfmt"), "{kinds:#?}");
assert!(kinds.iter().any(|k| k == "source.fixAll.lucisv"), "{kinds:#?}");
// 2. Exactly one publish for this version, carrying both lint findings.
let published: Vec<_> =
@@ -292,7 +292,7 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}");
for diagnostic in diagnostics {
assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning");
assert_eq!(diagnostic["source"], "vfmt");
assert_eq!(diagnostic["source"], "lucisv");
}
// 3. Two quick fixes and one fixAll, and the quick fixes name the finding.
@@ -301,7 +301,7 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
let quick: Vec<_> = actions.iter().filter(|a| a["kind"] == "quickfix").collect();
assert_eq!(quick.len(), 2, "{actions:#?}");
assert_eq!(quick[0]["diagnostics"].as_array().expect("its diagnostic").len(), 1);
let all: Vec<_> = actions.iter().filter(|a| a["kind"] == "source.fixAll.vfmt").collect();
let all: Vec<_> = actions.iter().filter(|a| a["kind"] == "source.fixAll.lucisv").collect();
assert_eq!(all.len(), 1, "{actions:#?}");
// 4. The filtered request returns the fixAll action and nothing else, and
@@ -322,23 +322,24 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
/// A fenced tab and an unfenced one, in a file whose name matches its module.
/// One pass converges here (no two fixes want the same bytes), which is what
/// makes the server's single-pass `fixAll` comparable to the CLI's loop.
const FENCED: &str = "module fenced;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
const FENCED: &str =
"module fenced;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
/// The `vfmt` CLI binary, built beside this crate's own.
/// The `lucisv` CLI binary, built beside this crate's own.
///
/// Cargo names no env var for another package's binary, so it is found by
/// path. `cargo test --workspace` — the gate this test belongs to — always
/// builds it; `cargo test -p vfmt_server` alone may not, and the test says so
/// builds it; `cargo test -p lucisv_server` alone may not, and the test says so
/// and passes rather than failing for a reason that is not about the server.
fn vfmt_binary() -> Option<PathBuf> {
let path = Path::new(env!("CARGO_BIN_EXE_vfmt-server")).with_file_name("vfmt");
fn lucisv_binary() -> Option<PathBuf> {
let path = Path::new(env!("CARGO_BIN_EXE_lucisv-server")).with_file_name("lucisv");
path.is_file().then_some(path)
}
#[test]
fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
let Some(vfmt) = vfmt_binary() else {
eprintln!("skipped: the `vfmt` binary is not built next to `vfmt-server`");
fn fix_all_edits_exactly_what_lucisv_check_fix_edits_inside_a_fence() {
let Some(lucisv) = lucisv_binary() else {
eprintln!("skipped: the `lucisv` binary is not built next to `lucisv-server`");
return;
};
let dir = temp_dir("fence");
@@ -358,7 +359,7 @@ fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
)),
// Fix-on-save, then a cursor sitting on the fenced tab.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":5,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.vfmt"]}}}}}}"#
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":5,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.lucisv"]}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":2,"character":0}},"end":{{"line":2,"character":1}}}},"context":{{"diagnostics":[]}}}}}}"#
@@ -386,7 +387,7 @@ fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
"no lightbulb inside a fence: {at_fence:#?}"
);
// And `fixAll` writes exactly what `vfmt check --fix` writes.
// And `fixAll` writes exactly what `lucisv check --fix` writes.
let fix_all = messages.iter().find(|m| m["id"] == 2).expect("fixAll response");
let fix_all = fix_all["result"].as_array().expect("an array");
assert_eq!(fix_all.len(), 1, "only what was asked for: {fix_all:#?}");
@@ -395,14 +396,14 @@ fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
let fixed = edits[0]["newText"].as_str().expect("newText").to_string();
let cli = dir.join("cli.sv");
std::fs::write(&cli, FENCED).expect("write");
let status = Command::new(&vfmt)
let status = Command::new(&lucisv)
.arg("check")
.arg("--fix")
.arg(&cli)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("the vfmt binary runs");
.expect("the lucisv binary runs");
// Two findings remain (the fenced tab is reported and unfixed), so the
// CLI exits 1 — the documented "reported, never auto-fixed" contract.
assert_eq!(status.code(), Some(1), "violations remain, and that is correct");
@@ -459,7 +460,7 @@ fn the_binary_serves_a_whole_session_over_stdio() {
assert_eq!(capabilities["documentFormattingProvider"], true);
assert_eq!(capabilities["definitionProvider"], true);
assert!(capabilities["semanticTokensProvider"].is_object());
assert_eq!(initialize["result"]["serverInfo"]["name"], "vfmt-server");
assert_eq!(initialize["result"]["serverInfo"]["name"], "lucisv-server");
// 2. Diagnostics were pushed for the broken buffer.
let published = messages
@@ -470,7 +471,7 @@ fn the_binary_serves_a_whole_session_over_stdio() {
let diagnostics = published["params"]["diagnostics"].as_array().expect("an array");
assert_eq!(diagnostics.len(), 1, "one error for `wire ;`");
assert_eq!(diagnostics[0]["severity"], 1, "an error");
assert_eq!(diagnostics[0]["source"], "vfmt");
assert_eq!(diagnostics[0]["source"], "lucisv");
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the `wire ;` line");
// 3. Definition jumped to the declaration, in the same file.
@@ -543,7 +544,7 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
// The rainbow's data source — a custom method, so this is the only
// thing that proves the request loop routes it at all.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"vfmt/scopePairs","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
r#"{{"jsonrpc":"2.0","id":6,"method":"lucisv/scopePairs","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
// The same request against a balanced buffer: `unmatched` has to come
// back present and empty, because that is what clears the extension's
@@ -553,7 +554,7 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
serde_json::to_string(BALANCED).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"vfmt/scopePairs","params":{{"textDocument":{{"uri":"{clean_uri}"}}}}}}"#
r#"{{"jsonrpc":"2.0","id":7,"method":"lucisv/scopePairs","params":{{"textDocument":{{"uri":"{clean_uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
@@ -637,7 +638,7 @@ fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() {
assert_eq!(warning["message"], "`begin` has no matching `end` — is an `end` missing?");
assert_eq!(warning["range"]["start"]["line"], 1, "the `initial begin`");
assert_eq!(warning["range"]["start"]["character"], 10);
assert_eq!(warning["source"], "vfmt");
assert_eq!(warning["source"], "lucisv");
assert!(
diagnostics.iter().any(|d| d["severity"] == 1),
"the parse error it explains is still there"
@@ -666,7 +667,7 @@ fn pushed_settings_reach_the_formatter_and_can_change_mid_session() {
};
let push = |indent: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"serverPath":"vfmt-server","rainbowBeginEnd":true,"lineLength":null,"indent":{indent},"exclude":[]}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"serverPath":"lucisv-server","rainbowBeginEnd":true,"lineLength":null,"indent":{indent},"exclude":[]}}}}}}}}"#
))
};
let session = [
@@ -690,7 +691,7 @@ fn pushed_settings_reach_the_formatter_and_can_change_mid_session() {
push("null"),
format(5),
// A payload that is nonsense must be ignored, not honoured by halves.
frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"vfmt":{"indent":"four","lineLength":9999}}}}"#),
frame(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"indent":"four","lineLength":9999}}}}"#),
format(6),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
@@ -743,7 +744,7 @@ fn a_pushed_exclude_rebuilds_the_index_mid_session() {
};
let exclude = |patterns: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"exclude":{patterns}}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"exclude":{patterns}}}}}}}}}"#
))
};
// An open buffer, so the *republish* half of `reindex()` has somewhere to
@@ -826,7 +827,7 @@ fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() {
};
let filelist = |path: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"filelist":"{path}"}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"filelist":"{path}"}}}}}}}}"#
))
};
let session = [
@@ -1068,22 +1069,22 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"#
)),
// `vfmt.propagatePorts` at the same place, through the command.
// `lucisv.propagatePorts` at the same place, through the command.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"vfmt.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"#
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"#
)),
// `vfmt.addPort` — the one that needs text nobody can click.
// `lucisv.addPort` — the one that needs text nobody can click.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{top_uri}","sub","input logic cfg"]}}}}"#
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{top_uri}","sub","input logic cfg"]}}}}"#
)),
// ...and a declaration that is not one is refused with a sentence.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{top_uri}","sub","wire"]}}}}"#
r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{top_uri}","sub","wire"]}}}}"#
)),
// ...and a port that would land inside an `ifdef arm is refused, over
// the wire, not only in the crate's own tests.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":6,"method":"workspace/executeCommand","params":{{"command":"vfmt.addPort","arguments":["{cond_uri}","cond","input logic cfg"]}}}}"#
r#"{{"jsonrpc":"2.0","id":6,"method":"workspace/executeCommand","params":{{"command":"lucisv.addPort","arguments":["{cond_uri}","cond","input logic cfg"]}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
@@ -1098,22 +1099,22 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() {
let commands = capabilities["executeCommandProvider"]["commands"]
.as_array()
.unwrap_or_else(|| panic!("no executeCommandProvider in {capabilities:#?}"));
assert!(commands.iter().any(|c| c == "vfmt.addPort"), "{commands:#?}");
assert!(commands.iter().any(|c| c == "vfmt.removePort"), "{commands:#?}");
assert!(commands.iter().any(|c| c == "vfmt.propagatePorts"), "{commands:#?}");
assert!(commands.iter().any(|c| c == "lucisv.addPort"), "{commands:#?}");
assert!(commands.iter().any(|c| c == "lucisv.removePort"), "{commands:#?}");
assert!(commands.iter().any(|c| c == "lucisv.propagatePorts"), "{commands:#?}");
let kinds = capabilities["codeActionProvider"]["codeActionKinds"]
.as_array()
.expect("the kinds are listed");
assert!(kinds.iter().any(|k| k == "refactor.rewrite.vfmt.ports"), "{kinds:#?}");
assert!(kinds.iter().any(|k| k == "refactor.rewrite.lucisv.ports"), "{kinds:#?}");
// 2. The code action carries its own edit, ready to apply.
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
let offered = actions["result"].as_array().expect("an array of actions");
let port_action = offered
.iter()
.find(|a| a["kind"] == "refactor.rewrite.vfmt.ports")
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
assert_eq!(port_action["title"], "vfmt: connect 1 missing port");
assert_eq!(port_action["title"], "lucisv: connect 1 missing port");
let edits = port_action["edit"]["changes"][&top_uri].as_array().expect("one file's edits");
assert_eq!(edits.len(), 1);
assert_eq!(edits[0]["newText"], ", .rst(rst)");
@@ -1433,7 +1434,7 @@ fn inline_templates_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `vfmt.inlineTemplates` really suppresses the request handler when pushed
/// `lucisv.inlineTemplates` really suppresses the request handler when pushed
/// over the wire — the link a unit test cannot check, since
/// `inline.rs`'s own tests call `Workspace::set_client_settings` directly
/// rather than going through `workspace/didChangeConfiguration`.
@@ -1453,7 +1454,7 @@ fn the_inline_templates_setting_is_honoured_over_the_wire() {
};
let push = |setting: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"inlineTemplates":{setting}}}}}}}}}"#
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"inlineTemplates":{setting}}}}}}}}}"#
))
};
let session = [
@@ -1874,7 +1875,7 @@ struct Live {
impl Live {
fn start() -> Live {
let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server"))
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -2038,7 +2039,7 @@ endmodule
fn include_links_definition_and_a_reachable_define_round_trip_over_the_wire() {
// What only an e2e test can check: that `documentLinkProvider` is
// advertised in the shape a client reads, that the `+incdir+` from a
// `vfmt.toml`-configured filelist survives the whole trip from disk to a
// `lucisv.toml`-configured filelist survives the whole trip from disk to a
// resolved URI, and that the two capabilities answer the same line.
let dir = temp_dir("include");
std::fs::create_dir_all(dir.join("inc")).expect("inc");
@@ -2054,7 +2055,7 @@ fn include_links_definition_and_a_reachable_define_round_trip_over_the_wire() {
"+incdir+inc\nrtl/top.sv\ninc/defs.svh\nother/elsewhere.svh\n",
)
.expect("write");
std::fs::write(dir.join("vfmt.toml"), "filelist = \"files.f\"\n").expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
@@ -2131,7 +2132,7 @@ fn include_nav_round_trips_in_a_workspace_whose_directory_has_a_space() {
let top = dir.join("top.sv");
std::fs::write(&top, INCLUDE_TOP).expect("write");
std::fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/defs.svh\n").expect("write");
std::fs::write(dir.join("vfmt.toml"), "filelist = \"files.f\"\n").expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
// The URIs the wire actually needs: the directory's own space encoded,
// matching what `path_to_uri` would produce and `uri_to_path` requires.
File renamed without changes.
+1 -1
View File
@@ -3,7 +3,7 @@ name = "vlog_formatter"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Verilog/SystemVerilog formatter engine for vfmt"
description = "Verilog/SystemVerilog formatter engine for lucisv"
[dependencies]
vlog_parser = { path = "../vlog_parser" }
+1 -1
View File
@@ -5,7 +5,7 @@
//! This is Verible's most-loved formatter feature minus the configuration: a
//! group whose author padded any of its lines by four or more excess spaces —
//! or that already sits at one common column — keeps its columns; everything
//! else formats flush, which is what vfmt has always done. The two states are
//! else formats flush, which is what lucisv has always done. The two states are
//! fixed points of each other, which is what lets the convergence check in
//! `verify.rs` stay untouched; the argument is written out in
//! `docs/features/alignment/README.md`.
+25 -25
View File
@@ -7,7 +7,7 @@
//!
//! [`protected_regions`] and [`is_protected`] are the same answer for the
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
//! `vfmt check --fix` and the language server's quick fixes. They live here so
//! `lucisv check --fix` and the language server's quick fixes. They live here so
//! there is one definition of "what is fenced": see
//! `docs/features/shared-fence-filter/README.md`.
@@ -27,12 +27,12 @@ pub enum Fence {
/// The fence a comment spells, if it spells one exactly.
///
/// The match is exact after trimming, not a prefix: a comment that merely
/// starts with a fence (`// vfmt: off-by-one`) is an ordinary comment, because
/// starts with a fence (`// lucisv: off-by-one`) is an ordinary comment, because
/// a fence firing by accident is worse than one that never fires.
pub fn fence_of(text: &str) -> Option<Fence> {
match text.strip_prefix("//")?.trim() {
"verilog_format: off" | "vfmt: off" => Some(Fence::Off),
"verilog_format: on" | "vfmt: on" => Some(Fence::On),
"verilog_format: off" | "lucisv: off" => Some(Fence::Off),
"verilog_format: on" | "lucisv: on" => Some(Fence::On),
_ => None,
}
}
@@ -78,7 +78,7 @@ pub fn region_at(regions: &[Region], pos: usize) -> Option<&Region> {
/// Every byte range in `src` that no tool may edit automatically.
///
/// `off` means hands-off across all of vfmt, not just the layout engine, so
/// `off` means hands-off across all of lucisv, not just the layout engine, so
/// the CLI's `--fix` and the server's quick fixes both ask this question here
/// rather than each answering it themselves. The answer is deliberately
/// wider than [`collect`]'s: it is the union of
@@ -291,49 +291,49 @@ mod tests {
fn both_spellings_and_both_sides_are_fences() {
assert_eq!(fence_of("// verilog_format: off"), Some(Fence::Off));
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
assert_eq!(fence_of("// vfmt: off"), Some(Fence::Off));
assert_eq!(fence_of("// vfmt: on"), Some(Fence::On));
assert_eq!(fence_of("// lucisv: off"), Some(Fence::Off));
assert_eq!(fence_of("// lucisv: on"), Some(Fence::On));
}
#[test]
fn surrounding_whitespace_is_trimmed() {
assert_eq!(fence_of("//vfmt: off"), Some(Fence::Off));
assert_eq!(fence_of("//lucisv: off"), Some(Fence::Off));
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
assert_eq!(fence_of("//\tvfmt: off"), Some(Fence::Off));
assert_eq!(fence_of("// vfmt: on "), Some(Fence::On));
assert_eq!(fence_of("//\tlucisv: off"), Some(Fence::Off));
assert_eq!(fence_of("// lucisv: on "), Some(Fence::On));
}
#[test]
fn anything_else_is_an_ordinary_comment() {
// Trailing text disqualifies a fence: an accidental switch is worse
// than one that never fires.
assert_eq!(fence_of("// vfmt: off (for now)"), None);
assert_eq!(fence_of("// vfmt: off-by-one bug here"), None);
assert_eq!(fence_of("// lucisv: off (for now)"), None);
assert_eq!(fence_of("// lucisv: off-by-one bug here"), None);
// The match is exact, not fuzzy.
assert_eq!(fence_of("// vfmt:off"), None);
assert_eq!(fence_of("// vfmt : off"), None);
assert_eq!(fence_of("// lucisv:off"), None);
assert_eq!(fence_of("// lucisv : off"), None);
assert_eq!(fence_of("// verilog_format off"), None);
assert_eq!(fence_of("// VFMT: OFF"), None);
assert_eq!(fence_of("// LUCISV: OFF"), None);
assert_eq!(fence_of("// verilog_lint: waive x"), None);
// Block comments are not fences.
assert_eq!(fence_of("/* vfmt: off */"), None);
assert_eq!(fence_of("/* lucisv: off */"), None);
assert_eq!(fence_of("/* verilog_format: off */"), None);
assert_eq!(fence_of("// vfmt: off\n// vfmt: on"), None);
assert_eq!(fence_of("// lucisv: off\n// lucisv: on"), None);
assert_eq!(fence_of(""), None);
assert_eq!(fence_of("// off"), None);
}
#[test]
fn a_fence_line_starts_at_its_indentation() {
let src = "module m;\n // vfmt: off\n";
let src = "module m;\n // lucisv: off\n";
let at = src.find("//").expect("fence");
assert_eq!(line_start(src, at), src.find(" //").expect("indent"));
// Not when another comment shares the line.
let src = "module m;\n /* a */ // vfmt: off\n";
let src = "module m;\n /* a */ // lucisv: off\n";
let at = src.find("//").expect("fence");
assert_eq!(line_start(src, at), at);
// At the very start of the file.
assert_eq!(line_start("// vfmt: off\n", 0), 0);
assert_eq!(line_start("// lucisv: off\n", 0), 0);
}
#[test]
@@ -387,7 +387,7 @@ mod tests {
// exercises the scan half it claims not to test (QA find): `\ta = 1;`
// bare at item position does not parse, and `collect` then hangs no
// region on the tree. `wire` declarations parse cleanly.
let src = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
let src = "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
let (parsed, diagnostics) = vlog_parser::parse_source_tolerant(src);
assert!(diagnostics.is_empty(), "the tree must be clean for this test to mean anything");
assert!(!collect(src, &parsed).is_empty(), "the TREE path must find the region");
@@ -402,7 +402,7 @@ mod tests {
fn the_line_scan_backstops_a_file_that_does_not_parse() {
// Error recovery can swallow the structure `collect` hangs a region
// on; the scan still finds it.
let src = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
let src = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\n// lucisv: on\nendmodule\n";
let (parsed, _) = vlog_parser::parse_source_tolerant(src);
assert!(collect(src, &parsed).is_empty(), "the premise: no tree region here");
let tab = src.find("\ta = 1").expect("tab");
@@ -411,7 +411,7 @@ mod tests {
#[test]
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
let src = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\nendmodule\n";
let src = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\nendmodule\n";
let regions = scanned_regions(src);
assert_eq!(regions.len(), 1);
assert_eq!(regions[0].end, src.len());
@@ -419,9 +419,9 @@ mod tests {
#[test]
fn an_ordinary_comment_protects_nothing() {
assert!(scanned_regions("// vfmt: off-by-one\n\ta = 1;\n").is_empty());
assert!(scanned_regions("// lucisv: off-by-one\n\ta = 1;\n").is_empty());
assert!(scanned_regions("// just a note\n\ta = 1;\n").is_empty());
assert!(scanned_regions("// vfmt: on\n\ta = 1;\n").is_empty(), "a stray `on`");
assert!(scanned_regions("// lucisv: on\n\ta = 1;\n").is_empty(), "a stray `on`");
assert!(protected_regions("module m;\n\ta = 1;\nendmodule\n").is_empty());
}
}
+1 -1
View File
@@ -245,7 +245,7 @@ impl<'a> Fmt<'a> {
/// into the middle of a line.
///
/// Like [`Fmt::raw_inline`] it is reproduced byte for byte — the block is
/// a constraint body vfmt does not model, so there is no layout to apply
/// a constraint body lucisv does not model, so there is no layout to apply
/// and re-indenting it would only drift on every pass — but the printer
/// is told about the line breaks inside it, so the expression around it
/// is still measured against the line width correctly.
+1 -1
View File
@@ -263,7 +263,7 @@ fn trim_lines(text: &str) -> String {
/// re-indent the *contents of a string* and still pass this check — masked
/// corruption, and the reason this function exists (QA finding, 2026-08-19:
/// `` `uvm_info("id", "line one\n line two", UVM_LOW) `` had its string
/// rewritten with vfmt exiting 0). Leaving those lines untrimmed makes the
/// rewritten with lucisv exiting 0). Leaving those lines untrimmed makes the
/// comparison byte-exact exactly where bytes are meaningful.
fn trim_lines_outside_strings(text: &str) -> String {
if !text.contains('\n') {
@@ -256,7 +256,7 @@ else $error("line one
endmodule
====
# a property spec far past the line limit is *not* broken: the property
# expression is a grammar vfmt does not model, so it is reproduced as written
# expression is a grammar lucisv does not model, so it is reproduced as written
module m;
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
endmodule
+89 -89
View File
@@ -15,18 +15,18 @@ wire [31:0] bb= 32'h2;
wire c;
endmodule
====
# the vfmt alias fences the same region
# the lucisv alias fences the same region
module m;
// vfmt: off
// lucisv: off
wire [3:0] a;
// vfmt: on
// lucisv: on
wire b;
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire [3:0] a;
// vfmt: on
// lucisv: on
wire b;
endmodule
====
@@ -34,45 +34,45 @@ endmodule
module m;
// verilog_format: off
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
----
module m;
// verilog_format: off
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
====
# a region keeps its own indentation, first line included
module m;
// vfmt: off
// lucisv: off
wire a;
wire b;
// vfmt: on
// lucisv: on
wire c;
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a;
wire b;
// vfmt: on
// lucisv: on
wire c;
endmodule
====
# a fence at the top of the file
// vfmt: off
// lucisv: off
module m; endmodule
// vfmt: on
// lucisv: on
module n;
wire a;
endmodule
----
// vfmt: off
// lucisv: off
module m; endmodule
// vfmt: on
// lucisv: on
module n;
wire a;
endmodule
@@ -81,19 +81,19 @@ endmodule
module m;
wire a;
endmodule
// vfmt: off
// lucisv: off
module n; wire b; endmodule
----
module m;
wire a;
endmodule
// vfmt: off
// lucisv: off
module n; wire b; endmodule
====
# an unmatched off runs to the end of the module body, not past endmodule
module m;
wire a;
// vfmt: off
// lucisv: off
wire b;
wire c;
endmodule
@@ -104,7 +104,7 @@ endmodule
----
module m;
wire a;
// vfmt: off
// lucisv: off
wire b;
wire c;
endmodule
@@ -115,25 +115,25 @@ endmodule
====
# an unmatched off keeps the comment trailing its last item
module m;
// vfmt: off
// lucisv: off
wire a; // note
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a; // note
endmodule
====
# an unmatched off swallows the scope's dangling comments too
module m;
// vfmt: off
// lucisv: off
wire a;
// dangling one
// dangling two
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a;
// dangling one
// dangling two
@@ -141,137 +141,137 @@ endmodule
====
# an on written after endmodule cannot close an off inside the module
module m;
// vfmt: off
// lucisv: off
wire a;
endmodule
// vfmt: on
// lucisv: on
module n;
wire b;
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a;
endmodule
// vfmt: on
// lucisv: on
module n;
wire b;
endmodule
====
# two regions in one file
module m;
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
// vfmt: off
// lucisv: off
wire c;
// vfmt: on
// lucisv: on
wire d;
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
// vfmt: off
// lucisv: off
wire c;
// vfmt: on
// lucisv: on
wire d;
endmodule
====
# a fence with trailing text is not a fence
module m;
// vfmt: off (just for now)
// lucisv: off (just for now)
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
----
module m;
// vfmt: off (just for now)
// lucisv: off (just for now)
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
====
# a block comment is not a fence
module m;
/* vfmt: off */
/* lucisv: off */
wire a;
/* vfmt: on */
/* lucisv: on */
wire b;
endmodule
----
module m;
/* vfmt: off */
/* lucisv: off */
wire a;
/* vfmt: on */
/* lucisv: on */
wire b;
endmodule
====
# a fence written after code on the same line is not a fence
module m;
wire z; // vfmt: off
wire z; // lucisv: off
wire a;
endmodule
----
module m;
wire z; // vfmt: off
wire z; // lucisv: off
wire a;
endmodule
====
# an on with no open off is an ordinary comment
module m;
// vfmt: on
// lucisv: on
wire a;
endmodule
----
module m;
// vfmt: on
// lucisv: on
wire a;
endmodule
====
# a second off inside an open region is just text, the first on closes
module m;
// vfmt: off
// lucisv: off
wire a;
// vfmt: off
// lucisv: off
wire b;
// vfmt: on
// lucisv: on
wire c;
// vfmt: on
// lucisv: on
wire d;
endmodule
----
module m;
// vfmt: off
// lucisv: off
wire a;
// vfmt: off
// lucisv: off
wire b;
// vfmt: on
// lucisv: on
wire c;
// vfmt: on
// lucisv: on
wire d;
endmodule
====
# a region of nothing but comments
module m;
// vfmt: off
// lucisv: off
// +-------+
// | ascii |
// +-------+
// vfmt: on
// lucisv: on
wire a;
endmodule
----
module m;
// vfmt: off
// lucisv: off
// +-------+
// | ascii |
// +-------+
// vfmt: on
// lucisv: on
wire a;
endmodule
====
@@ -280,9 +280,9 @@ module m;
wire z;
// doc for the table
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
----
@@ -290,62 +290,62 @@ module m;
wire z;
// doc for the table
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
endmodule
====
# valid-but-ugly code inside a region is left exactly as written
module m;
// vfmt: off
// lucisv: off
always@(posedge clk)if(en)q<=d;else q <= 1'b0;
assign y = {a,b , c} ;
// vfmt: on
// lucisv: on
assign z = a + b;
endmodule
----
module m;
// vfmt: off
// lucisv: off
always@(posedge clk)if(en)q<=d;else q <= 1'b0;
assign y = {a,b , c} ;
// vfmt: on
// lucisv: on
assign z = a + b;
endmodule
====
# attributes and directives inside a region are source bytes like anything else
module m;
// vfmt: off
// lucisv: off
(* keep *) wire a;
`ifdef FOO
wire b;
`endif
// vfmt: on
// lucisv: on
wire c;
endmodule
----
module m;
// vfmt: off
// lucisv: off
(* keep *) wire a;
`ifdef FOO
wire b;
`endif
// vfmt: on
// lucisv: on
wire c;
endmodule
====
# fences work in a package body
package p;
// vfmt: off
// lucisv: off
localparam int A =1;
// vfmt: on
// lucisv: on
localparam int B =2;
endpackage
----
package p;
// vfmt: off
// lucisv: off
localparam int A =1;
// vfmt: on
// lucisv: on
localparam int B = 2;
endpackage
====
@@ -353,9 +353,9 @@ endpackage
module m;
generate
if (X) begin : g
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
end
endgenerate
@@ -364,9 +364,9 @@ endmodule
module m;
generate
if (X) begin : g
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
wire b;
end
endgenerate
@@ -375,18 +375,18 @@ endmodule
# a statement-level fence has no effect this round
module m;
always @(*) begin
// vfmt: off
// lucisv: off
x = 1;
// vfmt: on
// lucisv: on
y = 2;
end
endmodule
----
module m;
always @(*) begin
// vfmt: off
// lucisv: off
x = 1;
// vfmt: on
// lucisv: on
y = 2;
end
endmodule
@@ -397,29 +397,29 @@ module m;
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
endmodule
----
module m;
wire z;
// vfmt: off
// lucisv: off
wire a;
// vfmt: on
// lucisv: on
endmodule
====
# a region ending the file keeps exactly one final newline
module m;
wire a;
endmodule
// vfmt: off
// lucisv: off
`define WIDTH 8
----
module m;
wire a;
endmodule
// vfmt: off
// lucisv: off
`define WIDTH 8
====
+17 -16
View File
@@ -26,9 +26,9 @@ fn fenced(src: &str, region: &str) -> String {
fn a_region_is_emitted_byte_for_byte() {
// Interior spacing, alignment, trailing comments and a blank line inside
// the region all survive; the item after it is formatted normally.
let src = "module m;\n // vfmt: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // vfmt: on\n wire c;\nendmodule\n";
let src = "module m;\n // lucisv: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // lucisv: on\n wire c;\nendmodule\n";
let region =
" // vfmt: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // vfmt: on";
" // lucisv: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // lucisv: on";
let out = fenced(src, region);
assert!(out.ends_with(" wire c;\nendmodule\n"), "{out}");
}
@@ -38,8 +38,8 @@ fn a_region_keeps_its_own_indentation_on_every_line() {
// The source is indented four spaces inside a module the formatter
// indents by two: the region's first line is not re-indented either.
let src =
"module m;\n // vfmt: off\n wire a;\n // vfmt: on\n wire b;\nendmodule\n";
let out = fenced(src, " // vfmt: off\n wire a;\n // vfmt: on");
"module m;\n // lucisv: off\n wire a;\n // lucisv: on\n wire b;\nendmodule\n";
let out = fenced(src, " // lucisv: off\n wire a;\n // lucisv: on");
assert!(
out.contains("\n wire b;\n"),
"formatting did not resume at the module indent:\n{out}"
@@ -51,15 +51,16 @@ fn an_unmatched_off_runs_to_the_end_of_its_scope_only() {
// It must stop at the module's last item — the comment trailing that item
// included, since `Meta.trailing` has no span of its own to splice from —
// and the next module must still be formatted.
let src = "module m;\n // vfmt: off\n wire a; // note\nendmodule\n\nmodule n;\n wire b;\nendmodule\n";
let out = fenced(src, " // vfmt: off\n wire a; // note");
let src = "module m;\n // lucisv: off\n wire a; // note\nendmodule\n\nmodule n;\n wire b;\nendmodule\n";
let out = fenced(src, " // lucisv: off\n wire a; // note");
assert!(out.contains("module n;\n wire b;\n"), "the next module was not formatted:\n{out}");
}
#[test]
fn comments_before_the_off_fence_are_still_formatted_and_never_dropped() {
let src = "module m;\n// doc for the table\n// vfmt: off\nwire a;\n// vfmt: on\nendmodule\n";
let out = fenced(src, "// vfmt: off\nwire a;\n// vfmt: on");
let src =
"module m;\n// doc for the table\n// lucisv: off\nwire a;\n// lucisv: on\nendmodule\n";
let out = fenced(src, "// lucisv: off\nwire a;\n// lucisv: on");
assert!(out.contains(" // doc for the table\n"), "leading comment lost or unindented:\n{out}");
}
@@ -68,18 +69,18 @@ fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
// The fence is not a licence to change bytes: a hand-built "output" that
// reformats, drops or adds anything inside the region must fail
// equivalence exactly as it would outside one.
let src = "module m;\n // vfmt: off\n wire [3:0] a;\n wire b; // note\n // vfmt: on\nendmodule\n";
let src = "module m;\n // lucisv: off\n wire [3:0] a;\n wire b; // note\n // lucisv: on\nendmodule\n";
let corrupted = [
// a token dropped from inside the region
"module m;\n // vfmt: off\n wire a;\n wire b; // note\n // vfmt: on\nendmodule\n",
"module m;\n // lucisv: off\n wire a;\n wire b; // note\n // lucisv: on\nendmodule\n",
// the region's trailing comment dropped
"module m;\n // vfmt: off\n wire [3:0] a;\n wire b;\n // vfmt: on\nendmodule\n",
"module m;\n // lucisv: off\n wire [3:0] a;\n wire b;\n // lucisv: on\nendmodule\n",
// a fence comment itself dropped
"module m;\n wire [3:0] a;\n wire b; // note\n // vfmt: on\nendmodule\n",
"module m;\n wire [3:0] a;\n wire b; // note\n // lucisv: on\nendmodule\n",
// a token added inside the region
"module m;\n // vfmt: off\n wire [3:0] a, z;\n wire b; // note\n // vfmt: on\nendmodule\n",
"module m;\n // lucisv: off\n wire [3:0] a, z;\n wire b; // note\n // lucisv: on\nendmodule\n",
// a fence turned into an ordinary comment
"module m;\n // vfmt: off\n wire [3:0] a;\n wire b; // note\n // vfmt: onward\nendmodule\n",
"module m;\n // lucisv: off\n wire [3:0] a;\n wire b; // note\n // lucisv: onward\nendmodule\n",
];
// The real formatter gets it right...
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
@@ -97,12 +98,12 @@ fn the_matcher_agrees_with_what_the_formatter_honours() {
// The unit tests in `fence.rs` pin the matcher; this pins that the
// formatter is driven by it, in both directions.
let body = "module m;\n {}\n wire a;\nendmodule\n";
for spelling in ["// verilog_format: off", "//vfmt: off", "//\tverilog_format: off"] {
for spelling in ["// verilog_format: off", "//lucisv: off", "//\tverilog_format: off"] {
assert_eq!(fence_of(spelling), Some(Fence::Off));
let out = fmt(&body.replace("{}", spelling));
assert!(out.contains("wire a;"), "{spelling} did not fence:\n{out}");
}
for spelling in ["// vfmt: off now", "// vfmt:off", "/* vfmt: off */", "// VFMT: OFF"] {
for spelling in ["// lucisv: off now", "// lucisv:off", "/* lucisv: off */", "// LUCISV: OFF"] {
assert_eq!(fence_of(spelling), None);
let out = fmt(&body.replace("{}", spelling));
assert!(out.contains("wire a;"), "{spelling} fenced but should not have:\n{out}");
+3 -3
View File
@@ -192,10 +192,10 @@ fn a_statement_is_never_the_unit_the_item_around_it_is() {
const WITH_FENCE: &str = "\
module m;
wire a;
// vfmt: off
// lucisv: off
wire b;
wire c;
// vfmt: on
// lucisv: on
wire d;
endmodule
";
@@ -203,7 +203,7 @@ endmodule
#[test]
fn a_fence_outranks_a_range() {
// Selecting a fenced line must not lay it out: `off` means hands off
// across all of vfmt, whatever the caller asked for.
// across all of lucisv, whatever the caller asked for.
for spec in ["3", "4", "5", "3-5"] {
assert_eq!(fixed_point(WITH_FENCE, spec), WITH_FENCE, "spec {spec}");
}
+1 -1
View File
@@ -53,7 +53,7 @@ fn multiline_macro_invocation_may_be_reindented() {
/// physical lines. Its continuation line's leading whitespace is part of the
/// string's *value*, so re-indenting it corrupts the string — and a blind
/// per-line trim in `normalize` used to report the pair as equivalent, so
/// `vfmt` exited 0 and wrote the corrupted file. The net must reject this.
/// `lucisv` exited 0 and wrote the corrupted file. The net must reject this.
#[test]
fn reindented_string_inside_a_macro_argument_is_rejected() {
let input = "module m;\nif (X) begin : g\n`uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\nend\nendmodule\n";
@@ -1,8 +1,8 @@
//! Prints the generated rule reference.
//!
//! `cargo run -p vlog_linter --example rules_markdown > docs/lint-rules.md`.
//! This exists because the CLI flag that will do the same (`vfmt check
//! --rules-doc`) belongs to `crates/vfmt` and is not wired yet — see the
//! This exists because the CLI flag that will do the same (`lucisv check
//! --rules-doc`) belongs to `crates/lucisv` and is not wired yet — see the
//! Handshakes section of `docs/features/lint-rules-2/README.md`.
fn main() {
+3 -3
View File
@@ -11,14 +11,14 @@ use vlog_semantic::{analyze, Semantics};
use crate::signals::Signals;
/// The default tab stop used when a fix expands a tab, matching vfmt's
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
/// no products of its own — `vfmt check` per file, [`LintContext::new`] —
/// no products of its own — `lucisv check` per file, [`LintContext::new`] —
/// parses here and lends the results to [`LintContext::from_parse`] via
/// [`ParsedSource::context`]. A caller that already holds the products (the
/// language server's per-buffer document) skips this type and calls
@@ -102,7 +102,7 @@ enum Backing<'a> {
/// rule asks for it.
///
/// Lazy rather than eager because most rules are syntactic: a run with no
/// semantic rule enabled — which is every default `vfmt check`, since all
/// semantic rule enabled — which is every default `lucisv check`, since all
/// three semantic rules ship off — must not pay for an analysis nobody reads.
enum SemanticsSlot<'a> {
Lent(&'a Semantics),
+18 -18
View File
@@ -1,5 +1,5 @@
//! Syntactic lint rules for Verilog/SystemVerilog — the engine behind
//! `vfmt check`.
//! `lucisv check`.
//!
//! This crate plays the role of `ruff_linter` in ruff's architecture: a
//! registry of named rules, each handed a prepared file ([`LintContext`]) and
@@ -105,7 +105,7 @@ mod tests {
#[test]
fn a_same_line_waiver_suppresses_that_line_only() {
let src = "module m;\n\twire a; // vfmt: waive no-tabs\n\twire b;\nendmodule\n";
let src = "module m;\n\twire a; // lucisv: waive no-tabs\n\twire b;\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec!["no-tabs"]);
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
@@ -113,7 +113,7 @@ mod tests {
#[test]
fn a_waiver_on_its_own_line_covers_the_next_one() {
let src = "module m;\n // vfmt: waive no-tabs\n\twire a;\n\twire b;\nendmodule\n";
let src = "module m;\n // lucisv: waive no-tabs\n\twire a;\n\twire b;\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec!["no-tabs"], "only the second tab line survives");
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
@@ -128,10 +128,10 @@ mod tests {
#[test]
fn a_start_stop_range_covers_its_markers_and_everything_between() {
let src = "module m;\n\
// vfmt: waive-start no-tabs\n\
// lucisv: waive-start no-tabs\n\
\twire a;\n\
\twire b;\n\
// vfmt: waive-stop no-tabs\n\
// lucisv: waive-stop no-tabs\n\
\twire c;\n\
endmodule\n";
let found = lint_all(src);
@@ -141,13 +141,13 @@ mod tests {
#[test]
fn an_unclosed_range_runs_to_the_end_of_the_file() {
let src = "module m;\n// vfmt: waive-start no-tabs\n\twire a;\n\twire b;\nendmodule\n";
let src = "module m;\n// lucisv: waive-start no-tabs\n\twire a;\n\twire b;\nendmodule\n";
assert!(lint_all(src).is_empty());
}
#[test]
fn a_waiver_that_suppresses_nothing_is_reported() {
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
assert!(found[0].message.contains("no-tabs"), "{}", found[0].message);
@@ -155,7 +155,7 @@ mod tests {
#[test]
fn an_unknown_or_malformed_waiver_is_reported() {
let src = "module m;\n // vfmt: waive no-such-rule\n // vfmt: waive\nendmodule\n";
let src = "module m;\n // lucisv: waive no-such-rule\n // lucisv: waive\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER, UNUSED_WAIVER]);
assert!(found[0].message.contains("unknown rule"), "{}", found[0].message);
@@ -163,21 +163,21 @@ mod tests {
}
#[test]
fn a_verible_waiver_for_a_rule_vfmt_does_not_have_is_ignored() {
// Real corpus RTL is annotated for Verible. Waivers naming rules vfmt
fn a_verible_waiver_for_a_rule_lucisv_does_not_have_is_ignored() {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// vfmt's own spelling gets no such benefit of the doubt.
let src = "module m;\n // vfmt: waive macro-name-style\n wire a;\nendmodule\n";
// lucisv's own spelling gets no such benefit of the doubt.
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
#[test]
fn a_waive_stop_without_a_start_is_reported() {
let src = "module m;\n // vfmt: waive-stop no-tabs\nendmodule\n";
let src = "module m;\n // lucisv: waive-stop no-tabs\nendmodule\n";
let found = lint_all(src);
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
assert!(found[0].message.contains("no matching"), "{}", found[0].message);
@@ -185,7 +185,7 @@ mod tests {
#[test]
fn a_waiver_for_a_rule_this_run_did_not_enable_is_silent() {
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &["no-tabs".to_string()]).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
@@ -193,15 +193,15 @@ mod tests {
#[test]
fn unused_waiver_findings_can_themselves_be_waived() {
let src = "module m;\n\
// vfmt: waive unused-waiver\n\
wire a; // vfmt: waive no-tabs\n\
// lucisv: waive unused-waiver\n\
wire a; // lucisv: waive no-tabs\n\
endmodule\n";
assert!(lint_all(src).is_empty());
}
#[test]
fn disabling_the_pseudo_rule_silences_unused_reporting() {
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &[UNUSED_WAIVER.to_string()]).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
@@ -216,7 +216,7 @@ mod tests {
fn fixing_leaves_the_file_clean_for_the_fixed_rules() {
// A tab that is also trailing whitespace needs two rounds: the two
// fixes overlap, so the first pass applies one and the second the
// other. This is the loop `vfmt check --fix` runs.
// other. This is the loop `lucisv check --fix` runs.
let mut src = "module m;\n\twire a;\t\n wire b; \nendmodule\n".to_string();
for _ in 0..10 {
let found = run(&src, None, &default_rules());
+2 -2
View File
@@ -1,12 +1,12 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. vfmt
//! Verible spells its naming conventions as RE2 regular expressions. lucisv
//! spells the same conventions as character-class predicates instead, on
//! purpose: every preset anyone actually uses is "these character classes, in
//! this order", which is four small functions — and a regex engine is a
//! dependency this crate (today: `vlog_parser` + std) does not otherwise need.
//! The cost is that user-supplied patterns are not expressible; that waits on
//! the `lint` key in `vfmt.toml` and is recorded as such in
//! the `lint` key in `lucisv.toml` and is recorded as such in
//! `docs/features/lint-rules-2/README.md`.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
+2 -2
View File
@@ -20,7 +20,7 @@ pub trait Rule: Sync {
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
/// Whether a plain `vfmt check` runs this rule. A rule is default-on only
/// Whether a plain `lucisv check` runs this rule. A rule is default-on only
/// where Verible defaults its equivalent on; see
/// `docs/features/lint-rules-2/README.md` for the citation per rule.
fn default_on(&self) -> bool {
@@ -60,7 +60,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
]
}
/// The rules a plain `vfmt check` runs: every rule whose
/// The rules a plain `lucisv check` runs: every rule whose
/// [`default_on`](Rule::default_on) says so.
pub fn default_rules() -> Vec<&'static dyn Rule> {
all_rules().into_iter().filter(|rule| rule.default_on()).collect()
+6 -6
View File
@@ -11,13 +11,13 @@ use crate::registry::all_rules;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
let mut out = String::new();
out.push_str("# vfmt lint rules\n\n");
out.push_str("# lucisv lint rules\n\n");
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
A rule marked **default** runs for a plain `vfmt check`; the others \
A rule marked **default** runs for a plain `lucisv check`; the others \
need `--select <name>`. Any rule can be turned off with `--ignore \
<name>` or waived in the source with `// vfmt: waive <name>`.\n\n",
<name>` or waived in the source with `// lucisv: waive <name>`.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
@@ -124,14 +124,14 @@ mod tests {
assert_eq!(
head,
vec![
"# vfmt lint rules",
"# lucisv lint rules",
"",
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"A rule marked **default** runs for a plain `vfmt check`; the others need \
"A rule marked **default** runs for a plain `lucisv check`; the others need \
`--select <name>`. Any rule can be turned off with `--ignore <name>` or waived \
in the source with `// vfmt: waive <name>`.",
in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
@@ -27,7 +27,7 @@ impl Rule for EnumNameStyle {
readable at a glance: `state_e cur_state` says which identifier is the \
type without knowing the codebase. Verible's `enum-name-style` \
(enabled by default) spells this as the pattern `[a-z_0-9]+(_t|_e)` — \
lower_snake_case with an `_e` or `_t` suffix — and vfmt checks the \
lower_snake_case with an `_e` or `_t` suffix — and lucisv checks the \
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
name to check, and giving it one is Verible's separate \
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
+1 -1
View File
@@ -23,7 +23,7 @@ impl Rule for NoTabs {
"A tab renders at a width nobody agrees on, so a file mixing tabs and \
spaces looks aligned in the editor that wrote it and ragged everywhere \
else — and code review diffs inherit the mess. Verible's style guide \
(and vfmt's own output) indents with spaces only. The fix expands each \
(and lucisv's own output) indents with spaces only. The fix expands each \
tab to the run's indent width; tabs inside string literals are left \
alone, because there the whitespace is data."
}
@@ -23,7 +23,7 @@ impl Rule for NoTrailingWhitespace {
"Trailing whitespace is invisible, so it survives review and then shows \
up as diff noise the day somebody's editor strips it — a one-character \
change that touches every line of the file. Verible's style guide \
forbids it and vfmt's formatter never emits it. The fix deletes the \
forbids it and lucisv's formatter never emits it. The fix deletes the \
run; a run inside a string literal is left alone, because there the \
whitespace is data."
}
@@ -26,7 +26,7 @@ impl Rule for ParameterNameStyle {
"A parameter is a compile-time constant, and reading one at a use site \
should not require scrolling back to the declaration to learn that. \
Verible's `parameter-name-style` (enabled by default) enforces exactly \
this, with `CamelCase` and `ALL_CAPS` as its presets. vfmt accepts \
this, with `CamelCase` and `ALL_CAPS` as its presets. lucisv accepts \
either preset for both `parameter` and `localparam` — Verible's \
default is stricter for `localparam` (`CamelCase` only), which would \
flag most `localparam int FOO_BAR` in existing RTL; until per-rule \
@@ -27,7 +27,7 @@ impl Rule for StructUnionNameStyle {
nearly universal: it marks an identifier as a type, which the language \
itself gives no syntax for at a use site. Verible's \
`struct-union-name-style` (enabled by default) requires \
lower_snake_case ending in `_t`, and vfmt checks the same shape. Only \
lower_snake_case ending in `_t`, and lucisv checks the same shape. Only \
a `typedef struct` / `typedef union` is judged — an anonymous struct \
has no name, and requiring it to have one is Verible's separate \
`typedef-structs-unions` idea. Escaped identifiers are exempt, and \
+1 -1
View File
@@ -29,7 +29,7 @@ impl Rule for UndrivenNet {
as an accusation. It stays silent about: ports (an input is driven \
by the instantiating file, an `inout` from either side), any signal \
wired to an instance or gate connection or passed to a task — those \
positions may be `output`, and vfmt does not read the instantiated \
positions may be `output`, and lucisv does not read the instantiated \
module to find out — any signal a macro, a compiler directive, a \
verbatim block or an unparsed region mentions, any signal in a \
module that instantiates with `.*`, anything declared with an \
@@ -23,7 +23,7 @@ impl Rule for UnusedSignal {
"A `wire` or `logic` that nothing reads and nothing drives is dead \
weight: it costs a reader the effort of working out what it is for, \
and it is often the leftover of a signal that was renamed everywhere \
but here. This is the first rule vfmt writes against the symbol \
but here. This is the first rule lucisv writes against the symbol \
table rather than the syntax tree — Verible cannot express it, \
because knowing that a name is unused means knowing which \
declaration every use refers to.\n\n\
@@ -34,7 +34,7 @@ impl Rule for UnusedSignal {
default), and any name mentioned *anywhere else* in the file's \
tokens, even inside a macro invocation, a compiler directive or a \
region that failed to parse. That last guard is the important one: \
vfmt does not expand macros, so a signal used only by \
lucisv does not expand macros, so a signal used only by \
`` `MY_ASSERT(foo) `` would otherwise be reported as unused. The \
cost of the guard is that two same-named unused signals in one file \
shield each other — a false negative, which is the harmless \
@@ -18,10 +18,10 @@ impl Rule for UnusedWaiver {
}
fn doc(&self) -> &'static str {
"A `// vfmt: waive` comment outlives the problem it was written for: \
"A `// lucisv: waive` comment outlives the problem it was written for: \
the code is fixed, the waiver stays, and the next reader believes the \
line is still exempt. ruff's experience is that suppressions only stay \
honest if the linter reports the dead ones, so vfmt does it from day \
honest if the linter reports the dead ones, so lucisv does it from day \
one. Reported for a waiver that suppressed nothing, one that names a \
rule that does not exist, and one that is malformed. A waiver for a \
rule this run did not enable is *not* reported — it never had a \
+3 -3
View File
@@ -9,7 +9,7 @@
//!
//! Everything here leans one way: **when the answer is not certain, say
//! nothing**. A name that a macro, a compiler directive, a verbatim block or
//! an unparsed region mentions is dropped from every judgement, because vfmt
//! an unparsed region mentions is dropped from every judgement, because lucisv
//! does not expand macros and cannot see what those regions do. That is the
//! insurance a semantic rule needs — a lint that cries wolf on real RTL is
//! worse than no lint at all.
@@ -125,7 +125,7 @@ struct ModuleInfo {
/// declared in it can therefore be judged. Two ways to earn it: an
/// instance connected with `.*`, which reads and drives same-named
/// signals without writing any of their names down, and an `` `include``
/// in the module body, which is arbitrary code vfmt does not follow.
/// in the module body, which is arbitrary code lucisv does not follow.
blind: bool,
}
@@ -392,7 +392,7 @@ impl Scanner {
}
}
// An `include` in a module body is arbitrary code — it may
// declare, read or drive anything — and vfmt does not follow one.
// declare, read or drive anything — and lucisv does not follow one.
ItemKind::Directive(raw) if is_include(&raw.text) => self.blind(module),
// Nothing here can be read: a macro is not expanded, a directive
// is not evaluated, a verbatim block is not modelled, and an
+16 -16
View File
@@ -1,12 +1,12 @@
//! Inline waivers: `// vfmt: waive <rule>` and friends.
//! Inline waivers: `// lucisv: waive <rule>` and friends.
//!
//! Grammar (Verible's, with a `vfmt:` alias — `verilog_lint:` is what
//! Grammar (Verible's, with a `lucisv:` alias — `verilog_lint:` is what
//! existing RTL is annotated with, so both spellings are accepted):
//!
//! ```text
//! // vfmt: waive <rule> this line, or the next if written alone
//! // vfmt: waive-start <rule> from this line ...
//! // vfmt: waive-stop <rule> ... to this one, both included
//! // lucisv: waive <rule> this line, or the next if written alone
//! // lucisv: waive-start <rule> from this line ...
//! // lucisv: waive-stop <rule> ... to this one, both included
//! ```
//!
//! A waiver that suppresses nothing is itself reported, under the
@@ -31,10 +31,10 @@ pub(crate) struct Waivers {
struct Entry {
/// The rule waived; empty when the comment did not parse.
rule: String,
/// Written with the `vfmt:` spelling. A `verilog_lint:` waiver naming a
/// rule vfmt does not have is Verible's, not a typo, so it is ignored
/// Written with the `lucisv:` spelling. A `verilog_lint:` waiver naming a
/// rule lucisv does not have is Verible's, not a typo, so it is ignored
/// rather than reported — that is what makes a Verible-annotated
/// codebase lintable by vfmt without editing it first.
/// codebase lintable by lucisv without editing it first.
ours: bool,
scope: Scope,
/// The waiver comment itself — where an `unused-waiver` points.
@@ -101,7 +101,7 @@ impl Waivers {
},
Directive::Malformed => entries.push(Entry::broken(
comment.span,
"malformed waiver: expected `// vfmt: waive <rule-name>`".to_string(),
"malformed waiver: expected `// lucisv: waive <rule-name>`".to_string(),
)),
}
}
@@ -206,10 +206,10 @@ fn alone_on_its_line(ctx: &LintContext, span: TextRange) -> bool {
}
/// Reads one comment as a waiver directive plus whether it was written with
/// vfmt's own prefix, or `None` if it is not a waiver at all.
/// lucisv's own prefix, or `None` if it is not a waiver at all.
fn parse_directive(text: &str) -> Option<(Directive, bool)> {
let body = strip_markers(text).trim();
let (rest, ours) = match body.strip_prefix("vfmt:") {
let (rest, ours) = match body.strip_prefix("lucisv:") {
Some(rest) => (rest, true),
None => (body.strip_prefix("verilog_lint:")?, false),
};
@@ -257,22 +257,22 @@ mod tests {
#[test]
fn both_spellings_are_accepted() {
assert_eq!(directive_of("// vfmt: waive no-tabs"), Some("waive"));
assert_eq!(directive_of("// lucisv: waive no-tabs"), Some("waive"));
assert_eq!(directive_of("// verilog_lint: waive no-tabs"), Some("waive"));
assert_eq!(directive_of("/* vfmt: waive-start no-tabs */"), Some("start"));
assert_eq!(directive_of("/* lucisv: waive-start no-tabs */"), Some("start"));
assert_eq!(directive_of("//verilog_lint:waive-stop no-tabs"), Some("stop"));
}
#[test]
fn ordinary_comments_and_format_fences_are_not_waivers() {
assert_eq!(directive_of("// a note"), None);
assert_eq!(directive_of("// vfmt: off"), None);
assert_eq!(directive_of("// lucisv: off"), None);
assert_eq!(directive_of("// verilog_format: off"), None);
}
#[test]
fn a_waiver_without_exactly_one_rule_is_malformed() {
assert_eq!(directive_of("// vfmt: waive"), Some("malformed"));
assert_eq!(directive_of("// vfmt: waive no-tabs and more"), Some("malformed"));
assert_eq!(directive_of("// lucisv: waive"), Some("malformed"));
assert_eq!(directive_of("// lucisv: waive no-tabs and more"), Some("malformed"));
}
}
@@ -11,12 +11,12 @@ endmodule
====
# always-ff-non-blocking waived on the same line
module m;
always_ff @(posedge clk) q = d; // vfmt: waive always-ff-non-blocking
always_ff @(posedge clk) q = d; // lucisv: waive always-ff-non-blocking
endmodule
====
# an always-ff waiver that waives nothing is reported
module m;
always_ff @(posedge clk) q <= d; // vfmt: waive always-ff-non-blocking
always_ff @(posedge clk) q <= d; // lucisv: waive always-ff-non-blocking
//^ 36 unused-waiver
endmodule
====
@@ -39,6 +39,6 @@ endmodule
====
# an always-comb waiver that waives nothing is reported
module m;
always_comb x = y; // vfmt: waive always-comb-blocking
always_comb x = y; // lucisv: waive always-comb-blocking
//^ 22 unused-waiver
endmodule
@@ -31,7 +31,7 @@ endmodule
# waived from the line above
module m;
always_comb begin
// vfmt: waive case-missing-default
// lucisv: waive case-missing-default
case (s)
0: x = 1;
endcase
@@ -44,7 +44,7 @@ module m;
case (s)
0: x = 1;
default: x = 0;
endcase // vfmt: waive case-missing-default
endcase // lucisv: waive case-missing-default
//^ 13 unused-waiver
end
endmodule
@@ -17,6 +17,6 @@ endpackage
====
# a waiver that waives nothing is reported
package p;
typedef enum logic { A } state_e; // vfmt: waive enum-name-style
typedef enum logic { A } state_e; // lucisv: waive enum-name-style
//^ 37 unused-waiver
endpackage
@@ -11,11 +11,11 @@ endmodule
====
# waived on the same line
module m;
parameter WIDTH = 8; // vfmt: waive explicit-parameter-storage-type
parameter WIDTH = 8; // lucisv: waive explicit-parameter-storage-type
endmodule
====
# a waiver that waives nothing is reported
module m;
parameter int WIDTH = 8; // vfmt: waive explicit-parameter-storage-type
parameter int WIDTH = 8; // lucisv: waive explicit-parameter-storage-type
//^ 28 unused-waiver
endmodule
@@ -15,11 +15,11 @@ endmodule
====
# waived on the same line
#path rtl/bar.sv
module foo; // vfmt: waive module-filename
module foo; // lucisv: waive module-filename
endmodule
====
# a waiver that waives nothing is reported
#path rtl/foo.sv
module foo; // vfmt: waive module-filename
module foo; // lucisv: waive module-filename
//^ 13 unused-waiver
endmodule
@@ -15,11 +15,11 @@ endmodule
====
# waived on the same line
#select module-name-style,unused-waiver
module FooBar; // vfmt: waive module-name-style
module FooBar; // lucisv: waive module-name-style
endmodule
====
# a waiver that waives nothing is reported
#select module-name-style,unused-waiver
module foo_bar; // vfmt: waive module-name-style
module foo_bar; // lucisv: waive module-name-style
//^ 17 unused-waiver
endmodule
@@ -147,7 +147,7 @@ endmodule
# waived on the same line
#select multiply-driven,unused-waiver
module m (input logic c, output logic q);
logic a; // vfmt: waive multiply-driven
logic a; // lucisv: waive multiply-driven
always_comb a = c;
always_comb a = 1'b0;
assign q = a;
@@ -156,7 +156,7 @@ endmodule
# a waiver that waives nothing is reported
#select multiply-driven,unused-waiver
module m (input logic c, output logic q);
logic a; // vfmt: waive multiply-driven
logic a; // lucisv: waive multiply-driven
//^ 12 unused-waiver
always_comb a = c;
assign q = a;
+3 -3
View File
@@ -28,18 +28,18 @@ endmodule
====
# waived on the same line
module m;
wire a; // vfmt: waive no-tabs
wire a; // lucisv: waive no-tabs
endmodule
====
# waived from the line above
module m;
// vfmt: waive no-tabs
// lucisv: waive no-tabs
wire a;
endmodule
====
# a waiver that waives nothing is reported
module m;
wire a; // vfmt: waive no-tabs
wire a; // lucisv: waive no-tabs
//^ 11 unused-waiver
endmodule
====
@@ -11,13 +11,13 @@ endmodule
====
# waived from the line above
module m;
// vfmt: waive no-trailing-whitespace
// lucisv: waive no-trailing-whitespace
wire a;
endmodule
====
# a waiver that waives nothing is reported
module m;
wire a; // vfmt: waive no-trailing-whitespace
wire a; // lucisv: waive no-trailing-whitespace
//^ 11 unused-waiver
endmodule
====
@@ -11,11 +11,11 @@ endmodule
====
# waived on the same line
module m;
parameter int addr_width = 8; // vfmt: waive parameter-name-style
parameter int addr_width = 8; // lucisv: waive parameter-name-style
endmodule
====
# a waiver that waives nothing is reported
module m;
parameter int AddrWidth = 8; // vfmt: waive parameter-name-style
parameter int AddrWidth = 8; // lucisv: waive parameter-name-style
//^ 32 unused-waiver
endmodule
@@ -11,11 +11,11 @@ endpackage
====
# waived on the same line
package p;
typedef struct packed { logic a; } addr; // vfmt: waive struct-union-name-style
typedef struct packed { logic a; } addr; // lucisv: waive struct-union-name-style
endpackage
====
# a waiver that waives nothing is reported
package p;
typedef struct packed { logic a; } addr_t; // vfmt: waive struct-union-name-style
typedef struct packed { logic a; } addr_t; // lucisv: waive struct-union-name-style
//^ 46 unused-waiver
endpackage
@@ -149,14 +149,14 @@ endmodule
# waived on the same line
#select undriven-net,unused-waiver
module m (output logic q);
wire a; // vfmt: waive undriven-net
wire a; // lucisv: waive undriven-net
assign q = a;
endmodule
====
# a waiver that waives nothing is reported
#select undriven-net,unused-waiver
module m (input logic c, output logic q);
wire a; // vfmt: waive undriven-net
wire a; // lucisv: waive undriven-net
//^ 11 unused-waiver
assign a = c;
assign q = a;
@@ -42,7 +42,7 @@ module m;
wire spare_unused;
endmodule
====
# a name only a macro invocation mentions is used as far as vfmt can tell
# a name only a macro invocation mentions is used as far as lucisv can tell
#select unused-signal,unused-waiver
module m;
wire a;
@@ -98,20 +98,20 @@ endmodule
# waived on the same line
#select unused-signal,unused-waiver
module m;
wire a; // vfmt: waive unused-signal
wire a; // lucisv: waive unused-signal
endmodule
====
# waived from the line above
#select unused-signal,unused-waiver
module m;
// vfmt: waive unused-signal
// lucisv: waive unused-signal
wire a;
endmodule
====
# a waiver that waives nothing is reported
#select unused-signal,unused-waiver
module m (input logic c, output logic q);
wire a; // vfmt: waive unused-signal
wire a; // lucisv: waive unused-signal
//^ 11 unused-waiver
assign a = c;
assign q = a;
+15 -15
View File
@@ -1,65 +1,65 @@
# a start/stop range covers its markers and everything between
module m;
// vfmt: waive-start no-tabs
// lucisv: waive-start no-tabs
wire a;
wire b;
// vfmt: waive-stop no-tabs
// lucisv: waive-stop no-tabs
wire c;
//^ 1 no-tabs
endmodule
====
# an unclosed range runs to the end of the file
module m;
// vfmt: waive-start no-tabs
// lucisv: waive-start no-tabs
wire a;
wire b;
endmodule
====
# a stop closes the innermost open start
module m;
// vfmt: waive-start no-tabs
// vfmt: waive-start no-tabs
// lucisv: waive-start no-tabs
// lucisv: waive-start no-tabs
wire a;
// vfmt: waive-stop no-tabs
// lucisv: waive-stop no-tabs
wire b;
// vfmt: waive-stop no-tabs
// lucisv: waive-stop no-tabs
wire c;
//^ 1 no-tabs
endmodule
====
# a verible waiver for a rule vfmt does not have is ignored
# a verible waiver for a rule lucisv does not have is ignored
module m;
// verilog_lint: waive macro-name-style
wire a;
endmodule
====
# vfmt's own spelling for an unknown rule is reported
# lucisv's own spelling for an unknown rule is reported
module m;
// vfmt: waive macro-name-style
// lucisv: waive macro-name-style
//^ 3 unused-waiver
wire a;
endmodule
====
# a malformed waiver is reported
module m;
// vfmt: waive
// lucisv: waive
//^ 3 unused-waiver
endmodule
====
# a waive-stop with nothing open is reported
module m;
// vfmt: waive-stop no-tabs
// lucisv: waive-stop no-tabs
//^ 3 unused-waiver
endmodule
====
# a waiver for a rule this run did not enable is silent
#select no-trailing-whitespace,unused-waiver
module m;
wire a; // vfmt: waive no-tabs
wire a; // lucisv: waive no-tabs
endmodule
====
# an unused waiver can itself be waived
module m;
// vfmt: waive unused-waiver
wire a; // vfmt: waive no-tabs
// lucisv: waive unused-waiver
wire a; // lucisv: waive no-tabs
endmodule
@@ -26,12 +26,12 @@ endmodule
# waived on the same line
#path rtl/m.sv
module m;
reg q; // vfmt: waive wire-reg-mixup
reg q; // lucisv: waive wire-reg-mixup
endmodule
====
# a waiver that waives nothing is reported
#path rtl/m.sv
module m;
logic q; // vfmt: waive wire-reg-mixup
logic q; // lucisv: waive wire-reg-mixup
//^ 12 unused-waiver
endmodule
+2 -2
View File
@@ -5,7 +5,7 @@
//! `====` lines. A case is Verilog source with its expected findings written
//! into it: a line whose trimmed text is `//^ <col> <rule-name>` asserts one
//! finding of that rule at that 1-based column on the nearest preceding
//! non-marker line — the same `line:col` that `vfmt check` prints, so a
//! non-marker line — the same `line:col` that `lucisv check` prints, so a
//! marker can be written by copying the diagnostic. Marker lines are ordinary
//! comments to the linter, so the source stays valid Verilog.
//!
@@ -18,7 +18,7 @@
//! - `#SKIP ...` — a known-bad case: it must still fail, and the moment it
//! passes the suite demands the marker's removal.
//! - `#path <p>` — lint the source as if it were read from this file path.
//! - `#select ...` — comma-separated rule names, `vfmt check --select`
//! - `#select ...` — comma-separated rule names, `lucisv check --select`
//! semantics (replaces the default rule set).
//!
//! A `----` line splits a case into `(input, expected fixed output)`: the
+1 -1
View File
@@ -3,6 +3,6 @@ name = "vlog_parser"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Verilog/SystemVerilog lexer and parser for vfmt"
description = "Verilog/SystemVerilog lexer and parser for lucisv"
[dependencies]
+4 -4
View File
@@ -126,7 +126,7 @@ pub struct RawText {
/// It is kept in a vector *beside* the elements rather than folded into one
/// enum with them: the element vectors are read by `vlog_semantic` and
/// `vlog_linter`, and a directive is not a port. `before` is what puts the
/// two back into source order. vfmt does not evaluate the condition — both
/// two back into source order. lucisv does not evaluate the condition — both
/// arms' elements are ordinary elements of the one list, exactly as an
/// `` `ifdef`` at item position already works.
#[derive(Debug, Clone)]
@@ -240,7 +240,7 @@ pub enum ItemKind {
/// `clocking cb @(posedge clk); ... endclocking` and the `default`
/// spellings of it (IEEE 1800 §14).
Clocking(ClockingDecl),
/// A block vfmt deliberately does not model, kept byte-for-byte:
/// A block lucisv deliberately does not model, kept byte-for-byte:
/// `constraint c { ... }`, `covergroup ... endgroup`, a concurrent
/// assertion (`assert property ( ... );`) and a `property`/`sequence`
/// declaration. See `docs/features/classes/README.md` and
@@ -446,7 +446,7 @@ impl DataType {
pub enum TypeExtra {
/// The `#( ... )` of a parameterized type reference, verbatim:
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so vfmt
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so lucisv
/// reproduces them as written instead of modelling a second grammar.
Params(RawText),
/// An anonymous enum standing where a type name would:
@@ -619,7 +619,7 @@ pub struct ContAssign {
/// The `( strength0 , strength1 )` pair of a continuous assignment. The two
/// strengths are stored in the order the source wrote them — the language
/// allows either order and vfmt is not a legality checker.
/// allows either order and lucisv is not a legality checker.
#[derive(Debug)]
pub struct DriveStrength {
pub first: String,
+1 -1
View File
@@ -636,7 +636,7 @@ impl<'a> RawLexer<'a> {
text.push(self.bump() as char);
// A based number whose digits come from a macro: `` 32'h`DM_ADDR ``
// (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The
// digits are preprocessor output vfmt does not expand, so the number
// digits are preprocessor output lucisv does not expand, so the number
// token ends here, with no digits, and the invocation lexes as the
// macro token it is; the parser rejoins the pair into one primary
// expression and the formatter prints them adjacent, as written.
+19 -16
View File
@@ -228,7 +228,7 @@ pub struct Parser<'a> {
/// Parse a token stream, stopping at the first error.
///
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// vfmt keeps verbatim (`constraint`, `covergroup` — see
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
@@ -720,7 +720,7 @@ impl<'a> Parser<'a> {
// argument (`.value(x)`, `.name()`) and a `[lo:hi]` value range (a
// `case ... inside` label). Both are recognized here, in the shared
// element parse, because rejecting them in the lists that cannot
// legally hold them would gain nothing — vfmt checks legality
// legally hold them would gain nothing — lucisv checks legality
// nowhere else either, and a wrong guess emits the same tokens.
let expr = if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.parse_named_arg()?
@@ -902,7 +902,7 @@ impl<'a> Parser<'a> {
/// expression or a port/parameter list. In an expression `` `A (b) `` may
/// well be `` `A `` applied to the parenthesized value `(b)` — the answer
/// depends on whether the macro was defined with formals, which lives in
/// a file vfmt does not read (IEEE 1800 §22.5.1, and the analysis in
/// a file lucisv does not read (IEEE 1800 §22.5.1, and the analysis in
/// `docs/features/lexer-cleanup/README.md`). At item position there is no
/// such ambiguity: neither reading is an item on its own.
///
@@ -925,7 +925,7 @@ impl<'a> Parser<'a> {
self.bump(); // (
self.skip_balanced("(", ")")?;
// Verbatim, space included: the argument text is preprocessor
// input vfmt does not model, and closing the gap would make the
// input lucisv does not model, and closing the gap would make the
// output's token text differ from the input's (`` `A (b) `` and
// `` `A(b) `` are one token each, of different text) — which the
// safety net rightly refuses.
@@ -1156,7 +1156,7 @@ impl<'a> Parser<'a> {
match kw.as_str() {
"module" | "macromodule" => self.parse_module("endmodule").map(ItemKind::Module),
// `interface class` is a class, not an interface (IEEE 1800
// §8.26): a different construct that vfmt does not model, so it
// §8.26): a different construct that lucisv does not model, so it
// falls through to the unsupported-construct error below.
"interface" if !self.nth(1).is_kw("class") => {
self.parse_module("endinterface").map(ItemKind::Module)
@@ -1574,7 +1574,7 @@ impl<'a> Parser<'a> {
/// `constraint name { ... }`, kept as verbatim source.
///
/// The constraint language is a grammar of its own (`dist`, `->`,
/// `solve ... before`, `inside`, `foreach`, `if`/`else`) that vfmt models
/// `solve ... before`, `inside`, `foreach`, `if`/`else`) that lucisv models
/// none of, and reflowing it has no payoff, so the block is copied out of
/// the source by span. A prototype (`constraint c;`) has no braces.
fn parse_constraint(&mut self) -> PResult<RawText> {
@@ -1654,7 +1654,7 @@ impl<'a> Parser<'a> {
///
/// `assert property (@(posedge clk) a |-> ##[1:3] b) else $error("...");`
/// — the property expression is a grammar of its own (`|->`, `##[1:3]`,
/// `throughout`, `disable iff`, `$rose`) that vfmt models none of, and
/// `throughout`, `disable iff`, `$rose`) that lucisv models none of, and
/// there is no layout convention worth inventing for it, so the whole
/// item is copied out of the source by span exactly as a `constraint` is.
fn parse_concurrent_assertion(&mut self) -> PResult<RawText> {
@@ -2024,7 +2024,7 @@ impl<'a> Parser<'a> {
}
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
/// it is a delay or an edge, never something vfmt re-lays out — so the
/// it is a delay or an edge, never something lucisv re-lays out — so the
/// printer writes back exactly what the source said. The `#(min:typ:max)`
/// spelling is not supported; see the feature README's Assumptions.
fn parse_clocking_skew(&mut self) -> PResult<String> {
@@ -2643,7 +2643,7 @@ impl<'a> Parser<'a> {
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
///
/// `bind` is deliberately *not* in the lexer's keyword table — the same
/// call vfmt makes for `new`/`this`/`super` — so that `obj.bind()` keeps
/// call lucisv makes for `new`/`this`/`super` — so that `obj.bind()` keeps
/// parsing as the ordinary method call it is in existing testbenches.
/// A directive is recognized from its shape instead: the word `bind`,
/// then a target scope (a name, possibly a `.`-separated hierarchical
@@ -4154,7 +4154,7 @@ impl<'a> Parser<'a> {
// `with { ... }` (a `randomize` constraint block) are the two
// postfix spellings of `with`; the delimiter tells them apart and
// demanding one keeps the `with [range]` of a stream expression,
// which vfmt does not model, out of this path.
// which lucisv does not model, out of this path.
|| (t.is_kw("with") && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
}
@@ -4463,7 +4463,7 @@ impl<'a> Parser<'a> {
// A bare `$` — the upper bound of a queue (`q[$]`,
// `q[$-1]`, `int q[$]`). Kept an ordinary name, like
// `new`/`this`/`super`: one leaf makes every position
// work through the existing expression grammar, and vfmt
// work through the existing expression grammar, and lucisv
// checks legality nowhere else either.
"$" => {
self.bump();
@@ -4508,7 +4508,7 @@ impl<'a> Parser<'a> {
if self.cur().is_sym("}") {
// `{}` — the empty queue/dynamic-array literal
// (`q = {};`). Illegal as a Verilog concatenation,
// but vfmt is not a legality checker.
// but lucisv is not a legality checker.
self.bump();
return Ok(self.expr_at(start, ExprKind::Concat(Vec::new())));
}
@@ -5018,7 +5018,7 @@ mod tests {
/// The spaced reading is offered at item and statement position only. In
/// an expression `` `A (b) `` may be `` `A `` applied to `(b)`, which
/// depends on a `` `define`` vfmt never sees.
/// depends on a `` `define`` lucisv never sees.
#[test]
fn a_spaced_macro_in_expression_position_is_still_a_call() {
let file = parse_ok("module m;\nassign x = `A (b);\nendmodule");
@@ -5327,11 +5327,14 @@ mod tests {
// The handshake `docs/features/format-fences/README.md` asked for: a
// same-line comment now has a byte offset, so a fence written there
// can be located in the source.
let src = "module m;\n wire a; // vfmt: off\nendmodule\n";
let src = "module m;\n wire a; // lucisv: off\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment");
assert_eq!(&src[trailing.span.start as usize..trailing.span.end as usize], "// vfmt: off");
assert_eq!(
&src[trailing.span.start as usize..trailing.span.end as usize],
"// lucisv: off"
);
assert_eq!((trailing.line, trailing.col), (2, 11));
}
@@ -5479,7 +5482,7 @@ mod tests {
#[test]
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
// vfmt does not evaluate the condition: an `ifdef/`else pair simply
// lucisv does not evaluate the condition: an `ifdef/`else pair simply
// contributes every element of both arms, in source order.
let src = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more