Add range formatting and the second lint-rule set (round 18)

range-formatting: --lines M-N[,M-N...] formats only the top-level
items intersecting the ranges; modules/packages split head/body/tail
with independent decisions, everything else is atomic, and
unselected units are emitted as merged verbatim source slices (the
run-merge is load-bearing: per-item slices let separators collapse
blank lines between untouched items). Convergence via Selection
replay -- same-selection re-runs are fixed points, sound because the
equivalence check has already proven token identity; QA's sabotage
of the replay failed immediately on real RTL. The honest limit
(same line numbers can sweep in a neighbor after lines move;
449/8236 corpus trials, all settled next run) is measured and
pinned. Fence wins over range; alignment groups split at verbatim
boundaries; cache fully bypassed; LSP rangeFormatting advertised and
consumes only lines (no UTF-16 column math); tools/vfmt-changed.sh
derives ranges from git diff. Default behavior provably unchanged
(TSV md5 + all-578-file byte-compare vs a pre-round binary).

lint-rules-2: visit.rs walks class bodies (closing the classes
handshake; +6 real findings in UVM code), five new rules with
evidence-based defaults -- parameter/enum/struct-union-name-style ON
with Verible's exact names and published defaults (vendored waivers
now honored), module-name-style OFF (Verible has no such rule; the
brief's premise was checked and corrected), wire-reg-mixup ON (0
corpus noise in .v, 209 findings on a .sv rename -- both zeroes
proven). rules_markdown() generates the rule reference; 13 rules
total, zero CLI/server wiring needed.

Also: lead notes in classes and shared-fence-filter READMEs
documenting the fence asymmetry lint-rules-2 QA found (a fence in a
class body protects fixes via the scan backstop even though the
formatter ignores it there).

768 workspace tests. Dev: 2 Opus agents; QA: 2 Sonnet agents;
reviews in docs/features/{range-formatting,lint-rules-2}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 15:28:24 -07:00
1 parent 003e0766e9
commit e9008b680c
36 files changed
+4317 -98

No files matched your search

+37
View File
@@ -31,6 +31,14 @@ vfmt --threads 1 rtl/
vfmt --check rtl/
vfmt --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
# ...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
# ignore any vfmt.toml found next to the input
vfmt --no-config rtl/
@@ -271,6 +279,35 @@ exactly — `// vfmt: off for now` is an ordinary comment, not a fence. An
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
### Range formatting (`--lines`)
`--lines M-N` formats only the constructs meeting those 1-based, inclusive
lines and emits every other byte exactly as it was written. This is the
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
```
The unit is one **item**. An item whose lines meet a range — a declaration, an
`always` block, an instantiation — is laid out exactly as a whole-file run
would lay it out; nothing smaller is, so selecting one statement lays out the
`always` block around it. A module or package is descended into: its header
and its `endmodule` stay as written unless they are themselves selected, and
only the body items that are selected are laid out — a three-line edit in a
two-thousand-line module reformats three lines. `// verilog_format: off` still
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
into ranges. Full semantics, including what happens at a range boundary:
`docs/features/range-formatting/README.md`.
## Supported syntax
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
+42 -9
View File
@@ -52,12 +52,24 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
→ `crates/vlog_formatter/src/fence.rs`; grammar, item-level semantics and
join rules in `docs/features/format-fences/README.md`. Item scopes only —
statement-level fences are documented as not implemented.
- [ ] **[V] Range formatting: `--lines M-N[,M-N...]`.** Format only
- [x] **[V] Range formatting: `--lines M-N[,M-N...]`.** Format only
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
`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;
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
runtime safety net runs over the whole output — the convergence half by
replaying the per-item decisions, since line numbers move when text does.
578 corpus files × 8236 range trials: 0 refusals, and whole-file output is
byte-identical to before. Semantics, interaction rules and the honest
limits in `docs/features/range-formatting/README.md`.
- [x] **[V] Alignment inference for declaration/port/connection groups.**
Verible's most-loved feature: infer align-vs-flush-left intent from the
original spacing (≥4 excess spaces = author wants alignment), and break
@@ -191,12 +203,25 @@ Verible's rule ergonomics (waivers, configurable rules).
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.
- [ ] **[V] Configurable naming rules via regex** (module/instance/
- [x] **[V] Configurable naming rules via regex** (module/instance/
parameter/enum naming), with named presets like Verible's
(snake_case, ALL_CAPS, etc.).
- [ ] **[V] `--generate_markdown`-style self-documentation** — generate the
→ Named presets ship, **without a regex dependency**: `parameter-name-style`,
`enum-name-style`, `struct-union-name-style` (Verible-default-on, Verible's
own names and patterns) and `module-name-style` (default-off — Verible has no
such rule to inherit a default from). Presets are character-class predicates
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.
- [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`.
- [ ] 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,
@@ -205,8 +230,14 @@ Verible's rule ergonomics (waivers, configurable rules).
`explicit-parameter-storage-type`, `case-missing-default`,
`always-ff-non-blocking`, `always-comb-blocking`, `module-filename` —
corpus baseline per rule in `docs/features/linter-core/README.md`.
- [ ] `wire`/`reg` mixups in SV files — needs to know which files are
SystemVerilog, a decision the linter does not make yet.
- [x] `wire`/`reg` mixups in SV files — `wire-reg-mixup`, default on. The
SystemVerilog-ness decision is the **file extension** (`.sv`/`.svh`), so a
stdin buffer without `--stdin-filename` is silent. It flags the `reg`
keyword only; `wire` is legitimate SystemVerilog and is not flagged. Note
for the record: unlike the other seed rules this one is **not** from
Verible's default set — Verible has no wire/reg rule at all; the rationale
is IEEE 1800 (`logic` and `reg` are one type) and the lowRISC style guide.
See `docs/features/lint-rules-2/README.md`.
## 5. Testing — adapt Verible's methodology
@@ -388,13 +419,15 @@ later:
help for instantiations.
→ `crates/vfmt_server`, binary `vfmt-server`, on `lsp-server` +
`lsp-types` (synchronous, no async runtime). **Shipped:**
`textDocument/formatting`, parse diagnostics on didOpen/didChange/didSave,
`textDocument/formatting`, `textDocument/rangeFormatting` (round 18, on §2's
`--lines`), parse diagnostics on didOpen/didChange/didSave,
`semanticTokens/full`, `hover` (in-file and workspace `` `define``
expansion, declaration snippets), `definition` (both resolution layers,
all locations when ambiguous), `references` (in-file), `documentSymbol`
and `workspace/symbol`. **Not shipped, deliberately:** `rangeFormatting`
(waits on §2 `--lines`), lint diagnostics (waits on `vlog_linter`),
cross-file references, completion/rename/signature help. Byte↔UTF-16
and `workspace/symbol`. **Not shipped, deliberately:** ~~`rangeFormatting`
(waits on §2 `--lines`)~~ **delivered**, lint diagnostics (waits on
`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`.
- [x] **Editor packaging.** A minimal VS Code extension (launch the
+59 -4
View File
@@ -2,7 +2,7 @@
use vfmt_core::cache;
use vfmt_core::config::FileConfig;
use vlog_formatter::Config;
use vlog_formatter::{Config, LineRanges};
/// Which tool this invocation runs.
///
@@ -58,6 +58,9 @@ pub struct Options {
pub line_length: Option<usize>,
/// `--indent`, if given; otherwise the config file decides.
pub indent: Option<usize>,
/// `--lines`: format only the constructs meeting these lines. `None` is a
/// whole-file run.
pub lines: Option<LineRanges>,
/// `check` only: how diagnostics are rendered.
pub output_format: OutputFormat,
/// `check` only: apply safe fixes and write the files back.
@@ -110,9 +113,11 @@ impl Options {
/// True when this run may consult and update the cache. `--stdout`
/// turns it off because every file's text has to be printed, and a
/// skipped file has none.
/// skipped file has none; `--lines` turns it off because a partially
/// formatted file is not the "already formatted" verdict the cache
/// stores, and reading a hit would skip the very lines the caller named.
pub fn cache_enabled(&self) -> bool {
!self.no_cache && !self.stdout
!self.no_cache && !self.stdout && self.lines.is_none()
}
/// The cache directory, resolved against the current directory when it
@@ -155,6 +160,12 @@ OPTIONS:
--threads <N> worker threads used to format files (default: one per
logical CPU). `--threads 1` formats on a single worker;
the output and exit code are identical either way
--lines <M-N> format only the constructs meeting these 1-based,
inclusive line ranges and emit every other byte
exactly as written; comma-separated (`--lines
3-9,40`) and repeatable. Requires explicit file
arguments or `-`, never a directory, 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
@@ -200,6 +211,14 @@ CONFIGURATION:
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`). A command line flag overrides the file.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
is laid out, everything else comes back byte-for-byte. A module or package
is descended into — its header and its `endmodule` stay as written unless
they are themselves selected, and only the body items that are selected are
laid out. Nothing smaller than an item is: selecting one statement lays out
the whole `always` block around it. `// verilog_format: off` still wins.
EXIT CODES:
0 nothing to do: files were formatted, --check/--diff found no change,
or `check` found no violations (or fixed all of them)
@@ -231,6 +250,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
exclude: Vec::new(),
line_length: None,
indent: None,
lines: None,
output_format: OutputFormat::Text,
fix: false,
unsafe_fixes: false,
@@ -238,6 +258,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
ignore: Vec::new(),
inputs: Vec::new(),
};
let mut line_specs: Vec<String> = Vec::new();
let mut args = args.peekable();
// The subcommand, if there is one, is the very first argument — so every
// command line that worked before subcommands existed still formats.
@@ -287,6 +308,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--indent requires a value")?;
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
}
"--lines" => {
let v = args.next().ok_or("--lines requires a value")?;
line_specs.push(v);
}
"--output-format" => {
let v = args.next().ok_or("--output-format requires a value")?;
opts.output_format = match v.as_str() {
@@ -321,6 +346,11 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
if opts.inputs.is_empty() {
return Err("no input files (try `vfmt --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.
if !line_specs.is_empty() {
opts.lines = Some(LineRanges::parse(&line_specs.join(","))?);
}
if opts.diff && opts.stdout {
return Err("--diff cannot be combined with --stdout".to_string());
}
@@ -345,7 +375,12 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
];
let format_only = [(opts.check, "--check"), (opts.diff, "--diff"), (opts.stdout, "--stdout")];
let format_only = [
(opts.check, "--check"),
(opts.diff, "--diff"),
(opts.stdout, "--stdout"),
(opts.lines.is_some(), "--lines"),
];
match opts.command {
Command::Format => {
for (given, flag) in lint_only {
@@ -460,6 +495,26 @@ mod tests {
assert!(parse(&["check", "--no-cache", "--cache-dir", "x", "rtl"]).is_ok());
}
#[test]
fn lines_accepts_both_the_comma_and_the_repeated_form() {
let one = parse(&["--lines", "3-9,20", "a.sv"]).unwrap();
let many = parse(&["--lines", "20", "--lines", "3-9", "a.sv"]).unwrap();
let spans = [(3, 9), (20, 20)];
assert_eq!(one.lines.as_ref().unwrap().spans(), spans);
assert_eq!(many.lines.as_ref().unwrap().spans(), spans, "order does not matter");
assert!(parse(&["a.sv"]).unwrap().lines.is_none());
assert!(parse(&["--lines"]).is_err());
assert!(parse(&["--lines", "5-1", "a.sv"]).is_err());
}
#[test]
fn lines_turns_the_cache_off_and_is_not_a_linter_flag() {
// A partially formatted file is not the "already formatted" verdict
// the cache stores, and a hit would skip the named lines outright.
assert!(!parse(&["--lines", "1", "a.sv"]).unwrap().cache_enabled());
assert!(parse(&["check", "--lines", "1", "a.sv"]).is_err());
}
#[test]
fn gitignore_is_honored_unless_switched_off() {
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
+25 -8
View File
@@ -28,7 +28,7 @@ use args::{Command, Options};
use vfmt_core::cache::{content_hash, Cache, Entry};
use vfmt_core::config::Discovery;
use vfmt_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_source, Config};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
@@ -102,7 +102,7 @@ fn run_stdin(opts: &Options) -> ExitCode {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
let out = match format_contained(&src, &config) {
let out = match format_contained(&src, &config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => {
eprintln!("error: {name}: {e}");
@@ -234,7 +234,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
if cache.is_clean(file, entry_for(hash, config)) {
return FileResult::plain(Outcome::Cached);
}
let out = match format_contained(&src, config) {
let out = match format_contained(&src, config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
};
@@ -288,6 +288,11 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
if input == "-" {
return Err("`-` cannot be combined with file arguments".to_string());
}
// A line range names lines of *a file*; over a directory it would
// mean "line 12 of everything", which is never what anyone meant.
if opts.lines.is_some() && Path::new(input).is_dir() {
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
}
@@ -337,10 +342,18 @@ fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, error
}
}
/// Formats one source text, reporting a panic inside the formatter as an
/// ordinary error so the rest of the run can continue.
fn format_contained(src: &str, config: &Config) -> Result<String, String> {
match catch_panic(|| format_source(src, config)) {
/// Formats one source text — all of it, or only the constructs meeting
/// `lines` — reporting a panic inside the formatter as an ordinary error so
/// the rest of the run can continue.
fn format_contained(
src: &str,
config: &Config,
lines: Option<&LineRanges>,
) -> Result<String, String> {
match catch_panic(|| match lines {
Some(lines) => format_range(src, config, lines),
None => format_source(src, config),
}) {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
Err(msg) => Err(format!("panicked while formatting: {msg}")),
@@ -441,7 +454,11 @@ mod tests {
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default()).unwrap_err();
let err = format_contained("module", &Config::default(), None).unwrap_err();
assert!(err.contains("parse error"), "{err}");
// A range run parses just as strictly: it cannot rescue broken input.
let lines = LineRanges::parse("1").expect("range");
let err = format_contained("module", &Config::default(), Some(&lines)).unwrap_err();
assert!(err.contains("parse error"), "{err}");
}
}
+130
View File
@@ -1331,6 +1331,136 @@ fn stdout_mode_prints_every_file_even_when_the_cache_is_warm() {
assert_eq!(stdout(&out), FORMATTED, "--stdout must print, never skip");
}
// ------------------------------------------------------------------
// --lines (range formatting)
// ------------------------------------------------------------------
/// Three items, each needing a different amount of work, so a range's reach is
/// visible line by line.
const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n";
#[test]
fn lines_formats_only_the_constructs_it_names() {
let dir = TempDir::new("lines");
let path = dir.write("a.sv", THREE);
let out = run(&["--stdout", "--lines", "2", &path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stdout(&out), "module m;\n wire a;\n wire b;\nendmodule\n");
// The comma form and the repeated form are the same thing.
let both = "module m;\n wire a;\n wire b;\nendmodule\n";
assert_eq!(stdout(&run(&["--stdout", "--lines", "2,3", &path])), both);
assert_eq!(stdout(&run(&["--stdout", "--lines", "2", "--lines", "3", &path])), both);
// In place, and only the named line moved.
let out = run(&["--lines", "3", &path]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), "module m;\n wire a;\n wire b;\nendmodule\n");
}
#[test]
fn lines_combines_with_check_and_diff() {
let dir = TempDir::new("lines-check");
let path = dir.write("a.sv", THREE);
// Line 4 is `endmodule`, already as the formatter would write it.
let out = run(&["--check", "--lines", "4", &path]);
assert_eq!(code(&out), 0, "nothing to change must exit 0: {}", stdout(&out));
let out = run(&["--check", "--lines", "2", &path]);
assert_eq!(code(&out), 1, "would-change must exit 1");
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
assert_eq!(dir.read("a.sv"), THREE, "--check must not write");
let out = run(&["--diff", "--lines", "2", &path]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("- wire a;") && text.contains("+ wire a;"), "{text}");
// Only the selected line shows up as a change; `wire b` is context only.
let changed: Vec<&str> = text
.lines()
.filter(|l| l.starts_with(['+', '-']) && !l.starts_with("+++") && !l.starts_with("---"))
.collect();
assert_eq!(changed, ["- wire a;", "+ wire a;"], "{text}");
}
#[test]
fn lines_works_on_stdin() {
let out = run_with_stdin(&["--lines", "3", "--stdin-filename", "rtl/top.sv", "-"], THREE);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stdout(&out), "module m;\n wire a;\n wire b;\nendmodule\n");
let out = run_with_stdin(&["--check", "--lines", "2", "-"], THREE);
assert_eq!(code(&out), 1);
assert_eq!(stdout(&out), "would reformat: <stdin>\n");
}
#[test]
fn lines_is_deterministic_and_settles() {
let dir = TempDir::new("lines-idem");
let path = dir.write("a.sv", THREE);
let once = stdout(&run(&["--stdout", "--lines", "2", &path]));
assert_eq!(stdout(&run(&["--stdout", "--lines", "2", &path])), once, "same input, same output");
// Formatting the output again with the same ranges changes nothing here,
// and `--check` is how a caller sees that.
dir.write("a.sv", &once);
assert_eq!(code(&run(&["--check", "--lines", "2", &path])), 0);
// A whole-file run afterwards may still have work to do — that is the
// feature, not a leftover.
assert_eq!(code(&run(&["--check", &path])), 1);
}
#[test]
fn lines_refuses_a_directory_and_a_bad_range() {
let dir = TempDir::new("lines-bad");
dir.write("a.sv", THREE);
let out = run(&["--lines", "2", &dir.root()]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--lines needs a file, not a directory"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), THREE, "nothing is written when the arguments are wrong");
for spec in ["5-1", "0-3", "", "x"] {
let out = run(&["--lines", spec, &dir.write("b.sv", THREE)]);
assert_eq!(code(&out), 2, "spec {spec:?}");
}
let out = run(&["--lines"]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--lines requires a value"), "{}", stderr(&out));
// 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));
}
#[test]
fn lines_neither_reads_nor_writes_the_cache() {
let dir = TempDir::new("lines-cache");
let path = dir.write("a.sv", FORMATTED);
let cache = dir.cache();
// Warm the cache with a whole-file run, then confirm a range run does not
// take the shortcut: a partial format is not the "already formatted"
// verdict the cache stores.
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
assert!(stderr(&out).contains("from cache"), "the cache is warm: {}", stderr(&out));
let out = run_raw(&["--check", "--lines", "1", &path, "--cache-dir", &cache]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
// And a range run on a file the cache has never seen writes no entry.
let fresh = TempDir::new("lines-cache-2");
let fresh_path = fresh.write("a.sv", FORMATTED);
let fresh_cache = fresh.cache();
assert_eq!(code(&run_raw(&["--lines", "1", &fresh_path, "--cache-dir", &fresh_cache])), 0);
assert!(!fresh.cache_file().exists(), "a range run must not seed the cache");
}
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
let mut child = Command::new(VFMT)
.args(args)
+110 -6
View File
@@ -1,14 +1,17 @@
//! `textDocument/formatting`.
//! `textDocument/formatting` and `textDocument/rangeFormatting`.
//!
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
//! this handler keeps it: either one whole-document edit built from verified
//! output, or no edit at all and an error for the user to read.
//! these handlers keep it: either one whole-document edit built from verified
//! output, or no edit at all and an error for the user to read. That holds for
//! the range request too — its output is verified over the whole buffer, and
//! what makes it a *range* format is which constructs it laid out, not which
//! bytes it was allowed to replace.
use std::path::Path;
use lsp_types::{FormattingOptions, TextEdit};
use lsp_types::{FormattingOptions, Range, TextEdit};
use vfmt_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_source, Config};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use crate::state::Document;
@@ -58,6 +61,36 @@ pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, S
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
}
/// Format the constructs a selection reaches, and nothing else.
///
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
/// wants 1-based inclusive *lines*, so only the line numbers survive the
/// conversion. An end position at character 0 still names its line — an
/// editor's "select these three lines" ends at the start of the fourth — so
/// a range that stops at a line's very beginning does not drag that line in
/// unless it is also where the range started.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
/// buffer only where it decided to differ.
pub fn range_formatting(
doc: &Document,
config: &Config,
range: Range,
) -> Result<Option<TextEdit>, String> {
let first = range.start.line.saturating_add(1);
// An end at character 0 of a later line is the start of that line, not
// any of its content.
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
let last = if ends_before_its_line { range.end.line } else { range.end.line + 1 };
let lines = LineRanges::new([(first, last.max(first))])?;
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
if formatted == doc.text {
return Ok(None);
}
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
}
/// The indent width governing a buffer, for a lint fix that has to write
/// spaces where a tab was.
///
@@ -112,7 +145,7 @@ fn config_from(file: &FileConfig, options: &FormattingOptions) -> Config {
mod tests {
use super::*;
use crate::state::Workspace;
use lsp_types::Uri;
use lsp_types::{Position, Uri};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -289,6 +322,77 @@ mod tests {
assert_eq!(settings.config.indent_width, 4, "the tab size is all there is");
}
/// Three items, one per line, so a range's reach is visible line by line.
const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n";
fn at(start_line: u32, start_char: u32, end_line: u32, end_char: u32) -> Range {
Range {
start: Position { line: start_line, character: start_char },
end: Position { line: end_line, character: end_char },
}
}
fn ranged(text: &str, range: Range) -> Result<Option<TextEdit>, String> {
let (ws, uri) = document(text);
let doc = ws.document(&uri).expect("open");
range_formatting(doc, &settings_for(doc, &options(2, true)).config, range)
}
#[test]
fn a_range_formats_only_the_lines_it_covers() {
// A cursor sitting on line 2 (0-based line 1) with nothing selected.
let edit = ranged(THREE, at(1, 4, 1, 4)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
// And the reply is still one whole-document edit.
assert_eq!(edit.range.start, Position { line: 0, character: 0 });
assert_eq!(edit.range.end.line, 4);
}
#[test]
fn a_selection_ending_at_the_start_of_a_line_stops_before_it() {
// "Select these two lines" in an editor ends at line 3, character 0.
let edit = ranged(THREE, at(1, 0, 3, 0)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
// One line only, ending where it began.
let edit = ranged(THREE, at(2, 0, 3, 0)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
}
#[test]
fn a_range_over_nothing_formattable_produces_no_edit() {
// Line 4 is `endmodule`, already written the way the formatter writes
// it, so there is nothing to send.
assert_eq!(ranged(THREE, at(3, 0, 3, 9)).expect("formats"), None);
}
#[test]
fn a_range_whose_end_is_past_the_document_still_answers() {
let edit = ranged(THREE, at(0, 0, 99, 0)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
}
#[test]
fn a_range_over_multi_byte_content_lands_on_the_right_lines() {
// The character columns are UTF-16 units; only the *lines* reach the
// engine, so the emoji line must not shift which item is formatted.
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
let edit = ranged(text, at(2, 0, 2, 11)).expect("formats").expect("changed");
assert_eq!(
edit.new_text,
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"
);
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
}
#[test]
fn an_unparsable_buffer_produces_no_range_edit_either() {
// Range formatting cannot rescue broken input; the strict parse still
// has to succeed.
let message =
ranged("module m;\n wire ;\nendmodule\n", at(0, 0, 0, 9)).expect_err("must refuse");
assert!(!message.is_empty(), "the user needs something to read");
}
#[test]
fn an_unparsable_buffer_produces_no_edit() {
let (ws, uri) = document("module m;\n wire ;\nendmodule\n");
+2 -1
View File
@@ -59,6 +59,7 @@ fn capabilities() -> ServerCapabilities {
position_encoding: Some(PositionEncodingKind::UTF16),
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
document_formatting_provider: Some(OneOf::Left(true)),
document_range_formatting_provider: Some(OneOf::Left(true)),
definition_provider: Some(OneOf::Left(true)),
references_provider: Some(OneOf::Left(true)),
hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
@@ -121,6 +122,7 @@ mod tests {
fn every_advertised_capability_is_implemented() {
let caps = capabilities();
assert!(caps.document_formatting_provider.is_some());
assert!(caps.document_range_formatting_provider.is_some());
assert!(caps.definition_provider.is_some());
assert!(caps.references_provider.is_some());
assert!(caps.hover_provider.is_some());
@@ -129,7 +131,6 @@ mod tests {
assert!(caps.semantic_tokens_provider.is_some());
assert!(caps.code_action_provider.is_some());
// Deliberately absent until the engines exist — see the README.
assert!(caps.document_range_formatting_provider.is_none(), "no --lines yet");
assert!(caps.completion_provider.is_none());
assert!(caps.rename_provider.is_none());
}
+40 -13
View File
@@ -14,16 +14,16 @@ use lsp_types::notification::{
LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
CodeActionRequest, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, References,
Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest,
CodeActionRequest, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest,
RangeFormatting, References, Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
CodeActionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams,
ReferenceParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, LogMessageParams, MessageType,
Position, PublishDiagnosticsParams, ReferenceParams, SemanticTokensParams,
SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
@@ -77,6 +77,7 @@ impl Server {
let method = request.method.clone();
let result = match method.as_str() {
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
@@ -166,7 +167,27 @@ impl Server {
// 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
// the file — a format-on-save loop would otherwise repeat it forever.
if let Some(problem) = settings.problem {
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// `textDocument/rangeFormatting`, on the same engine and the same
/// all-or-nothing contract as whole-document formatting.
fn range_formatting(
&mut self,
params: DocumentRangeFormattingParams,
) -> Result<Value, Failure> {
let uri = params.text_document.uri;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
let settings = format::settings_for(doc, &params.options);
let result = format::range_formatting(doc, &settings.config, params.range);
self.warn_about_config(&uri, settings.problem);
self.edits(result)
}
/// Say once per change of a file that its `vfmt.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,
@@ -174,15 +195,21 @@ impl Server {
);
}
}
}
/// One edit, none, or — when the formatter refused — none plus the reason.
///
/// It never emits partial output (CLAUDE.md invariant #1), so neither do
/// we. Diagnostics are not used for the failure: they belong to the parse
/// pass and are cleared on the next keystroke, which would erase an
/// explicit format failure the user asked for.
fn edits(
&mut self,
result: Result<Option<lsp_types::TextEdit>, String>,
) -> Result<Value, Failure> {
match result {
// A whole-document edit, or none when nothing changed.
Ok(Some(edit)) => to_value(vec![edit]),
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
// The formatter refused. It never emits partial output (CLAUDE.md
// invariant #1), so neither do we: no edit, and the reason goes to
// the user as a message. Diagnostics are not used for this — they
// belong to the parse pass and are cleared on the next keystroke,
// which would erase an explicit format failure the user asked for.
Err(message) => {
self.show_message(MessageType::ERROR, format!("vfmt: cannot format — {message}"));
to_value(Vec::<lsp_types::TextEdit>::new())
+69
View File
@@ -168,6 +168,75 @@ fn a_broken_vfmt_toml_warns_once_and_still_formats() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A UTF-16 boundary in the buffer: the emoji line is two lines above the one
/// the range names, so a byte-vs-UTF-16 confusion would format the wrong item.
const MULTI_BYTE: &str = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
#[test]
fn range_formatting_is_advertised_and_formats_only_the_selection() {
let dir = temp_dir("rangefmt");
let file = dir.join("m.sv");
std::fs::write(&file, MULTI_BYTE).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let request = |id: u32, sl: u32, sc: u32, el: u32, ec: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":{sc}}},"end":{{"line":{el},"character":{ec}}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(MULTI_BYTE).expect("json")
)),
// "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.
request(3, 4, 0, 4, 9),
request(4, 0, 0, 99, 0),
// A cursor on the emoji comment: a leading comment belongs to its
// item's unit, so the declaration under it is what gets laid out.
request(5, 1, 8, 1, 8),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
assert_eq!(
initialize["result"]["capabilities"]["documentRangeFormattingProvider"],
serde_json::json!(true),
"the capability must be advertised now that --lines exists"
);
assert_eq!(
new_text(&messages, 2),
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
"only the selected line, and the emoji survives"
);
let idle = messages.iter().find(|m| m["id"] == 3).expect("response");
assert_eq!(idle["result"].as_array().expect("an array").len(), 0, "nothing to change");
assert_eq!(
new_text(&messages, 5),
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
"a leading comment selects the item it belongs to"
);
assert_eq!(
new_text(&messages, 4),
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n",
"a range over the whole buffer is a whole-file format"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A file with a tab (`no-tabs`, Safe fix) and a trailing space
/// (`no-trailing-whitespace`, Safe fix) — and a name matching its module, so
/// `module-filename` stays quiet and every finding here is fixable.
+2 -2
View File
@@ -245,7 +245,7 @@ fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
/// The start of the line `at` sits on, when nothing but whitespace precedes it
/// there — otherwise `at` itself, so a fence sharing its line with another
/// comment does not swallow it.
fn line_start(src: &str, at: usize) -> usize {
pub(crate) fn line_start(src: &str, at: usize) -> usize {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
match src.get(bol..at) {
Some(before) if before.chars().all(char::is_whitespace) => bol,
@@ -254,7 +254,7 @@ fn line_start(src: &str, at: usize) -> usize {
}
/// Extend `end` over the comments written after it on the same line.
fn with_trailing_comments(src: &str, end: usize) -> usize {
pub(crate) fn with_trailing_comments(src: &str, end: usize) -> usize {
let mut at = end;
loop {
let Some(rest) = src.get(at..) else { return at };
+160 -20
View File
@@ -8,6 +8,7 @@ use crate::align::{self, Align, ColSpec, Row};
use crate::doc::*;
use crate::fence::{self, Region};
use crate::printer::{contains_hard_line, Printer};
use crate::range::{self, Split};
use crate::verify::{
line_starts_inside_string, verify_convergence, verify_equivalence, VerificationError,
};
@@ -84,12 +85,50 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
Ok(output)
}
/// Format only the constructs intersecting `lines`, emitting every other byte
/// exactly as it was written.
///
/// The safety net is the same one and it still runs over the *whole* output:
/// the spliced bytes are source text, the laid-out islands are ordinary
/// formatter output, and both checks are global. Convergence is checked by
/// replaying the same per-item decisions against the output — see
/// `docs/features/range-formatting/README.md`.
pub fn format_range(
source: &str,
config: &Config,
lines: &range::LineRanges,
) -> Result<String, FormatError> {
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
let selection = range::select(source, &file, lines);
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
let again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?;
verify_convergence(&output, &again)?;
Ok(output)
}
/// A single unverified formatting pass: parse, lay out, print.
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let regions = fence::collect(source, &file);
let fmt = Fmt { cfg: config, src: source, regions };
let doc = fmt.file(&file);
Ok(render(&Fmt { cfg: config, src: source, regions, splits: Vec::new() }, &file, config))
}
/// The same pass, restricted to the units `selection` picked out.
fn format_selected(
source: &str,
config: &Config,
selection: &range::Selection,
) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let plan = range::plan(source, &file, selection);
let fmt = Fmt { cfg: config, src: source, regions: plan.regions, splits: plan.splits };
Ok(render(&fmt, &file, config))
}
/// Lay the file out and print it, ending in exactly one newline.
fn render(fmt: &Fmt, file: &SourceFile, config: &Config) -> String {
let doc = fmt.file(file);
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
let mut out = printer.print(&doc);
// Normalize trailing whitespace: exactly one final newline.
@@ -97,16 +136,20 @@ fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Err
out.pop();
}
out.push('\n');
Ok(out)
out
}
struct Fmt<'a> {
cfg: &'a Config,
/// The text the AST was parsed from — what `// verilog_format: off`
/// regions are spliced out of.
/// regions and `--lines` runs are spliced out of.
src: &'a str,
/// The fenced regions of `src`, sorted and non-overlapping.
/// The byte ranges of `src` emitted exactly as written, sorted and
/// non-overlapping: fenced regions, plus whatever a range run left alone.
regions: Vec<Region>,
/// Scope-bearing items a range run descends into. Empty for a whole-file
/// run.
splits: Vec<Split>,
}
/// What a comment turns into: itself, the verbatim region it opens, or
@@ -260,12 +303,31 @@ impl<'a> Fmt<'a> {
}
}
/// True if this node's code is inside a fenced region, i.e. its bytes are
/// already being emitted verbatim and it must not be formatted.
fn is_fenced(&self, span: TextRange) -> bool {
/// True if this node's code is inside a verbatim region, i.e. its bytes
/// are already being emitted as written and it must not be laid out.
fn is_verbatim(&self, span: TextRange) -> bool {
fence::region_at(&self.regions, span.start as usize).is_some()
}
/// The verbatim region this byte offset *opens*, if it opens one.
///
/// A region's opener is the first byte of the first unit it covers: a
/// fence comment, the first leading comment of a run's first item, or —
/// when that item has no leading comments — the item's own code.
fn opens_at(&self, at: usize) -> Option<&Region> {
fence::region_at(&self.regions, at).filter(|r| r.fence == at)
}
/// The split recorded for the item starting at this byte offset.
fn split_at(&self, at: usize) -> Option<&Split> {
self.splits.iter().find(|s| s.item == at)
}
/// A verbatim slice of the source, by byte range.
fn slice(&self, (start, end): (usize, usize)) -> Doc {
Doc::Verbatim(self.src.get(start..end).unwrap_or_default().to_string())
}
/// A fenced region's source bytes.
///
/// A slice that is not on a character boundary cannot happen — every
@@ -672,7 +734,7 @@ impl<'a> Fmt<'a> {
/// the way it always has and splits the group in two.
fn param_decl_row(&self, item: &Item) -> Option<Row> {
let ItemKind::ParamDecl(d) = &item.kind else { return None };
if !item.meta.attrs.is_empty() || self.is_fenced(item.span) {
if !item.meta.attrs.is_empty() || self.is_verbatim(item.span) {
return None;
}
let [decl] = &d.declarators[..] else { return None };
@@ -802,12 +864,22 @@ impl<'a> Fmt<'a> {
concat(self.item_docs(item, None, depth))
}
/// One item: its leading comments, then — unless a fenced region is
/// One item: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its attributes, code and trailing
/// comment. Comments before the `off` fence are still emitted; comments
/// are never dropped.
fn item_docs(&self, item: &Item, align: Option<&Align>, depth: usize) -> Vec<Doc> {
if self.is_fenced(item.span) {
if let Some(split) = self.split_at(item.span.start as usize) {
if let Some(docs) = self.split_item(item, split, depth) {
return docs;
}
}
// A verbatim run whose first item carries no leading comment opens at
// the item's own code; there is no comment to emit the bytes from.
if let Some(region) = self.opens_at(item.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(item.span) {
// The item's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&item.meta);
@@ -824,6 +896,65 @@ impl<'a> Fmt<'a> {
docs
}
/// A scope-bearing item a range run descends into.
///
/// Its header and its closing keyword are the source's own bytes unless
/// the caller's lines reached them, and its body is laid out one item at a
/// time — which is what keeps a three-line edit from reformatting a
/// two-thousand-line module. `None` for any other item kind, which
/// `range.rs` never records a split for.
fn split_item(&self, item: &Item, split: &Split, depth: usize) -> Option<Vec<Doc>> {
let (items, dangling) = match &item.kind {
ItemKind::Module(m) => (&m.items[..], &m.dangling[..]),
ItemKind::Package { items, dangling, .. } => (&items[..], &dangling[..]),
_ => return None,
};
let mut docs = Vec::new();
match split.head {
Some(range) => docs.push(self.slice(range)),
None => {
docs.extend(self.leading(&item.meta));
docs.push(self.head_doc(&item.kind, depth)?);
}
}
let mut body = Vec::new();
if !items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(items, depth + 1));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
match split.tail {
// The slice reaches over the comment written after the keyword,
// so the trailing comment must not be printed a second time.
Some(range) => docs.push(self.slice(range)),
None => {
docs.push(Self::tail_doc(&item.kind)?);
docs.extend(self.trailing(&item.meta));
}
}
Some(docs)
}
/// A split item's header, laid out.
fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option<Doc> {
match kind {
ItemKind::Module(m) => Some(self.module_head(m, depth)),
ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {name};"))),
_ => None,
}
}
/// A split item's closing keyword, laid out.
fn tail_doc(kind: &ItemKind) -> Option<Doc> {
match kind {
ItemKind::Module(m) => Some(Self::closing("endmodule", &m.end_label)),
ItemKind::Package { end_label, .. } => Some(Self::closing("endpackage", end_label)),
_ => None,
}
}
fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc {
match kind {
ItemKind::Module(m) => self.module(m, depth),
@@ -892,6 +1023,24 @@ impl<'a> Fmt<'a> {
// ------------------------------------------------------------------
fn module(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![self.module_head(m, depth)];
let mut body = Vec::new();
if !m.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&m.items, depth + 1));
}
body.extend(self.dangling(&m.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(Self::closing("endmodule", &m.end_label));
concat(docs)
}
/// A module header: everything through the `;` that closes it.
///
/// Split out from the body so a range run can keep one and lay out the
/// other (`range.rs`); a whole-file run always emits both.
fn module_head(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![text(format!("{} {}", m.kw, m.name))];
let has_imports = !m.imports.is_empty();
if has_imports {
@@ -963,15 +1112,6 @@ impl<'a> Fmt<'a> {
docs.push(text(";"));
}
}
let mut body = Vec::new();
if !m.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&m.items, depth + 1));
}
body.extend(self.dangling(&m.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(Self::closing("endmodule", &m.end_label));
concat(docs)
}
+3 -1
View File
@@ -5,7 +5,9 @@ pub mod doc;
pub mod fence;
pub mod format;
pub mod printer;
pub mod range;
pub mod verify;
pub use format::{format_source, Config, FormatError};
pub use format::{format_range, format_source, Config, FormatError};
pub use range::LineRanges;
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
+531
View File
@@ -0,0 +1,531 @@
//! `--lines M-N` range formatting: lay out only what the caller selected.
//!
//! A range is morally an inverted fence. The unit of formatting is an *item*:
//! one whose lines intersect a requested range is laid out exactly as a
//! whole-file run would lay it out, and every other item is emitted as the
//! source bytes it was written with — the splice `fence.rs` already does, over
//! ranges the caller chose instead of ranges a comment marked.
//!
//! Two things make that more than a byte filter:
//!
//! 1. **Runs.** Consecutive unselected items are merged into *one* verbatim
//! slice, so the blank lines between them survive untouched. Emitting them
//! one at a time would let the item separator normalize the gaps.
//! 2. **Splits.** A module whose body is 2000 lines long must not reformat
//! whole because three of them were edited, so a scope-bearing item is
//! descended into: its header and its `endmodule` stay verbatim unless they
//! intersect, and only the body items that intersect are laid out.
//!
//! Full spec: `docs/features/range-formatting/README.md`.
use crate::fence::{self, Region};
use vlog_parser::ast::{Item, ItemKind, SourceFile};
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
/// The lines a caller asked to format: 1-based, inclusive, sorted, disjoint.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LineRanges {
spans: Vec<(u32, u32)>,
}
impl LineRanges {
/// Build from `(first, last)` pairs, merging what overlaps or touches.
///
/// A reversed range is a typo, not an intent, so it is refused; a range
/// running past the end of the file is not, because a wrapper deriving
/// ranges from a diff cannot know where the file ends.
pub fn new(spans: impl IntoIterator<Item = (u32, u32)>) -> Result<LineRanges, String> {
let mut spans: Vec<(u32, u32)> = spans.into_iter().collect();
for &(first, last) in &spans {
if first == 0 || last == 0 {
return Err("line numbers start at 1".to_string());
}
if first > last {
return Err(format!("reversed line range: {first}-{last}"));
}
}
if spans.is_empty() {
return Err("no line ranges given".to_string());
}
spans.sort_unstable();
let mut merged: Vec<(u32, u32)> = Vec::with_capacity(spans.len());
for (first, last) in spans {
match merged.last_mut() {
// `first == prev.1 + 1` is adjacent, not overlapping, and
// merging it changes no answer while shortening the list.
Some(prev) if first <= prev.1.saturating_add(1) => prev.1 = prev.1.max(last),
_ => merged.push((first, last)),
}
}
Ok(LineRanges { spans: merged })
}
/// Parse a `--lines` value: `M-N`, a single `M`, or a comma-separated list
/// of either.
pub fn parse(spec: &str) -> Result<LineRanges, String> {
let mut spans = Vec::new();
for piece in spec.split(',') {
let piece = piece.trim();
if piece.is_empty() {
return Err(format!("empty line range in `{spec}`"));
}
let (first, last) = match piece.split_once('-') {
Some((a, b)) => (number(a, spec)?, number(b, spec)?),
None => {
let n = number(piece, spec)?;
(n, n)
}
};
spans.push((first, last));
}
LineRanges::new(spans)
}
/// The ranges, as sorted disjoint 1-based inclusive pairs.
pub fn spans(&self) -> &[(u32, u32)] {
&self.spans
}
/// Does any requested range meet the inclusive line span `first..=last`?
fn hits(&self, first: u32, last: u32) -> bool {
self.spans.iter().any(|&(a, b)| a <= last && first <= b)
}
}
fn number(text: &str, spec: &str) -> Result<u32, String> {
text.trim().parse().map_err(|_| format!("invalid line number `{text}` in `{spec}`"))
}
/// What range formatting does with one item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pick {
/// Emit the item's own bytes, exactly as written.
Verbatim,
/// Lay the item out, as a whole-file run would.
Format,
/// Lay out the item's *body* item by item. `head`/`tail` say whether the
/// item's own header and closing keyword are laid out too.
Split { head: bool, tail: bool },
}
/// The per-unit decisions of one range run.
///
/// Recorded once against the input and replayed against the formatted output.
/// That is what makes the convergence check meaningful when only part of a
/// file was formatted: the output has the same token stream as the input
/// (equivalence says so), hence the same item tree, hence the same walk order
/// — so the second pass reformats exactly the units the first one did, and any
/// drift shows up as a failed fixed point rather than as silent damage.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Selection {
picks: Vec<Pick>,
}
/// A scope-bearing item formatted from the inside out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Split {
/// `Item::span.start` of the item this describes — its identity.
pub item: usize,
/// Source bytes of the header, leading comments included; `None` when the
/// header is laid out instead.
pub head: Option<(usize, usize)>,
/// Source bytes of the closing keyword, its trailing comment included;
/// `None` when it is laid out instead.
pub tail: Option<(usize, usize)>,
}
/// Everything the formatter needs to lay out part of a file.
#[derive(Debug, Clone, Default)]
pub struct Plan {
/// Byte ranges emitted exactly as written, sorted and non-overlapping.
pub regions: Vec<Region>,
/// Items descended into, sorted by [`Split::item`].
pub splits: Vec<Split>,
}
/// Decide what each unit of `file` gets, from the lines the caller asked for.
pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
let mut planner = Planner::new(src, file, Mode::Lines(lines));
planner.scope(&file.items, &file.dangling);
Selection { picks: planner.picks }
}
/// Turn a [`Selection`] into the byte plan for `src`.
///
/// `src` must be the text `file` was parsed from; it need not be the text the
/// selection was made against.
pub fn plan(src: &str, file: &SourceFile, selection: &Selection) -> Plan {
let mut planner = Planner::new(src, file, Mode::Picks(&selection.picks));
planner.scope(&file.items, &file.dangling);
Plan { regions: normalize(planner.regions), splits: planner.splits }
}
/// Sort the collected regions and fold everything that overlaps into one.
///
/// Fenced regions and verbatim runs can overlap — a run swallows the fence
/// that made its items unformattable, and a fence closing inside the next
/// item's leading comments reaches past a run's end — and the formatter's
/// lookup wants a list sorted by both ends. The union is the right answer for
/// both: every byte in either region is source text either way, and the
/// earliest opener is where it gets emitted.
fn normalize(mut regions: Vec<Region>) -> Vec<Region> {
regions.sort_by_key(|r| (r.start, std::cmp::Reverse(r.end)));
let mut out: Vec<Region> = Vec::with_capacity(regions.len());
for region in regions {
match out.last_mut() {
Some(prev) if region.start < prev.end => {
prev.end = prev.end.max(region.end);
prev.fence = prev.fence.min(region.fence);
}
_ => out.push(region),
}
}
out
}
/// Where a decision comes from: the caller's lines, or an earlier run's.
#[derive(Clone, Copy)]
enum Mode<'a> {
Lines(&'a LineRanges),
Picks(&'a [Pick]),
}
/// The byte extents a split item is cut at.
#[derive(Debug, Clone, Copy)]
struct Extents {
head: (usize, usize),
tail: (usize, usize),
}
struct Planner<'a> {
src: &'a str,
index: LineIndex,
/// The fenced regions of `src`. A fenced item is never formatted, whatever
/// the caller's lines say: `// verilog_format: off` outranks `--lines`.
fences: Vec<Region>,
mode: Mode<'a>,
picks: Vec<Pick>,
cursor: usize,
regions: Vec<Region>,
splits: Vec<Split>,
}
impl<'a> Planner<'a> {
fn new(src: &'a str, file: &SourceFile, mode: Mode<'a>) -> Planner<'a> {
Planner {
src,
index: LineIndex::new(src),
fences: fence::collect(src, file),
mode,
picks: Vec::new(),
cursor: 0,
regions: Vec::new(),
splits: Vec::new(),
}
}
/// Walk one item-list scope. Returns whether anything in it is laid out,
/// which is what tells an enclosing item that it has to be descended into.
fn scope(&mut self, items: &[Item], dangling: &[Comment]) -> bool {
let mut touched = false;
// A run of consecutive verbatim units, as `(first byte, last byte)`.
let mut run: Option<(usize, usize, usize)> = None;
for item in items {
let pick = self.item(item);
touched |= pick != Pick::Verbatim;
let (start, end) = self.unit_extent(item);
match pick {
Pick::Verbatim => self.extend(&mut run, start, end),
_ => self.flush(&mut run),
}
}
for comment in dangling {
let (start, end) = (comment.span.start as usize, comment.span.end as usize);
match self.comment(comment) {
Pick::Verbatim => self.extend(&mut run, start, end),
_ => {
touched = true;
self.flush(&mut run);
}
}
}
self.flush(&mut run);
touched
}
/// Add one unit's bytes to the open run, opening it if there is none.
fn extend(&self, run: &mut Option<(usize, usize, usize)>, start: usize, end: usize) {
match run {
Some((_, _, last)) => *last = end,
None => *run = Some((fence::line_start(self.src, start), start, end)),
}
}
/// Close the open run, if any, and record it as a verbatim region.
fn flush(&mut self, run: &mut Option<(usize, usize, usize)>) {
if let Some((start, open, end)) = run.take() {
self.regions.push(Region { fence: open, start, end });
}
}
/// Decide one item, having first decided everything nested inside it.
fn item(&mut self, item: &Item) -> Pick {
let slot = self.reserve();
let extents = self.extents(item);
let touched = match scope_of(item) {
// The body is always walked, splittable or not, so the shape of
// the pick list depends on the item tree alone — which is what
// lets a selection be replayed against reformatted text.
Some((items, dangling)) => self.scope(items, dangling),
None => false,
};
let pick = self.decide(slot, item, extents, touched);
if let (Pick::Split { head, tail }, Some(e)) = (pick, extents) {
self.splits.push(Split {
item: item.span.start as usize,
head: (!head).then_some(e.head),
tail: (!tail).then_some(e.tail),
});
}
pick
}
/// Decide one dangling comment. It has no body and no header, so it is
/// laid out or emitted as written, nothing else.
fn comment(&mut self, comment: &Comment) -> Pick {
let slot = self.reserve();
let pick = match self.mode {
Mode::Picks(picks) => picks.get(slot).copied().unwrap_or(Pick::Verbatim),
Mode::Lines(lines) => {
let start = comment.span.start as usize;
if fence::region_at(&self.fences, start).is_some()
|| !self.hits(lines, start, comment.span.end as usize)
{
Pick::Verbatim
} else {
Pick::Format
}
}
};
self.record(slot, pick);
pick
}
fn decide(
&mut self,
slot: usize,
item: &Item,
extents: Option<Extents>,
touched: bool,
) -> Pick {
let pick = match self.mode {
Mode::Picks(picks) => picks.get(slot).copied().unwrap_or(Pick::Verbatim),
Mode::Lines(lines) => self.pick_from_lines(lines, item, extents, touched),
};
// A pick that asks for a split the text cannot be cut at would emit
// nothing for the header; fall back to laying the whole item out.
let pick = match pick {
Pick::Split { .. } if extents.is_none() => Pick::Format,
other => other,
};
self.record(slot, pick);
pick
}
fn pick_from_lines(
&self,
lines: &LineRanges,
item: &Item,
extents: Option<Extents>,
touched: bool,
) -> Pick {
// `// verilog_format: off` wins: the bytes stay whatever the caller
// selected, and the fence machinery is already emitting them.
if fence::region_at(&self.fences, item.span.start as usize).is_some() {
return Pick::Verbatim;
}
let Some(e) = extents else {
let (start, end) = self.unit_extent(item);
return if self.hits(lines, start, end) { Pick::Format } else { Pick::Verbatim };
};
let head = self.hits(lines, e.head.0, e.head.1);
let tail = self.hits(lines, e.tail.0, e.tail.1);
if head || tail || touched {
Pick::Split { head, tail }
} else {
Pick::Verbatim
}
}
/// The index this unit's pick lives at, advancing the cursor.
fn reserve(&mut self) -> usize {
let slot = self.cursor;
self.cursor += 1;
if matches!(self.mode, Mode::Lines(_)) {
self.picks.push(Pick::Verbatim);
}
slot
}
fn record(&mut self, slot: usize, pick: Pick) {
if let Some(entry) = self.picks.get_mut(slot) {
*entry = pick;
}
}
/// Does any requested range meet the lines the byte range `start..end`
/// occupies?
fn hits(&self, lines: &LineRanges, start: usize, end: usize) -> bool {
let first = self.index.line_col(start as u32).0;
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
lines.hits(first, last)
}
/// An item's whole unit: its leading comments through the comment written
/// after it on the same line.
fn unit_extent(&self, item: &Item) -> (usize, usize) {
let start = item
.meta
.leading
.first()
.map_or(item.span.start, |c| c.span.start.min(item.span.start));
(start as usize, fence::with_trailing_comments(self.src, item.span.end as usize))
}
/// Where a scope-bearing item can be cut into header, body and footer, or
/// `None` when it cannot be cut at all.
///
/// Every boundary has to fall on a line of its own, because a verbatim
/// slice is emitted at column zero and carries its own indentation. A
/// module written as `module m; wire a; endmodule` has no such line, so it
/// is laid out whole or not at all.
fn extents(&self, item: &Item) -> Option<Extents> {
let (items, dangling) = scope_of(item)?;
let head_start = own_line_start(self.src, self.unit_extent(item).0)?;
let first = items
.first()
.map(|i| self.unit_extent(i).0)
.or_else(|| dangling.first().map(|c| c.span.start as usize))?;
let head_end = trim_back(self.src, own_line_start(self.src, first)?);
if head_end <= head_start {
return None;
}
// The scope's dangling comments come after its last item, so they —
// not the item — are where the body ends when there are any.
let last = dangling
.last()
.map(|c| c.span.end as usize)
.or_else(|| items.last().map(|i| self.unit_extent(i).1))?;
let close = next_code(self.src, last)?;
if close >= item.span.end as usize {
return None;
}
let tail_start = own_line_start(self.src, close)?;
if tail_start < last {
return None;
}
let tail_end = fence::with_trailing_comments(self.src, item.span.end as usize);
Some(Extents { head: (head_start, head_end), tail: (tail_start, tail_end) })
}
}
/// The item scope an item carries, if it is one this feature descends into.
///
/// Modules and packages only. A `generate` region, a class or a `begin`…`end`
/// is an item scope too, but it has no header worth keeping apart from its
/// body, and the point of descending is to spare a 2000-line module body —
/// which is exactly the shape these two have. Everything else is one unit.
fn scope_of(item: &Item) -> Option<(&[Item], &[Comment])> {
match &item.kind {
ItemKind::Module(m) => Some((&m.items, &m.dangling)),
ItemKind::Package { items, dangling, .. } => Some((items, dangling)),
_ => None,
}
}
/// The start of `at`'s line, or `None` when anything but whitespace precedes
/// it there.
fn own_line_start(src: &str, at: usize) -> Option<usize> {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
src.get(bol..at).filter(|before| before.chars().all(char::is_whitespace)).map(|_| bol)
}
/// Walk `end` back over whitespace, so a slice never ends in the blank lines
/// that follow it.
fn trim_back(src: &str, end: usize) -> usize {
src.get(..end).map_or(end, |s| s.trim_end().len())
}
/// The first non-whitespace byte at or after `at`.
fn next_code(src: &str, at: usize) -> Option<usize> {
let rest = src.get(at..)?;
let trimmed = rest.trim_start();
if trimmed.is_empty() {
return None;
}
Some(at + rest.len() - trimmed.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranges_are_sorted_and_merged() {
let r = LineRanges::parse("10-12,1-3,2-5").expect("parses");
assert_eq!(r.spans(), [(1, 5), (10, 12)]);
// Adjacent ranges fold together; a bare number is one line.
assert_eq!(LineRanges::parse("1-2,3-4").expect("parses").spans(), [(1, 4)]);
assert_eq!(LineRanges::parse("7").expect("parses").spans(), [(7, 7)]);
assert_eq!(LineRanges::parse(" 4 - 6 ").expect("parses").spans(), [(4, 6)]);
}
#[test]
fn a_reversed_or_zero_range_is_refused() {
assert!(LineRanges::parse("5-1").is_err(), "reversed");
assert!(LineRanges::parse("0-3").is_err(), "lines are 1-based");
assert!(LineRanges::parse("1,,2").is_err(), "empty piece");
assert!(LineRanges::parse("").is_err());
assert!(LineRanges::parse("a-b").is_err());
assert!(LineRanges::parse("1-2-3").is_err());
assert!(LineRanges::new([]).is_err(), "no ranges at all");
}
#[test]
fn a_range_past_the_end_of_the_file_is_kept() {
// A wrapper deriving ranges from a diff cannot know where the file
// ends, so this clamps by simply matching no line.
let r = LineRanges::parse("900-1000").expect("parses");
assert!(!r.hits(1, 20));
assert!(r.hits(950, 960));
}
#[test]
fn overlapping_regions_fold_into_their_union() {
let regions = normalize(vec![
Region { fence: 30, start: 30, end: 40 },
Region { fence: 12, start: 10, end: 35 },
Region { fence: 0, start: 0, end: 5 },
]);
assert_eq!(
regions,
vec![Region { fence: 0, start: 0, end: 5 }, Region { fence: 12, start: 10, end: 40 }]
);
}
#[test]
fn a_line_start_is_only_its_own_when_nothing_but_space_precedes() {
assert_eq!(own_line_start("module m;\n wire a;\n", 12), Some(10));
assert_eq!(own_line_start("module m;\n wire a;\n", 10), Some(10));
assert_eq!(own_line_start("wire a; wire b;\n", 8), None);
assert_eq!(own_line_start("wire a;\n", 0), Some(0));
}
#[test]
fn the_helpers_walk_over_whitespace_in_both_directions() {
assert_eq!(trim_back("a;\n\n\n", 5), 2);
assert_eq!(next_code("a;\n\n endmodule\n", 2), Some(6));
assert_eq!(next_code("a;\n\n ", 2), None, "nothing but whitespace left");
}
}
+417
View File
@@ -0,0 +1,417 @@
//! `--lines` range formatting: only the selected constructs are laid out, and
//! every other byte comes back exactly as it was written.
//!
//! `.cases` tables cannot express a range, so this is where the engine's
//! contract lives. Spec: `docs/features/range-formatting/README.md`.
use std::fs;
use std::path::{Path, PathBuf};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
fn ranged(src: &str, spec: &str) -> String {
let lines = LineRanges::parse(spec).expect("range spec");
format_range(src, &Config::default(), &lines).expect("formats")
}
fn whole(src: &str) -> String {
format_source(src, &Config::default()).expect("formats")
}
/// Format twice with the same ranges and assert the second run changed
/// nothing.
///
/// This holds whenever the first run did not move the selected lines, which is
/// every case below; `a_line_shift_can_sweep_in_the_next_construct` is the
/// counterexample and the reason the *runtime* convergence check replays the
/// per-item decisions instead of the line numbers.
fn fixed_point(src: &str, spec: &str) -> String {
let out = ranged(src, spec);
assert_eq!(ranged(&out, spec), out, "a second run with the same ranges must change nothing");
out
}
const TWO_MODULES: &str = "\
// top note
module m (input a,output b);
wire x;
wire y;
assign x=a;
// dangling
endmodule // done
module n;
wire z;
endmodule
";
// ------------------------------------------------------------------
// The unit of formatting
// ------------------------------------------------------------------
#[test]
fn only_the_selected_body_item_is_laid_out() {
let out = fixed_point(TWO_MODULES, "3");
assert_eq!(
out,
"\
// top note
module m (input a,output b);
wire x;
wire y;
assign x=a;
// dangling
endmodule // done
module n;
wire z;
endmodule
"
);
}
#[test]
fn a_module_header_is_laid_out_without_its_body() {
// This is the whole point of descending: a three-line edit in the port
// list must not reflow two thousand lines of body.
let out = fixed_point(TWO_MODULES, "2");
assert!(out.contains("module m (input a, output b);"), "{out}");
assert!(out.contains(" wire x;"), "the body is untouched: {out}");
assert!(out.contains("endmodule // done"), "and so is the footer: {out}");
}
#[test]
fn the_closing_keyword_is_laid_out_on_its_own() {
let out = fixed_point(TWO_MODULES, "10");
assert!(out.contains("endmodule // done"), "{out}");
assert!(out.contains("module m (input a,output b);"), "the header stays: {out}");
assert!(out.contains(" wire x;"), "the body stays: {out}");
}
#[test]
fn an_unselected_module_is_emitted_verbatim() {
let out = fixed_point(TWO_MODULES, "3");
assert!(out.contains("module n;\n wire z;\nendmodule\n"), "{out}");
}
#[test]
fn a_range_that_meets_no_construct_changes_nothing() {
// Line 6 is blank, and a blank line belongs to no item. Selecting one is
// deliberately *not* an excuse to reformat the module around it.
assert_eq!(fixed_point(TWO_MODULES, "6"), TWO_MODULES);
// Neither is a range past the end of the file.
assert_eq!(fixed_point(TWO_MODULES, "900-1000"), TWO_MODULES);
}
#[test]
fn a_range_covering_the_file_is_a_whole_file_format() {
for src in [TWO_MODULES, PACKAGE, ALIGNED, WITH_FENCE] {
assert_eq!(ranged(src, "1-10000"), whole(src), "src: {src}");
}
}
#[test]
fn formatting_everything_afterwards_still_reaches_the_normal_output() {
// A partial run is not a fixed point of the *whole-file* formatter, and
// must not be: reformatting more later is the feature, not a bug.
let partial = ranged(TWO_MODULES, "3");
assert_ne!(partial, whole(TWO_MODULES));
assert_eq!(whole(&partial), whole(TWO_MODULES));
}
// ------------------------------------------------------------------
// Packages, generate regions, statements
// ------------------------------------------------------------------
const PACKAGE: &str = "\
package p;
localparam int A=1;
localparam int BBB=2;
localparam int C=3;
endpackage
";
#[test]
fn a_package_splits_the_same_way_a_module_does() {
assert_eq!(fixed_point(PACKAGE, "1"), PACKAGE.replacen("package p;", "package p;", 1));
let out = fixed_point(PACKAGE, "3");
assert_eq!(
out,
"package p;\n localparam int A=1;\n localparam int BBB = 2;\n \
localparam int C=3;\nendpackage\n"
);
}
const GENERATE: &str = "\
module m;
generate
if (X) begin
wire a;
wire bb;
end
endgenerate
endmodule
";
#[test]
fn a_generate_region_is_one_unit_and_reformats_whole() {
// Documented coarseness: only modules and packages are descended into,
// so selecting one line of a `generate` lays out all of it.
let out = fixed_point(GENERATE, "4");
assert!(out.contains(" wire a;"), "{out}");
assert!(out.contains(" wire bb;"), "the sibling reflowed too: {out}");
}
const ALWAYS: &str = "\
module m;
always @(posedge clk) begin
x <= 1;
y <= 2;
end
endmodule
";
#[test]
fn a_statement_is_never_the_unit_the_item_around_it_is() {
// Statements are deliberately not descended into this round.
let out = fixed_point(ALWAYS, "3");
assert!(out.contains(" x <= 1;"), "{out}");
assert!(out.contains(" y <= 2;"), "the whole block reflowed: {out}");
}
// ------------------------------------------------------------------
// Interaction rules
// ------------------------------------------------------------------
const WITH_FENCE: &str = "\
module m;
wire a;
// vfmt: off
wire b;
wire c;
// vfmt: on
wire d;
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.
for spec in ["3", "4", "5", "3-5"] {
assert_eq!(fixed_point(WITH_FENCE, spec), WITH_FENCE, "spec {spec}");
}
// Line 6 is the `on` fence, which is the *next* item's leading comment,
// so selecting it selects that item — and still not the region.
let out = fixed_point(WITH_FENCE, "6");
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
assert!(out.contains(" wire d;"), "{out}");
// And a range next to the fence still works, leaving the region alone.
let out = fixed_point(WITH_FENCE, "2");
assert!(out.contains(" wire a;"), "{out}");
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
}
const ALIGNED: &str = "\
module m;
localparam int A = 1;
localparam int BBBBB = 2;
localparam int C = 3;
endmodule
";
#[test]
fn an_alignment_group_breaks_at_a_range_boundary() {
// Alignment groups run across consecutive *items*, so a range boundary
// can fall inside one. The unselected members keep their bytes and leave
// the group; the selected ones align among themselves, exactly as a
// fenced member already does.
let out = fixed_point(ALIGNED, "2-3");
assert!(out.contains(" localparam int A = 1;\n localparam int BBBBB = 2;\n"), "{out}");
assert!(out.contains(" localparam int C = 3;\n"), "the outsider is untouched: {out}");
// A group of one has nothing to align to and formats flush.
let out = fixed_point(ALIGNED, "2");
assert!(out.contains(" localparam int A = 1;\n"), "{out}");
}
#[test]
fn a_file_that_does_not_parse_is_refused_whatever_the_range() {
// Range formatting cannot rescue broken input: the strict parse still has
// to succeed, so the answer is an error and an untouched file.
let broken = "module m;\n wire ;\nendmodule\n";
let lines = LineRanges::parse("2").expect("range spec");
let error = format_range(broken, &Config::default(), &lines).expect_err("must refuse");
assert!(error.to_string().contains("parse error"), "{error}");
// Even when the range names none of the broken lines.
let lines = LineRanges::parse("1").expect("range spec");
assert!(format_range(broken, &Config::default(), &lines).is_err());
}
// ------------------------------------------------------------------
// Bytes outside the range
// ------------------------------------------------------------------
#[test]
fn blank_lines_inside_a_verbatim_run_survive_untouched() {
let src = "module m;\n wire a;\n\n\n\n wire b;\nendmodule\n";
// Nothing selected inside the module body: the run keeps all three blanks.
assert_eq!(fixed_point(src, "3"), src);
// A boundary is where the item separator applies, and it collapses runs
// of blank lines to one — the same rule a fence boundary follows.
assert_eq!(fixed_point(src, "2"), "module m;\n wire a;\n\n wire b;\nendmodule\n");
}
#[test]
fn comments_are_never_dropped() {
let src = "\
module m;
// leading
wire a; // trailing
/* block */
wire b;
// dangling
endmodule
";
for spec in ["1", "2", "3", "4", "5", "6", "7", "2-4"] {
let out = fixed_point(src, spec);
for comment in ["// leading", "// trailing", "/* block */", "// dangling"] {
assert!(out.contains(comment), "{comment} lost at {spec}: {out}");
}
}
}
#[test]
fn multi_byte_content_is_sliced_on_character_boundaries() {
let src = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
let out = fixed_point(src, "3");
assert!(out.contains("// é ✓ 🎉 note"), "{out}");
assert!(out.contains(" wire a;\n wire b;\n"), "{out}");
}
#[test]
fn a_line_shift_can_sweep_in_the_next_construct() {
// The honest limit of "same ranges, same result": a range is line numbers,
// and laying out a construct can change how many lines it takes. Here the
// header collapses from three lines to one, so the second run's lines 1-3
// reach a body item the first run's did not. That is another correct,
// verified partial run — not a broken fixed point — and it is why the
// runtime check replays the *decisions*, which do not move.
let src = "module m #(\n parameter P = 1\n) (input a);\n wire x;\nendmodule\n";
let once = ranged(src, "1-3");
assert_eq!(once, "module m #(parameter P = 1) (input a);\n wire x;\nendmodule\n");
let twice = ranged(&once, "1-3");
assert_eq!(twice, "module m #(parameter P = 1) (input a);\n wire x;\nendmodule\n");
// And it settles there.
assert_eq!(ranged(&twice, "1-3"), twice);
}
#[test]
fn a_module_written_on_one_line_has_nowhere_to_be_cut_and_formats_whole() {
let src = "module m; wire a; endmodule\n";
assert_eq!(fixed_point(src, "1"), "module m;\n wire a;\nendmodule\n");
}
#[test]
fn an_empty_module_body_is_one_unit() {
let src = "module m;\nendmodule\n";
assert_eq!(fixed_point(src, "1"), "module m;\nendmodule\n");
assert_eq!(fixed_point(src, "9"), src);
}
// ------------------------------------------------------------------
// The spec grammar
// ------------------------------------------------------------------
#[test]
fn several_ranges_select_several_constructs() {
let out = fixed_point(TWO_MODULES, "3,13");
assert!(out.contains(" wire x;"), "{out}");
assert!(out.contains(" wire z;"), "{out}");
assert!(out.contains(" wire y;"), "and nothing between them: {out}");
}
#[test]
fn a_bad_spec_is_rejected_before_anything_is_formatted() {
for spec in ["", "0", "5-1", "1,,2", "x", "1-", "-3"] {
assert!(LineRanges::parse(spec).is_err(), "spec {spec:?} must be refused");
}
}
// ------------------------------------------------------------------
// Corpus spot check
// ------------------------------------------------------------------
/// Five real files, formatted at lines 1-5 only: the run must succeed (which
/// means the safety net passed on the whole output), be a fixed point under
/// the same ranges, and leave the bulk of the file byte-identical.
#[test]
fn a_corpus_spot_check_touches_only_the_top_of_the_file() {
let Some(files) = corpus_files(5) else { return };
for path in &files {
let src = fs::read_to_string(path).expect("read");
let lines = LineRanges::parse("1-5").expect("range spec");
let out = format_range(&src, &Config::default(), &lines)
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
// A second run is another verified partial run. It may reach further
// than the first if the first moved a line (see
// `a_line_shift_can_sweep_in_the_next_construct`), so what is asserted
// here is that it succeeds, not that it changes nothing.
format_range(&out, &Config::default(), &lines)
.unwrap_or_else(|e| panic!("{} second run: {e}", path.display()));
// Compared after the tail normalization every run applies (exactly
// one final newline), which is not a range decision.
let (src, out) = (src.trim_end(), out.trim_end());
let shared = common_suffix(src, out);
assert!(
shared * 2 > src.len(),
"{}: only {shared} of {} bytes came back untouched",
path.display(),
src.len()
);
}
}
/// How many trailing bytes two texts share.
fn common_suffix(a: &str, b: &str) -> usize {
a.bytes().rev().zip(b.bytes().rev()).take_while(|(x, y)| x == y).count()
}
/// The first `want` corpus files over 100 lines that format cleanly, or `None`
/// when the corpus is not checked out (`tools/corpus_fetch.sh`).
fn corpus_files(want: usize) -> Option<Vec<PathBuf>> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
return None;
}
let mut found = Vec::new();
let mut stack = vec![root];
while let (Some(dir), true) = (stack.pop(), found.len() < want) {
let mut entries: Vec<PathBuf> =
fs::read_dir(&dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path()).collect();
entries.sort();
for path in entries {
if path.is_dir() {
stack.push(path);
continue;
}
if path.extension().is_none_or(|e| e != "sv" && e != "v") {
continue;
}
let Ok(src) = fs::read_to_string(&path) else { continue };
if src.lines().count() > 100 && format_source(&src, &Config::default()).is_ok() {
found.push(path);
if found.len() == want {
break;
}
}
}
}
(found.len() == want).then_some(found)
}
@@ -0,0 +1,10 @@
//! 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
//! Handshakes section of `docs/features/lint-rules-2/README.md`.
fn main() {
print!("{}", vlog_linter::rules_markdown());
}
+3
View File
@@ -21,7 +21,9 @@
//! `docs/features/linter-core/README.md`.
mod context;
mod naming;
mod registry;
mod rule_docs;
mod rules;
mod violation;
mod visit;
@@ -31,6 +33,7 @@ use std::path::PathBuf;
pub use context::LintContext;
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, Rule};
pub use rule_docs::rules_markdown;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
pub use waiver::UNUSED_WAIVER;
+93
View File
@@ -0,0 +1,93 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. vfmt
//! 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
//! `docs/features/lint-rules-2/README.md`.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
//! whole point is to carry characters no convention allows.
/// True for an escaped identifier, which no naming rule judges.
pub(crate) fn is_escaped(name: &str) -> bool {
name.starts_with('\\')
}
/// `lower_snake_case`: starts with a lowercase letter, then lowercase
/// letters, digits and underscores.
pub(crate) fn is_lower_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_lowercase)
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// `UPPER_SNAKE_CASE`: starts with an uppercase letter, then uppercase
/// letters, digits and underscores. Verible calls this preset `ALL_CAPS`.
pub(crate) fn is_upper_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase)
&& name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}
/// `CamelCase` (a.k.a. PascalCase): starts with an uppercase letter, then
/// letters and digits only — an underscore anywhere disqualifies it.
pub(crate) fn is_camel_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase) && name.chars().all(|c| c.is_ascii_alphanumeric())
}
/// True when `name` is non-empty and its first character passes `first`.
fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
name.chars().next().is_some_and(|c| first(&c))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lower_snake_case_accepts_what_rtl_writes() {
for name in ["a", "clk", "data_i", "fifo2_wr_en", "a1_b2"] {
assert!(is_lower_snake_case(name), "{name}");
}
for name in ["", "Clk", "_clk", "clkA", "clk-en", "CLK", "1clk"] {
assert!(!is_lower_snake_case(name), "{name}");
}
}
#[test]
fn upper_snake_case_accepts_what_parameters_write() {
for name in ["A", "WIDTH", "ADDR_W", "FIFO2_DEPTH"] {
assert!(is_upper_snake_case(name), "{name}");
}
for name in ["", "Width", "_WIDTH", "WIDTHx", "1W"] {
assert!(!is_upper_snake_case(name), "{name}");
}
}
#[test]
fn camel_case_rejects_underscores_and_a_lowercase_start() {
for name in ["A", "Width", "AddrWidth", "Fifo2Depth"] {
assert!(is_camel_case(name), "{name}");
}
for name in ["", "width", "Addr_Width", "_Width", "2Wide"] {
assert!(!is_camel_case(name), "{name}");
}
}
#[test]
fn an_all_caps_name_is_not_camel_case_only_by_accident() {
// `WIDTH` passes both presets: it starts uppercase and has no
// underscore. Rules that accept either preset therefore accept it
// once, not twice — the union is what is documented.
assert!(is_camel_case("WIDTH") && is_upper_snake_case("WIDTH"));
assert!(is_upper_snake_case("ADDR_W") && !is_camel_case("ADDR_W"));
}
#[test]
fn an_escaped_identifier_is_recognized() {
assert!(is_escaped("\\my$name"));
assert!(!is_escaped("my_name"));
}
}
+45 -5
View File
@@ -2,7 +2,7 @@
use crate::context::LintContext;
use crate::rules;
use crate::violation::Violation;
use crate::violation::{Applicability, Violation};
/// One lint rule.
///
@@ -20,6 +20,20 @@ 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
/// where Verible defaults its equivalent on; see
/// `docs/features/lint-rules-2/README.md` for the citation per rule.
fn default_on(&self) -> bool {
true
}
/// The applicability of the fix this rule can offer, or `None` when it
/// never offers one. Declarative metadata for the rule reference — the
/// authority is still the [`Fix`](crate::Fix) on each violation.
fn fix(&self) -> Option<Applicability> {
None
}
/// Everything this rule finds in one file.
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
}
@@ -30,19 +44,23 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::case_missing_default::CaseMissingDefault,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::parameter_name_style::ParameterNameStyle,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::unused_waiver::UnusedWaiver,
&rules::wire_reg_mixup::WireRegMixup,
]
}
/// The rules a plain `vfmt check` runs. Today that is all of them; the split
/// exists so a rule can be added in an off-by-default state without changing
/// any caller.
/// The rules a plain `vfmt check` runs: every rule whose
/// [`default_on`](Rule::default_on) says so.
pub fn default_rules() -> Vec<&'static dyn Rule> {
all_rules()
all_rules().into_iter().filter(|rule| rule.default_on()).collect()
}
/// The rule with this name, if there is one.
@@ -118,6 +136,28 @@ mod tests {
assert_eq!(names, sorted);
}
#[test]
fn the_default_set_is_a_subset_of_every_rule() {
let all: Vec<&str> = all_rules().iter().map(|r| r.name()).collect();
let default: Vec<&str> = default_rules().iter().map(|r| r.name()).collect();
assert!(default.iter().all(|name| all.contains(name)));
assert!(default.len() < all.len(), "some rule must ship off by default");
for rule in all_rules() {
assert_eq!(rule.default_on(), default.contains(&rule.name()), "{}", rule.name());
}
}
#[test]
fn an_off_by_default_rule_is_still_selectable() {
let off = all_rules()
.into_iter()
.find(|rule| !rule.default_on())
.map(|rule| rule.name().to_string())
.unwrap();
let chosen = select_rules(std::slice::from_ref(&off), &[]).unwrap();
assert_eq!(chosen.iter().map(|r| r.name()).collect::<Vec<_>>(), vec![off.as_str()]);
}
#[test]
fn selection_defaults_to_the_default_set() {
let chosen = select_rules(&[], &[]).unwrap();
+166
View File
@@ -0,0 +1,166 @@
//! The rule reference, generated from the registry.
//!
//! Verible ships `--generate_markdown` so its rule documentation cannot drift
//! from its rules; ruff does the same for its 900+ rules. This is that: one
//! markdown document rendered from [`all_rules`], with nothing hand-written
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
//! this.
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(
"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 \
need `--select <name>`. Any rule can be turned off with `--ignore \
<name>` or waived in the source with `// vfmt: waive <name>`.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
for rule in all_rules() {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
name = rule.name(),
default = on_off(rule.default_on()),
fix = fix_word(rule),
));
}
out.push('\n');
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Default: {}\n- Fix: {}\n\n",
on_off(rule.default_on()),
fix_word(rule)
));
out.push_str(rule.doc());
out.push_str("\n\n");
}
out
}
/// How the table spells an on/off default.
fn on_off(on: bool) -> &'static str {
if on {
"**on**"
} else {
"off"
}
}
/// How the table spells a rule's fix applicability.
fn fix_word(rule: &dyn crate::Rule) -> &'static str {
match rule.fix() {
Some(applicability) => applicability.as_str(),
None => "none",
}
}
/// The summary with an initial capital, so it reads as a sentence under the
/// heading. Rule summaries are written lower-case for the diagnostic line.
fn capitalize(text: &str) -> String {
let mut chars = text.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Applicability;
#[test]
fn every_registered_rule_appears_with_its_summary_and_doc() {
let markdown = rules_markdown();
for rule in all_rules() {
assert!(markdown.contains(&format!("## {}\n", rule.name())), "{}", rule.name());
assert!(markdown.contains(rule.doc()), "{}: doc missing", rule.name());
assert!(
markdown.contains(&capitalize(rule.summary())),
"{}: summary missing",
rule.name()
);
}
}
#[test]
fn the_index_lists_every_rule_once() {
let markdown = rules_markdown();
for rule in all_rules() {
let row = format!("| [`{0}`](#{0}) |", rule.name());
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
}
}
#[test]
fn defaults_and_fixes_are_rendered_from_the_registry() {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
#[test]
fn the_document_shape_is_pinned() {
// A golden test on the *shape*, not on the prose: the heading, the
// generated-by note, the index table header, and the first per-rule
// section, which together are what a reader (and any renderer) sees.
let markdown = rules_markdown();
let head: Vec<&str> = markdown.lines().take(8).collect();
assert_eq!(
head,
vec![
"# vfmt 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 \
`--select <name>`. Any rule can be turned off with `--ignore <name>` or waived \
in the source with `// vfmt: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
]
);
let first_rule = all_rules()[0];
let section = format!(
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
first_rule.name(),
capitalize(first_rule.summary()),
on_off(first_rule.default_on()),
fix_word(first_rule),
first_rule.doc(),
);
assert!(markdown.contains(&section), "per-rule section shape changed:\n{section}");
assert!(markdown.ends_with("\n\n"));
}
#[test]
fn declared_fix_metadata_matches_what_the_rules_return() {
// The metadata is declarative, so it can drift. This probe lints a
// file that trips every fixable rule and checks the two agree.
let src = "module m;\n\twire a;\t\n wire b; \nendmodule\n";
let ctx = crate::LintContext::new(src, Some(std::path::PathBuf::from("rtl/x.sv")));
for rule in all_rules() {
for violation in rule.check(&ctx) {
let returned = violation.fix.as_ref().map(|f| f.applicability);
assert_eq!(
returned,
rule.fix(),
"{} declares {:?} but returned {returned:?}",
rule.name(),
rule.fix(),
);
}
}
}
}
@@ -0,0 +1,107 @@
//! `enum-name-style` — enum typedef names are `lower_snake_case` ending `_e`
//! or `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
/// See [`Rule::doc`].
pub struct EnumNameStyle;
const NAME: &str = "enum-name-style";
impl Rule for EnumNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name enum typedefs in lower_snake_case ending in _e or _t"
}
fn doc(&self) -> &'static str {
"A type name that looks like a type name is what makes a declaration \
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 \
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 \
fix: a type rename reaches every use."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Typedef(typedef) = &item.kind else { return };
if !matches!(typedef.kind, TypedefKind::Enum(_)) || is_escaped(&typedef.name) {
return;
}
let name = &typedef.name;
let suffixed = name.ends_with("_e") || name.ends_with("_t");
if is_lower_snake_case(name) && suffixed {
return;
}
out.push(Violation::new(
NAME,
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
typedef.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
EnumNameStyle.check(&LintContext::new(src, None))
}
fn typedef(name: &str) -> String {
format!("package p;\n typedef enum logic {{ A, B }} {name};\nendpackage\n")
}
#[test]
fn flags_a_missing_suffix_and_a_wrong_case() {
assert_eq!(violations(&typedef("state")).len(), 1);
assert_eq!(violations(&typedef("StateE")).len(), 1);
assert_eq!(violations(&typedef("STATE_E")).len(), 1);
let found = violations(&typedef("state"));
assert!(found[0].message.contains("state"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "a type rename reaches every use");
}
#[test]
fn both_accepted_suffixes_are_clean() {
assert!(violations(&typedef("state_e")).is_empty());
assert!(violations(&typedef("state_t")).is_empty());
assert!(violations(&typedef("fifo2_state_e")).is_empty());
}
#[test]
fn a_non_enum_typedef_is_none_of_its_business() {
let src = "package p;\n typedef logic [7:0] byteish;\nendpackage\n";
assert!(violations(src).is_empty());
let src = "package p;\n typedef struct packed { logic a; } thing;\nendpackage\n";
assert!(violations(src).is_empty());
}
#[test]
fn an_enum_typedef_inside_a_class_body_is_covered() {
let src = "class c;\n typedef enum logic { A, B } state;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn it_points_at_the_name() {
let src = typedef("state");
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
}
}
@@ -3,7 +3,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
/// See [`Rule::doc`].
@@ -34,24 +34,23 @@ impl Rule for ExplicitParameterStorageType {
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| match &item.kind {
ItemKind::ParamDecl(decl) => untyped_decl(decl, &mut out),
ItemKind::Module(module) => {
for port in module.param_ports.iter().flatten() {
// Only an entry that writes the keyword opens a
// declaration; the rest continue the previous one's type.
let Some(kw) = &port.kw else { continue };
if port.is_type || !port.ty.name.is_empty() {
continue;
}
out.push(Violation::new(
NAME,
format!("`{kw}` has no storage type: `{}`", port.name),
port.name_span,
));
}
walk_items(ctx.file(), &mut |item| {
if let ItemKind::ParamDecl(decl) = &item.kind {
untyped_decl(decl, &mut out);
}
_ => {}
});
walk_param_ports(ctx.file(), &mut |port| {
// Only an entry that writes the keyword opens a declaration; the
// rest continue the previous one's type.
let Some(kw) = &port.kw else { return };
if port.is_type || !port.ty.name.is_empty() {
return;
}
out.push(Violation::new(
NAME,
format!("`{kw}` has no storage type: `{}`", port.name),
port.name_span,
));
});
walk_all_stmts(ctx.file(), &mut |stmt| {
if let StmtKind::ParamDecl(decl) = &stmt.kind {
@@ -116,6 +115,12 @@ mod tests {
assert!(found[1].message.contains("localparam"), "{}", found[1].message);
}
#[test]
fn a_class_body_and_a_class_header_are_covered() {
let found = violations("class c #(parameter A = 1);\n localparam B = 2;\nendclass\n");
assert_eq!(found.len(), 2, "{found:?}");
}
#[test]
fn packed_dimensions_alone_are_not_a_storage_type() {
assert_eq!(violations("module m;\n parameter [7:0] A = 1;\nendmodule\n").len(), 1);
+5
View File
@@ -6,8 +6,13 @@
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod case_missing_default;
pub mod enum_name_style;
pub mod explicit_parameter_storage_type;
pub mod module_filename;
pub mod module_name_style;
pub mod no_tabs;
pub mod no_trailing_whitespace;
pub mod parameter_name_style;
pub mod struct_union_name_style;
pub mod unused_waiver;
pub mod wire_reg_mixup;
@@ -0,0 +1,97 @@
//! `module-name-style` — module names are `lower_snake_case`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ModuleNameStyle;
const NAME: &str = "module-name-style";
impl Rule for ModuleNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name modules in lower_snake_case"
}
fn doc(&self) -> &'static str {
"A module name ends up as a file name, a directory name, an instance \
path in a waveform viewer and a grep target, and every one of those is \
case-sensitive somewhere and case-insensitive somewhere else. The \
lowRISC/Google SystemVerilog style guide asks for `lower_snake_case`; \
`module-filename` already ties the name to the file, and this rule ties \
it to the convention. Off by default: unlike the other naming rules \
here, Verible ships no `module-name-style` rule to inherit a default \
from, so enabling it is the user's call — `--select \
module-name-style`. Escaped identifiers (`\\my$mod`) are exempt, and \
there is no fix: renaming a module is a cross-file edit."
}
fn default_on(&self) -> bool {
false
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if is_escaped(&module.name) || is_lower_snake_case(&module.name) {
return;
}
out.push(Violation::new(
NAME,
format!("module `{}` is not lower_snake_case", module.name),
module.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModuleNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_name_that_is_not_lower_snake_case() {
let found = violations("module FooBar;\nendmodule\n");
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("FooBar"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "renaming a module is a cross-file edit");
}
#[test]
fn lower_snake_case_names_are_clean() {
assert!(violations("module foo_bar;\nendmodule\n").is_empty());
assert!(violations("module fifo2_ctrl;\nendmodule\n").is_empty());
}
#[test]
fn it_points_at_the_name() {
let src = "module FooBar;\nendmodule\n";
assert_eq!(&src[violations(src)[0].span.as_range()], "FooBar");
}
#[test]
fn a_nested_module_is_covered() {
let src =
"package p;\nendpackage\nmodule Outer;\n module Inner;\n endmodule\nendmodule\n";
assert_eq!(violations(src).len(), 2);
}
#[test]
fn it_is_off_by_default() {
assert!(!ModuleNameStyle.default_on());
}
}
+5 -1
View File
@@ -2,7 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::violation::{Fix, Violation};
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
@@ -28,6 +28,10 @@ impl Rule for NoTabs {
alone, because there the whitespace is data."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for line in 1..=ctx.line_index().line_count() {
@@ -2,7 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::violation::{Fix, Violation};
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
@@ -28,6 +28,10 @@ impl Rule for NoTrailingWhitespace {
whitespace is data."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for line in 1..=ctx.line_index().line_count() {
@@ -0,0 +1,139 @@
//! `parameter-name-style` — parameter names are `CamelCase` or `ALL_CAPS`.
use crate::context::LintContext;
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
use crate::registry::Rule;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ParameterNameStyle;
const NAME: &str = "parameter-name-style";
impl Rule for ParameterNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name parameters in CamelCase or ALL_CAPS"
}
fn doc(&self) -> &'static str {
"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 \
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 \
style configuration exists, the union is the honest default. The rule \
covers item- and statement-level declarations and the `#( ... )` \
parameter ports of module and class headers. Escaped identifiers are \
exempt, and there is no fix: a rename reaches every override site."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if let ItemKind::ParamDecl(decl) = &item.kind {
check_decl(decl, &mut out);
}
});
walk_all_stmts(ctx.file(), &mut |stmt| {
if let StmtKind::ParamDecl(decl) = &stmt.kind {
check_decl(decl, &mut out);
}
});
walk_param_ports(ctx.file(), &mut |port| {
// An entry with no keyword continues the previous declaration, but
// it still declares a name of its own, so it is checked like any
// other. A `type` parameter is a type name, not a constant, and is
// left to Verible's separate `parameter-type-name-style` idea.
if port.is_type {
return;
}
let kw = port.kw.as_deref().unwrap_or("parameter");
report(&port.name, port.name_span, kw, &mut out);
});
out
}
}
/// Reports every declarator of one `parameter`/`localparam` declaration.
fn check_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
for declarator in &decl.declarators {
report(&declarator.name, declarator.name_span, &decl.kw, out);
}
}
/// Reports `name` unless it matches one of the two accepted presets.
fn report(name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
if is_escaped(name) || is_camel_case(name) || is_upper_snake_case(name) {
return;
}
out.push(Violation::new(
NAME,
format!("`{kw}` `{name}` is neither CamelCase nor ALL_CAPS"),
span,
));
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ParameterNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_lower_snake_case_parameter() {
let found = violations("module m;\n parameter int addr_width = 8;\nendmodule\n");
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("addr_width"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "a rename reaches every override site");
}
#[test]
fn both_presets_are_accepted() {
let src = "module m;\n parameter int AddrWidth = 8;\n localparam int ADDR_W = 4;\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn parameter_ports_of_a_module_header_are_covered() {
let found = violations("module m #(parameter int width = 8) ();\nendmodule\n");
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("width"), "{}", found[0].message);
}
#[test]
fn parameter_ports_of_a_class_header_are_covered_but_type_params_are_not() {
let found = violations("class c #(parameter int width = 1, type T = int);\nendclass\n");
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("width"), "{}", found[0].message);
}
#[test]
fn a_localparam_inside_a_class_body_is_covered() {
let found = violations("class c;\n localparam int max_depth = 4;\nendclass\n");
assert_eq!(found.len(), 1, "{found:?}");
}
#[test]
fn every_name_of_a_multi_declarator_line_is_pointed_at() {
let found = violations("module m;\n parameter int a = 1, b = 2;\nendmodule\n");
assert_eq!(found.len(), 2);
assert_ne!(found[0].span.start, found[1].span.start);
}
#[test]
fn it_is_on_by_default() {
assert!(ParameterNameStyle.default_on());
}
}
@@ -0,0 +1,104 @@
//! `struct-union-name-style` — struct/union typedef names are
//! `lower_snake_case` ending `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
/// See [`Rule::doc`].
pub struct StructUnionNameStyle;
const NAME: &str = "struct-union-name-style";
impl Rule for StructUnionNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name struct and union typedefs in lower_snake_case ending in _t"
}
fn doc(&self) -> &'static str {
"The `_t` suffix is the one piece of Verilog naming convention that is \
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 \
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 \
there is no fix: a type rename reaches every use."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Typedef(typedef) = &item.kind else { return };
let TypedefKind::Struct(structure) = &typedef.kind else { return };
let name = &typedef.name;
if is_escaped(name) || (is_lower_snake_case(name) && name.ends_with("_t")) {
return;
}
out.push(Violation::new(
NAME,
format!("{} `{name}` is not lower_snake_case ending in `_t`", structure.kw),
typedef.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
StructUnionNameStyle.check(&LintContext::new(src, None))
}
fn typedef(kw: &str, name: &str) -> String {
format!("package p;\n typedef {kw} packed {{ logic a; }} {name};\nendpackage\n")
}
#[test]
fn flags_a_missing_suffix_and_a_wrong_case() {
let found = violations(&typedef("struct", "addr"));
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("struct"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "a type rename reaches every use");
assert_eq!(violations(&typedef("struct", "AddrT")).len(), 1);
assert_eq!(violations(&typedef("struct", "addr_e")).len(), 1, "_e is for enums");
}
#[test]
fn a_union_is_named_in_the_message() {
let found = violations(&typedef("union", "addr"));
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("union"), "{}", found[0].message);
}
#[test]
fn a_conventional_name_is_clean() {
assert!(violations(&typedef("struct", "addr_t")).is_empty());
assert!(violations(&typedef("union", "word2_t")).is_empty());
}
#[test]
fn a_non_struct_typedef_is_none_of_its_business() {
let src = "package p;\n typedef enum logic { A } state;\nendpackage\n";
assert!(violations(src).is_empty());
let src = "package p;\n typedef logic [7:0] byteish;\nendpackage\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_struct_typedef_inside_a_class_body_is_covered() {
let src = "class c;\n typedef struct packed { logic a; } addr;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -0,0 +1,123 @@
//! `wire-reg-mixup` — no `reg` in a SystemVerilog file.
use std::path::Path;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct WireRegMixup;
const NAME: &str = "wire-reg-mixup";
impl Rule for WireRegMixup {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"use `logic` instead of `reg` in SystemVerilog files"
}
fn doc(&self) -> &'static str {
"`reg` is Verilog-1995's name for a variable, and its worst property is \
that it reads like hardware: generations of engineers have written \
`reg` meaning a flop and `wire` meaning combinational, which the \
language never promised. SystemVerilog's `logic` is the same type \
under a name that claims nothing, so a file that has already chosen \
SystemVerilog has no reason left to write `reg`. This rule fires only \
in a file whose extension is `.sv` or `.svh` — a `.v` file is Verilog \
and `reg` is simply its spelling, and a stdin buffer with no \
`--stdin-filename` has no extension to judge, so the rule is silent \
there. `wire` itself is **not** flagged: a net is a distinct kind of \
object in SystemVerilog too, and `wire x = expr;` is a perfectly good \
continuous assignment. No fix is offered: `reg` → `logic` preserves \
meaning, but a `reg` in a `.sv` file is usually a symptom of code \
carried over wholesale, and the repair worth making is bigger than \
the keyword."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let Some(path) = ctx.path() else { return Vec::new() };
if !is_systemverilog(path) {
return Vec::new();
}
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::Keyword && token.text == "reg")
.map(|token| {
Violation::new(NAME, "`reg` in a SystemVerilog file; use `logic`", token.span)
})
.collect()
}
}
/// True for the two SystemVerilog file extensions, compared case-insensitively.
fn is_systemverilog(path: &Path) -> bool {
let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false };
let ext = ext.to_ascii_lowercase();
ext == "sv" || ext == "svh"
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn violations(src: &str, path: Option<&str>) -> Vec<Violation> {
WireRegMixup.check(&LintContext::new(src, path.map(PathBuf::from)))
}
#[test]
fn flags_reg_in_a_sv_file() {
let found = violations("module m;\n reg q;\nendmodule\n", Some("rtl/m.sv"));
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("logic"), "{}", found[0].message);
assert!(found[0].fix.is_none());
assert!(violations("module m;\n reg q;\nendmodule\n", Some("rtl/m.svh")).len() == 1);
assert!(violations("module m;\n reg q;\nendmodule\n", Some("rtl/m.SV")).len() == 1);
}
#[test]
fn a_verilog_file_and_a_nameless_buffer_are_silent() {
let src = "module m;\n reg q;\nendmodule\n";
assert!(violations(src, Some("rtl/m.v")).is_empty());
assert!(violations(src, Some("rtl/m.vh")).is_empty());
assert!(violations(src, None).is_empty());
}
#[test]
fn logic_and_wire_are_left_alone() {
let src = "module m;\n logic q;\n wire w;\n wire z = w & q;\nendmodule\n";
assert!(violations(src, Some("rtl/m.sv")).is_empty());
}
#[test]
fn every_spelling_of_a_reg_declaration_is_caught() {
let src = "module m (output reg [7:0] o);\n reg a, b;\n output reg c;\nendmodule\n";
assert_eq!(violations(src, Some("rtl/m.sv")).len(), 3);
}
#[test]
fn reg_in_a_string_or_an_identifier_is_not_the_keyword() {
let src = "module m;\n string s = \"reg\";\n logic reg_q;\n logic regfile;\nendmodule\n";
assert!(violations(src, Some("rtl/m.sv")).is_empty());
}
#[test]
fn it_points_at_the_keyword() {
let src = "module m;\n reg q;\nendmodule\n";
let found = violations(src, Some("m.sv"));
assert_eq!(&src[found[0].span.as_range()], "reg");
}
#[test]
fn a_file_that_does_not_parse_is_still_checked() {
// The rule reads tokens, not the tree, so error recovery cannot hide
// a `reg` from it.
let src = "module m;\n @@@ not verilog\n reg q;\nendmodule\n";
assert_eq!(violations(src, Some("m.sv")).len(), 1);
}
}
+75 -1
View File
@@ -4,7 +4,7 @@
//! decides what it cares about. `Error` leaves from a tolerant parse hold raw
//! text and no children, so they are visited and matched by nothing.
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, SourceFile, Stmt, StmtKind};
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind};
/// Calls `f` on every item in the file, nested items included.
pub(crate) fn walk_items(file: &SourceFile, f: &mut dyn FnMut(&Item)) {
@@ -16,6 +16,9 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
f(item);
match &item.kind {
ItemKind::Module(m) => items(&m.items, f),
// A class body holds ordinary items — properties, localparams,
// methods — so every AST rule sees them like any other scope.
ItemKind::Class(class) => items(&class.items, f),
ItemKind::Package { items: inner, .. } => items(inner, f),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
ItemKind::GenIf(gen_if) => {
@@ -106,6 +109,21 @@ fn stmts(list: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
}
}
/// Calls `f` on every `#( ... )` parameter port of the file — a module header's
/// and a class header's alike, since both spell them with the same node.
pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort)) {
walk_items(file, &mut |item| {
let ports = match &item.kind {
ItemKind::Module(module) => &module.param_ports,
ItemKind::Class(class) => &class.param_ports,
_ => return,
};
for port in ports.iter().flatten() {
f(port);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
@@ -150,6 +168,62 @@ mod tests {
assert_eq!(count_assignments(src), 2);
}
#[test]
fn reaches_items_and_statements_inside_a_class_body() {
let src = "class c;\n\
localparam int A = 1;\n\
function void f(int x);\n\
case (x)\n\
1: a = 1;\n\
endcase\n\
endfunction\n\
endclass\n";
let (file, diagnostics) = parse_source_tolerant(src);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let mut params = 0;
let mut cases = 0;
walk_items(&file, &mut |item| {
if matches!(item.kind, ItemKind::ParamDecl(_)) {
params += 1;
}
});
walk_all_stmts(&file, &mut |stmt| {
if matches!(stmt.kind, StmtKind::Case { .. }) {
cases += 1;
}
});
assert_eq!((params, cases), (1, 1));
}
#[test]
fn reaches_a_class_nested_in_a_package_and_a_class() {
let src = "package p;\n\
class outer;\n\
class inner;\n\
localparam int A = 1;\n\
endclass\n\
endclass\n\
endpackage\n";
let (file, _) = parse_source_tolerant(src);
let mut params = 0;
walk_items(&file, &mut |item| {
if matches!(item.kind, ItemKind::ParamDecl(_)) {
params += 1;
}
});
assert_eq!(params, 1);
}
#[test]
fn parameter_ports_of_both_module_and_class_headers_are_reached() {
let src = "module m #(parameter int A = 1) ();\nendmodule\n\
class c #(type T = int);\nendclass\n";
let (file, _) = parse_source_tolerant(src);
let mut names = Vec::new();
walk_param_ports(&file, &mut |port| names.push(port.name.clone()));
assert_eq!(names, vec!["A".to_string(), "T".to_string()]);
}
#[test]
fn an_unparsable_region_is_visited_but_holds_nothing() {
let (file, diagnostics) = parse_source_tolerant("module m;\n @@@;\nendmodule\n");
+240 -2
View File
@@ -11,12 +11,24 @@
use std::path::PathBuf;
use vlog_linter::{default_rules, run};
use vlog_linter::{default_rules, run, select_rules};
/// Asserts that linting `src` (as `path`) finds exactly what its markers say.
#[track_caller]
fn assert_lint(path: Option<&str>, src: &str) {
let violations = run(src, path.map(PathBuf::from), &default_rules());
assert_lint_with(&default_rules(), path, src)
}
/// The same, for a rule that a plain `vfmt check` does not run.
#[track_caller]
fn assert_lint_selecting(rule: &str, path: Option<&str>, src: &str) {
let rules = select_rules(&[rule.to_string(), "unused-waiver".to_string()], &[]).unwrap();
assert_lint_with(&rules, path, src)
}
#[track_caller]
fn assert_lint_with(rules: &[&'static dyn vlog_linter::Rule], path: Option<&str>, src: &str) {
let violations = run(src, path.map(PathBuf::from), rules);
let index = vlog_parser::LineIndex::new(src);
let mut actual: Vec<(u32, String)> =
@@ -55,6 +67,17 @@ fn the_harness_notices_a_missing_marker() {
assert!(expectations(src).is_empty(), "and the unmarked source must expect none");
}
#[test]
fn a_rule_off_by_default_says_nothing_until_selected() {
let src = "module FooBar;\nendmodule\n";
assert!(run(src, None, &default_rules()).is_empty());
assert_lint_selecting(
"module-name-style",
None,
"module FooBar;\n//~ module-name-style\nendmodule\n",
);
}
// ---------------------------------------------------------------- no-tabs
#[test]
@@ -271,3 +294,218 @@ fn several_rules_on_one_file_report_independently() {
endmodule\n",
);
}
// ------------------------------------------------------ module-name-style
#[test]
fn module_name_style_fires() {
assert_lint_selecting(
"module-name-style",
None,
"module FooBar;\n//~ module-name-style\nendmodule\n",
);
}
#[test]
fn module_name_style_is_quiet_on_lower_snake_case() {
assert_lint_selecting("module-name-style", None, "module foo_bar;\nendmodule\n");
}
#[test]
fn module_name_style_is_waived() {
assert_lint_selecting(
"module-name-style",
None,
"module FooBar; // vfmt: waive module-name-style\nendmodule\n",
);
}
#[test]
fn module_name_style_waiver_that_waives_nothing_is_reported() {
assert_lint_selecting(
"module-name-style",
None,
"module foo_bar; // vfmt: waive module-name-style\n//~ unused-waiver\nendmodule\n",
);
}
// --------------------------------------------------- parameter-name-style
#[test]
fn parameter_name_style_fires() {
assert_lint(
None,
"module m;\n parameter int addr_width = 8;\n//~ parameter-name-style\nendmodule\n",
);
}
#[test]
fn parameter_name_style_accepts_both_presets() {
assert_lint(
None,
"module m #(parameter int AddrWidth = 8) ();\n localparam int ADDR_W = 4;\nendmodule\n",
);
}
#[test]
fn parameter_name_style_is_waived() {
assert_lint(
None,
"module m;\n parameter int addr_width = 8; // vfmt: waive parameter-name-style\nendmodule\n",
);
}
#[test]
fn parameter_name_style_waiver_that_waives_nothing_is_reported() {
assert_lint(
None,
"module m;\n parameter int AddrWidth = 8; // vfmt: waive parameter-name-style\n//~ unused-waiver\nendmodule\n",
);
}
// -------------------------------------------------------- enum-name-style
#[test]
fn enum_name_style_fires() {
assert_lint(
None,
"package p;\n typedef enum logic { A, B } state;\n//~ enum-name-style\nendpackage\n",
);
}
#[test]
fn enum_name_style_is_quiet_on_a_suffixed_name() {
assert_lint(None, "package p;\n typedef enum logic { A, B } state_e;\nendpackage\n");
}
#[test]
fn enum_name_style_is_waived() {
assert_lint(
None,
"package p;\n// verilog_lint: waive enum-name-style\n typedef enum logic { A } state;\nendpackage\n",
);
}
#[test]
fn enum_name_style_waiver_that_waives_nothing_is_reported() {
assert_lint(
None,
"package p;\n typedef enum logic { A } state_e; // vfmt: waive enum-name-style\n//~ unused-waiver\nendpackage\n",
);
}
// ------------------------------------------------ struct-union-name-style
#[test]
fn struct_union_name_style_fires() {
assert_lint(
None,
"package p;\n typedef struct packed { logic a; } addr;\n//~ struct-union-name-style\nendpackage\n",
);
}
#[test]
fn struct_union_name_style_is_quiet_on_a_suffixed_name() {
assert_lint(None, "package p;\n typedef union packed { logic a; } addr_t;\nendpackage\n");
}
#[test]
fn struct_union_name_style_is_waived() {
assert_lint(
None,
"package p;\n typedef struct packed { logic a; } addr; // vfmt: waive struct-union-name-style\nendpackage\n",
);
}
#[test]
fn struct_union_name_style_waiver_that_waives_nothing_is_reported() {
assert_lint(
None,
"package p;\n typedef struct packed { logic a; } addr_t; // vfmt: waive struct-union-name-style\n//~ unused-waiver\nendpackage\n",
);
}
// --------------------------------------------------------- wire-reg-mixup
#[test]
fn wire_reg_mixup_fires() {
assert_lint(Some("rtl/m.sv"), "module m;\n reg q;\n//~ wire-reg-mixup\nendmodule\n");
}
#[test]
fn wire_reg_mixup_is_quiet_on_logic_and_on_verilog_files() {
assert_lint(Some("rtl/m.sv"), "module m;\n logic q;\n wire w;\nendmodule\n");
assert_lint(Some("rtl/m.v"), "module m;\n reg q;\nendmodule\n");
assert_lint(None, "module m;\n reg q;\nendmodule\n");
}
#[test]
fn wire_reg_mixup_is_waived() {
assert_lint(Some("rtl/m.sv"), "module m;\n reg q; // vfmt: waive wire-reg-mixup\nendmodule\n");
}
#[test]
fn wire_reg_mixup_waiver_that_waives_nothing_is_reported() {
assert_lint(
Some("rtl/m.sv"),
"module m;\n logic q; // vfmt: waive wire-reg-mixup\n//~ unused-waiver\nendmodule\n",
);
}
// ------------------------------------------------------ class-body reach
#[test]
fn case_missing_default_reaches_a_class_method() {
assert_lint(
None,
"class c;\n\
function void f(int x);\n\
case (x)\n\
//~ case-missing-default\n\
1: a = 1;\n\
endcase\n\
endfunction\n\
endclass\n",
);
}
#[test]
fn explicit_parameter_storage_type_reaches_a_class_body_and_header() {
assert_lint(
None,
"class c #(parameter A = 1);\n\
//~ explicit-parameter-storage-type\n\
localparam B = 2;\n\
//~ explicit-parameter-storage-type\n\
endclass\n",
);
}
#[test]
fn a_class_inside_a_module_is_reached_too() {
assert_lint(
Some("rtl/m.sv"),
"module m;\n\
class c;\n\
localparam B = 2;\n\
//~ explicit-parameter-storage-type\n\
endclass\n\
endmodule\n",
);
}
#[test]
fn the_always_rules_reach_a_class_body_too() {
// SystemVerilog forbids an `always` block inside a class, so this shape is
// not real-world code — but the tolerant parser accepts it and the walk is
// uniform, which is the property being pinned: no rule stops at `endclass`.
assert_lint(
None,
"class c;\n\
always_comb x <= y;\n\
//~ always-comb-blocking\n\
always_ff @(posedge clk) q = d;\n\
//~ always-ff-non-blocking\n\
endclass\n",
);
}
+6 -1
View File
@@ -201,7 +201,12 @@ verbatim. The fix is one arm —
`ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out)` — but
`fence.rs` was explicitly outside this round's scope, so it is filed here
rather than done. Nothing is corrupted by the gap; the fence is simply
inactive.
inactive. *(Lead note, per lint-rules-2 QA: inactive for the FORMATTER
only. `fence::protected_regions`' line-based scan backstop still sees the
fence, so `vfmt check --fix` and the server's quick fixes DO decline to
edit inside it — the asymmetry errs toward hands-off, which is the
harmless direction, but readers should not conclude the fence does
nothing in a class body.)*
**Requested of `vlog_linter` (same shape, lower stakes):** `visit.rs`'s
`items()` walk has a `_ => {}` arm too, so the four **AST-walking** rules
+657
View File
@@ -0,0 +1,657 @@
# lint-rules-2
## Goal
Finish the practical rule set `linter-core` started, inside `vlog_linter`
only. Three things ship: (1) `visit.rs` now walks **class bodies**, which
closes the handshake `docs/features/classes/README.md` filed — the four
AST-walking rules stopped at `endclass` and now do not; (2) five new rules —
four **naming** rules with built-in style presets and no regex dependency,
plus `wire-reg-mixup`, the SystemVerilog-ness decision the linter-core round
parked; (3) `vlog_linter::rules_markdown()`, a rule reference generated from
the registry so the docs cannot drift from the rules (Verible's
`--generate_markdown`, ruff's generated rule pages). Everything slots into the
existing registry, so `vfmt check`, `--select`/`--ignore` and `vfmt-server`'s
diagnostics pick the new rules up with **zero wiring** — verified live, not
assumed.
## Assumptions
- **A class body is an ordinary scope.** `ItemKind::Class`'s `items` are
walked exactly like a module's, so every AST rule sees class properties,
class localparams, class typedefs and class methods. Nothing about a rule
is class-aware; the walk is what changed.
- **Naming presets are fixed per rule this round.** Verible spells its
conventions as RE2 patterns and lets you override them; vfmt spells the same
conventions as character-class predicates (`src/naming.rs`) and does not
let you override them yet. Per-rule style configuration needs the `lint`
key in `vfmt.toml`, which is still parked (see Handshakes).
- **Escaped identifiers (`\my$name`) are exempt from every naming rule.**
Their whole purpose is to carry characters no convention allows.
- **A name's style is judged on ASCII.** A non-ASCII identifier fails
`lower_snake_case` etc. and is reported. Verilog identifiers are ASCII by
the standard (outside escaped ones, which are exempt), so this has no
practical population.
- **`wire-reg-mixup` decides SystemVerilog-ness from the file extension
alone** — `.sv`/`.svh`, compared case-insensitively. Not from content, not
from a config key, and never for a buffer with no name: `vfmt check -`
without `--stdin-filename` is silent. This is the whole SV-ness decision,
deliberately: any content heuristic ("it uses `logic`, so it's SV") would
make the rule's own subject its input.
- **`wire-reg-mixup` reads tokens, not the tree**, so a file that does not
parse is still checked, and a `reg` inside a `constraint`/`covergroup`
verbatim block is still seen. A `reg` inside a `` `define`` body is *not*:
a directive is one `TokenKind::Directive` token and its body is never
lexed as keywords. Consistent with vfmt's no-preprocessing stance.
- **`rules_markdown()`'s "Fix" column is declarative metadata**
(`Rule::fix()`), not derived from running the rules. A unit test probes the
rules against a file that trips every fixable one and asserts the two
agree, which catches the drift direction that matters (a rule gains a fix
and forgets to declare it) for any rule that fires on that probe.
## Handshakes
**Consumed** (all unchanged from `linter-core`)
- `vlog_parser`: `ast::{ItemKind::Class, ClassDecl, ParamPort, Typedef,
TypedefKind, StructType}`, `token::{Token, TokenKind}`, `span::TextRange`.
New this round is only that the class arm of `ItemKind` is now read.
`StructType::kw` is read for the `struct`/`union` word in a message.
- Nothing else. `cargo tree -p vlog_linter` is still `vlog_parser` + std —
**no new dependency**, which is also the naming rules' central design
decision (below).
**Promised**
- Three new public items: `rules_markdown()`, and two new methods on the
`Rule` trait, `default_on()` (defaults to `true`) and `fix()` (defaults to
`None`). Both have defaults, so an out-of-crate implementor of `Rule` — if
there ever is one — is not broken by them.
- `default_rules()` is no longer `all_rules()`: it filters on `default_on()`.
Callers are unaffected (`crates/vfmt` calls `select_rules`,
`crates/vfmt_server/src/lint.rs` calls `default_rules()`); both keep
compiling and keep meaning what they meant.
- Rule *names* are stable API — they appear in users' waivers. The five new
names are `enum-name-style`, `module-name-style`, `parameter-name-style`,
`struct-union-name-style`, `wire-reg-mixup`. Four of the five are spelled
exactly as Verible spells its equivalent, on purpose: a codebase already
annotated `// verilog_lint: waive enum-name-style` is honored by vfmt
unedited.
**Requested of others (not done here)**
- *`crates/vfmt`'s owner (concurrent this round)*: a `vfmt check --rules-doc`
flag that prints `vlog_linter::rules_markdown()` to stdout and exits 0.
One `println!`; no other wiring. Until then the same output is available as
`cargo run -p vlog_linter --example rules_markdown`.
- *config-discovery's owner*: the `lint` key in `vfmt.toml` is what
per-rule naming-style configuration waits on — the shape wanted is
`[lint.parameter-name-style] style = "CamelCase"` picking one of the named
presets, not a regex. Restated from `linter-core`, unchanged.
- No request to `vlog_formatter`, `vlog_semantic`, `vfmt_server` or
`vfmt_core`; none of them was touched.
## Status / TODO
- [x] `visit.rs` walks `ItemKind::Class` bodies — the classes handshake.
- [x] `visit.rs::walk_param_ports` — module **and** class header `#( ... )`
parameter ports, shared by the two parameter rules.
- [x] `src/naming.rs`: `lower_snake_case`, `UPPER_SNAKE_CASE`, `CamelCase`
predicates + escaped-identifier exemption, no regex dependency.
- [x] `parameter-name-style` (default on).
- [x] `enum-name-style` (default on).
- [x] `struct-union-name-style` (default on).
- [x] `module-name-style` (default **off** — see the defaults table).
- [x] `wire-reg-mixup` (default on).
- [x] `Rule::default_on()` + `Rule::fix()`; `default_rules()` filters.
- [x] `rules_markdown()` + golden shape test + "every rule appears" test +
fix-metadata consistency test.
- [x] `examples/rules_markdown.rs` so the reference is renderable today.
- [x] Violating/clean/waived/unused-waiver quartets for all five new rules;
class-body coverage tests for all four original AST rules.
- [x] Corpus baseline re-run, before/after per rule.
- [ ] Per-rule style **configuration** — needs the `vfmt.toml` `lint` key.
- [ ] `vfmt check --rules-doc` — `crates/vfmt`, handshake above.
- [ ] Parked naming rules, listed with their Verible names below.
- [ ] External waiver files — untouched, still `linter-core`'s open item.
## Rules shipped, and where each default comes from
Verible's own rule list was checked against
<https://chipsalliance.github.io/verible/lint.html> rather than recalled.
That check changed two decisions, both recorded honestly below.
| Rule | Default | Verible equivalent | Verible's default |
|---|---|---|---|
| `parameter-name-style` | **on** | `parameter-name-style` | enabled |
| `enum-name-style` | **on** | `enum-name-style` | enabled |
| `struct-union-name-style` | **on** | `struct-union-name-style` | enabled |
| `module-name-style` | **off** | *none — no such rule* | — |
| `wire-reg-mixup` | **on** | *none — no such rule* | — |
**`parameter-name-style`** — accepts `CamelCase` or `ALL_CAPS` for both
`parameter` and `localparam`. Verible's defaults are `parameter_style:
CamelCase|ALL_CAPS` and `localparam_style: CamelCase`, i.e. stricter for
`localparam`. vfmt accepts the union for both, deliberately: matching
Verible's `localparam` default would flag `localparam int ADDR_W` — an
overwhelmingly common spelling — in a rule that is on by default, and vfmt
has no per-rule config key yet to relax it with. When that key lands, the
strict split is the natural first setting to offer. Covers item- and
statement-level declarations and the `#( ... )` ports of module *and* class
headers; `type` parameters are skipped (they name a type, which is Verible's
separate `parameter-type-name-style`, parked).
**`enum-name-style`** — Verible's default pattern is literally
`[a-z_0-9]+(_t|_e)`; vfmt checks `lower_snake_case` ending in `_e` or `_t`,
the same shape. Only `typedef enum` is judged: an anonymous enum has no name,
and *requiring* the typedef is Verible's separate `typedef-enums` (parked).
**`struct-union-name-style`** — Verible requires `lower_snake_case` ending in
`_t` for `struct` and `union`; vfmt checks the same. Only `typedef struct` /
`typedef union`; requiring the typedef is Verible's `typedef-structs-unions`
(parked).
**`module-name-style` ships OFF, which is a deliberate deviation from the
round's brief.** The brief said "snake_case default-on per Verible".
Verible has **no `module-name-style` rule at all** — the documentation check
above is explicit about it, and the nearest things it does have are
`module-filename` (enabled by default, which vfmt already implements) and
`interface-name-style` for the sibling construct. The instruction for this
round was to default a naming rule on *only* where Verible defaults its
equivalent on, and there is no equivalent to inherit a default from, so the
rule ships selectable but quiet: `vfmt check --select module-name-style`.
The rationale in `Rule::doc` cites the lowRISC/Google SystemVerilog style
guide, which does require `lower_snake_case` for module names. Flipping it on
is a one-line change (`fn default_on`) if the lead prefers the brief's
reading; the corpus evidence (**one** finding over 860 files) says it would
be quiet either way.
**`wire-reg-mixup` ships ON, and TODO.md's provenance note for it is wrong.**
TODO §4 lists it under "all from Verible's default set"; Verible has no
wire/reg rule of any kind. It ships on anyway because it is an explicitly
requested seed rule, because the corpus says it is silent on real
SystemVerilog (0 findings over 860 files, see below), and because its
rationale stands on IEEE 1800 (`logic` and `reg` are the same type) and the
lowRISC style guide's "use `logic`" without needing Verible. The README is
the place that record lives; `TODO.md`'s item text is left intact per
CLAUDE.md.
What `wire-reg-mixup` deliberately does **not** flag:
- **`wire` itself.** A net is a distinct kind of object in SystemVerilog too,
and `wire x = expr;` is a perfectly good continuous assignment. Flagging
`wire` would be a house-style opinion, not a mixup.
- **Anything in a `.v`/`.vh` file**, or in a nameless stdin buffer. `reg` is
Verilog's spelling; the rule has no opinion about Verilog.
- **`reg` inside a `` `define`` body**, which is never lexed as a keyword.
- It offers **no fix**, though `reg` → `logic` would be a meaning-preserving
one in SystemVerilog. A `reg` in a `.sv` file is usually a symptom of code
carried over wholesale, and the repair worth making is bigger than the
keyword. A Safe fix is the obvious follow-up if the corpus ever grows a
population for it.
### Parked, with their Verible names
Listed so the next round does not have to rediscover them:
`signal-name-style` (Verible: off by default), `interface-name-style`,
`constraint-name-style`, `macro-name-style`, `parameter-type-name-style`,
`create-object-name-style`, `port-name-suffix`, `dff-name-style`,
`typedef-enums`, `typedef-structs-unions`, `package-filename`.
`genvar-name-style` is parked too and is *not* a Verible rule: genvars are
conventionally one-letter (`i`, `j`) or `gen_*`, and no preset here has
anything useful to say about `i`.
## Why no regex dependency
Verible spells naming conventions as RE2 patterns. vfmt spells them as three
character-class predicates in `src/naming.rs`, roughly 20 lines:
```
lower_snake_case first char [a-z], then [a-z0-9_]
UPPER_SNAKE_CASE first char [A-Z], then [A-Z0-9_]
CamelCase first char [A-Z], then [A-Za-z0-9] (no underscore)
```
The justification CLAUDE.md asks for, in full: every preset anyone actually
uses *is* "these character classes, in this order". A regex crate would buy
user-supplied patterns — which this round explicitly does not ship, because
they need a config key that does not exist — at the cost of the crate's only
real property, that `cargo tree -p vlog_linter` is `vlog_parser` + std. When
the `lint` key lands, the setting it should offer is a **named preset**, not
a pattern: "no option explosion" is TODO §7, and a regex field in a config
file is the option explosion of naming rules. A lower-first `camelCase`
predicate was specified for this round and deliberately **not** written: no
rule needs it, and an unused predicate is an abstraction for a second user
that does not exist.
## Class-body coverage: what changed and what it found
One arm in `visit.rs::items()`:
```rust
ItemKind::Class(class) => items(&class.items, f),
```
plus `walk_param_ports`, which yields the `#( ... )` parameter ports of both
module and class headers and is now what both parameter rules use (previously
`explicit-parameter-storage-type` inlined a module-only version).
All four originally-AST-walking rules were verified firing inside a class
body by test, not by inspection:
| Rule | Class-body test |
|---|---|
| `case-missing-default` | `case_missing_default_reaches_a_class_method` |
| `explicit-parameter-storage-type` | `explicit_parameter_storage_type_reaches_a_class_body_and_header`, `a_class_inside_a_module_is_reached_too` |
| `always-comb-blocking` | `the_always_rules_reach_a_class_body_too` |
| `always-ff-non-blocking` | `the_always_rules_reach_a_class_body_too` |
Honest caveat on the last two: **SystemVerilog forbids an `always` block
inside a class**, so that test pins walk uniformity, not a real-world
population. The tolerant parser accepts the shape and the rules fire on it;
in real code these two rules gain nothing from this change, and the corpus
agrees (both deltas are 0).
## Corpus baseline
860 files (`corpus/`: ibex, opentitan, picorv32, common_cells), read-only,
0.08–0.09 s wall on 10 cores. Byte-identical across repeated runs and between
`--threads 1` and the default pool.
**Before** is this working tree at the start of the round, *not* the number in
`docs/features/linter-core/README.md`: the concurrent classes/parser work has
already moved what parses, so linter-core's 7806/93 no longer reproduces here
(it reads 7875/88 before any of this round's changes). Comparing against a
stale number would misattribute someone else's delta to this round.
| Rule | Before | After | Δ | Files after | Cause of Δ |
|---|---|---|---|---|---|
| `no-tabs` | 7527 | 7527 | 0 | 45 | — |
| `explicit-parameter-storage-type` | 182 | 183 | **+1** | 51 | class-body walk |
| `no-trailing-whitespace` | 85 | 85 | 0 | 7 | — |
| `case-missing-default` | 60 | 65 | **+5** | 21 | class-body walk |
| `parameter-name-style` | — | 39 | **+39** | 11 | new rule |
| `module-filename` | 17 | 17 | 0 | 17 | — |
| `always-ff-non-blocking` | 4 | 4 | 0 | 1 | — |
| `struct-union-name-style` | — | 1 | **+1** | 1 | new rule |
| `always-comb-blocking` | 0 | 0 | 0 | 0 | — |
| `enum-name-style` | — | 0 | 0 | 0 | new rule |
| `wire-reg-mixup` | — | 0 | 0 | 0 | new rule |
| `unused-waiver` | 0 | 0 | 0 | 0 | — |
| **default-rule total** | **7875** | **7921** | **+46** | **96 files** | |
| `module-name-style` (off) | — | 1 | — | 1 | new rule, `--select` |
Read honestly:
- **Nothing was lost.** Diffing the two runs by `(file, rule, byte range)`:
46 findings appear, **0 disappear**. The change is purely additive, which is
what an added walk arm should be.
- **The class-body growth is +6 findings in 4 files, all DV code**, exactly as
predicted. The five new `case-missing-default` are `case` statements in UVM
scoreboards/sequences (`opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv` ×3,
`uart_intr_vseq.sv`, `ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv`);
the one new `explicit-parameter-storage-type` is `localparam BusWidth = 32;`
inside a class in `ibex_icache_scoreboard.sv`. These are new *findings*, not
new *violations* — the code always looked like this; the linter could not
see it.
- **`parameter-name-style`'s 39 are concentrated in testbenches and
picorv32** (14 in `picorv32.v`, 9 in `spiflash.v`, the rest ≤3 per file),
and every one is a `lower_snake_case` constant. Synthesizable lowRISC RTL
is essentially clean, which is the point: it is written to the style guide
this rule encodes.
- **`enum-name-style` scoring 0 was checked, not assumed.** A separate scan
found **166** `typedef enum` names in the corpus's `.sv`/`.svh` files and
**0** of them violate `[a-z_0-9]+(_t|_e)`. The rule is silent because the
corpus conforms.
- **`wire-reg-mixup` scoring 0 was checked the same way**, and this one
needed proving because a silent rule and a broken rule look identical. The
corpus's `.sv`/`.svh` files contain no `reg` at all, while `picorv32.v` is
full of them. Copying `picorv32.v` to `picorv32.sv` and re-running gives
**209** findings; the identical bytes as `.v` give **0**. The extension
gate works and the rule works.
- **`module-name-style`'s single finding** is
`common_cells/src/deprecated/generic_LFSR_8bit.sv` — in a directory named
`deprecated`. That is the entire population over 860 files, which is why
its default costs nothing either way.
## The generated rule reference
`vlog_linter::rules_markdown() -> String` renders the whole registry as one
markdown document — 139 lines today. Shape:
```markdown
# vfmt 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 `--select <name>`. ...
| Rule | Default | Fix |
|---|---|---|
| [`always-comb-blocking`](#always-comb-blocking) | **on** | none |
...
| [`module-name-style`](#module-name-style) | off | none |
| [`no-tabs`](#no-tabs) | **on** | safe |
...
## always-comb-blocking
Assign with `=` inside always_comb.
- Default: **on**
- Fix: none
A non-blocking assignment in a combinational block schedules its update ...
```
An index table (name → anchor, default, fix applicability) followed by one
`##` section per rule carrying the capitalized summary, the two metadata
lines and `Rule::doc` verbatim. Nothing is written per rule outside the rule's
own source, which is the whole point: the reference cannot drift.
Three tests hold it:
- `every_registered_rule_appears_with_its_summary_and_doc` — iterates
`all_rules()` and asserts each name, summary and doc text is present. A new
rule that forgets the docs cannot exist.
- `the_document_shape_is_pinned` — the golden test: the first eight lines
verbatim, plus the exact per-rule section template rendered from the first
registered rule and asserted to appear. It pins the *shape*, not the prose,
so improving a rule's `doc` does not churn a snapshot.
- `declared_fix_metadata_matches_what_the_rules_return` — the drift guard
described in Assumptions.
`cargo run -p vlog_linter --example rules_markdown` prints it today; the
`vfmt check --rules-doc` flag is filed as a handshake because `crates/vfmt`
belongs to a concurrent agent this round.
## Zero-wiring claim, verified
The claim that a new rule needs no wiring outside the registry was checked by
running the built binary, not by reading the code:
- `vfmt check corpus/` reports the four new default-on rules with no CLI
change (the table above is that run).
- `vfmt check ... --select module-name-style` runs an off-by-default rule,
and `--select wire-reg-mixup` an on-by-default one; both were used to
produce numbers above.
- `--ignore <new-rule>` and `// vfmt: waive <new-rule>` work by construction
(they key on `rule_by_name`), and each new rule has a waiver test.
- `crates/vfmt_server/src/lint.rs` was read **read-only**: it calls
`default_rules()` with no filtering of its own, so the four new default-on
rules appear as editor diagnostics automatically, and `module-name-style`
correctly does not. `cargo test -p vfmt_server` stays green.
## Work log
### 2026-08-19 — dev
- **Verified Verible's rule set against its documentation instead of
recalling it**, which changed two of the round's stated decisions:
Verible has no `module-name-style`, no `genvar-name-style` and no wire/reg
rule, so `module-name-style` ships default-**off** (deviation from the
brief, argued above) and `wire-reg-mixup`'s "it's Verible-default"
provenance is recorded as incorrect while the rule still ships on. Also
confirmed the exact default patterns now implemented: `[a-z_0-9]+(_t|_e)`
for enums, `lower_snake_case` + `_t` for structs/unions, and the
`CamelCase` / `CamelCase|ALL_CAPS` split for parameters.
- **Named the typedef rules after Verible's two rules** (`enum-name-style`,
`struct-union-name-style`) rather than inventing one `typedef-name-style`.
Rule names are what appear in users' waivers, so matching Verible's
spelling means a `// verilog_lint: waive enum-name-style` already in
vendored code is honored instead of ignored. Typedef *aliases*
(`typedef logic [7:0] x;`) are judged by neither, matching Verible.
- `visit.rs`: one arm for `ItemKind::Class`, plus `walk_param_ports` so the
two parameter rules share one answer for "every `#( ... )` port" —
`explicit-parameter-storage-type` was rewritten onto it, which also gave it
class-header parameter ports (0 additional corpus findings; the class
headers in this corpus are all `type` parameters or typed).
- `Rule` gained `default_on()` and `fix()`, both with defaults so no existing
rule file had to change except the two that offer fixes. `default_rules()`
filters on the former. The one off-by-default rule is what keeps that
mechanism from being a phantom: the registry test asserts the default set
is a strict subset, so it cannot silently become "all of them" again.
- `rules_markdown()` lives in its own module rather than in `registry.rs`:
the registry is about *selecting* rules, and rendering has three tests of
its own.
- **Test counts**: `vlog_linter` 116 unit (was 71) + 55 inline-marker
integration (was 30) + 1 doctest, all green. New: 5 quartets, 4 class-body
reach tests, 3 walk tests, 5 naming-predicate tests, 4 rule-doc tests, 2
registry default-set tests, and the per-rule unit tests in each new rule
file.
- **Gates**: `cargo test -p vlog_linter` green (116/55/1);
`cargo test --workspace` green; `cargo clippy -p vlog_linter --all-targets`
silent; `cargo fmt -p vlog_linter --check` clean. The workspace has one
clippy warning (`methods called from_* usually take no self`) and one
`cargo fmt --check` diff, **both in `crates/vlog_formatter`** — the
concurrent agent's churn, untouched here.
- **Scope**: files changed are `crates/vlog_linter/**`, this README, and
`TODO.md` §4 checkboxes. `crates/vfmt`, `vfmt_server`, `vlog_parser`,
`vlog_formatter`, `vlog_semantic` and `vfmt_core` were not modified;
`vfmt_server/src/lint.rs` was read only.
- **TODO.md §4**: checked the naming-rules item (with the "styles are fixed
presets, configuration waits on the `lint` key" caveat spelled out) and the
`--generate_markdown` item; checked the `wire`/`reg` sub-item of the seed
rules. Left external waiver files, the `lint` config key and "one parse,
two tools" unchecked.
## QA log
### 2026-08-19 — QA
Scope: `-p vlog_linter` only, plus a read-only look at `crates/vfmt/src/lint.rs`
and `crates/vfmt_server/src/lint.rs` for the wiring/fence claims. Did not touch
`vlog_formatter`, `vfmt_server`, `vlog_parser` or `vlog_semantic` (concurrent
this round). All six claims verified; no corpus regression; no preset false
positive/negative found. Two documentation-gap findings, no functional bugs.
**Gates** — `cargo test -p vlog_linter`: 116 unit + 55 inline-marker + 1
doctest, all green, exact match to the claimed counts. `cargo clippy -p
vlog_linter --all-targets`: silent. `cargo fmt -p vlog_linter --check`: clean.
`cargo tree -p vlog_linter`: `vlog_parser` + std, no new dependency. Bonus:
`cargo clippy --workspace --all-targets` and `cargo fmt --all --check` are
*both* silent right now — the "1 clippy warning + 1 fmt diff in
vlog_formatter" the work log flags as the concurrent agent's churn is not
present in the tree as I found it (their round must have landed since the
work log entry was written); not this feature's concern either way.
**Verible citations, checked against the live page, not just the README's
claim** — fetched <https://chipsalliance.github.io/verible/lint.html>
independently. `parameter-name-style`: enabled by default, `parameter_style`
default `CamelCase|ALL_CAPS`, `localparam_style` default `CamelCase` — matches
the README's claim of a deliberate union-not-split deviation. `enum-name-style`:
enabled by default, pattern `[a-z_0-9]+(_t|_e)` — exact match. `struct-union-
name-style`: enabled by default, lower_snake_case ending `_t` — exact match.
No `module-name-style`, no `genvar-name-style`, no wire/reg rule of any kind —
all three "no such rule" claims confirmed independently. Claim 1: **pass**,
externally verified, not just internally consistent.
**visit.rs / class-body walk** (claim 2) — `cargo test -p vlog_linter`
includes all the class-body reach tests named in the README and they pass.
Additionally probed live: `parameter-name-style` fires on a class header
`#(parameter int bad_name = 1)` (`walk_param_ports`), `case-missing-default`
fires on a `case` inside a class method. **Pass.**
**Corpus** (claim 3) — reproduced deterministically.
- After: built `vfmt --release` at the current working tree, ran `vfmt check
corpus/ --output-format json`. Total **7921**, 96 files, and the per-rule
breakdown (no-tabs 7527/45, explicit-parameter-storage-type 183/51,
no-trailing-whitespace 85/7, case-missing-default 65/21,
parameter-name-style 39/11, module-filename 17/17, always-ff-non-blocking
4/1, struct-union-name-style 1/1) matches the README's table exactly, cell
for cell.
- Before: rather than trust the README's number, rebuilt it independently
with `git worktree add <scratch> HEAD` (last commit, before this round's
`vlog_linter` changes) and ran the same corpus check there:
**7875**, 88 files, breakdown (no-tabs 7527/45,
explicit-parameter-storage-type 182/50, no-trailing-whitespace 85/7,
case-missing-default 60/18, module-filename 17/17, always-ff-non-blocking
4/1) — an exact match to the README's claimed "before", which is itself
*not* `linter-core`'s stale 7806/93 (confirming the attribution reasoning:
HEAD already carries the concurrent classes/parser round's commits).
- Diffed both JSON dumps by `(filename, rule, range.start, range.end)`:
**46 appeared, 0 disappeared** — purely additive, exact match, broken down
identically to the README (case-missing-default +5, parameter-name-style
+39, struct-union-name-style +1, explicit-parameter-storage-type +1).
- `--select module-name-style`: **1** finding,
`common_cells/src/deprecated/generic_LFSR_8bit.sv` — exact match.
- Proven zero #1: extracted every `typedef enum ... name;` in the corpus's
`.sv`/`.svh` with an independent regex scan (not the linter) — **166**
names, **0** violate `[a-z_0-9]+(_t|_e)`. Matches the claimed 166/0 exactly.
- Proven zero #2: `vfmt check corpus/picorv32/picorv32.v --select
wire-reg-mixup` → 0. Copied the identical bytes to `picorv32.sv` in the
scratchpad and re-ran → **209**. Matches exactly.
- Claim 3: **pass**, every number reproduced independently and exactly, not
just re-read from the README.
**Zero-wiring** (claim 4) — `vfmt check <file> --select nope` lists all
**13** known rules in its error, alphabetical, as `registry.rs`'s own test
already pins. `crates/vfmt_server/src/lint.rs` read (not modified): both call
sites use `default_rules()` unfiltered, so the four new default-on rules and
not `module-name-style` reach server diagnostics automatically, by
construction. **Pass.**
**Attack probes — preset predicates** (`crates/vlog_linter/src/naming.rs`):
`Camel_Case` (mixed) → flagged by `parameter-name-style` (fails both
presets, correct). `ALL_CAPS2` (digit suffix) → accepted (correct, digits are
in the `ALL_CAPS` character class). `_WIDTH` (leading underscore) → flagged
(correct, `starts_with` requires an uppercase *first* char). `N`
(single letter) → accepted (correct, passes both presets trivially, matches
the doc). `weird_E` (uppercase suffix) → flagged (`_e`/`_t` check is
case-sensitive on the suffix, matches the documented pattern shape).
`weird_t`/`weird_e` → accepted. `foo_t` → accepted, `foo_s` → flagged
(`_e`-suffixed name is correctly not exempted from struct's `_t`
requirement). Escaped identifier `\weird+name` as a parameter name → the file
parses cleanly (confirmed via the unrelated `module-filename` rule still
firing on the same file) and `parameter-name-style` is silent on it, i.e. the
exemption is `is_escaped` working, not a parse failure hiding it. No panics
anywhere. **Pass**, with one documentation nit below.
**Attack probes — wire-reg-mixup scoping**: `.sv` fires, `.svh` fires
(case-insensitive extension check confirmed via `.SV` too, in the existing
unit tests), `.v` silent, stdin without `--stdin-filename` silent, stdin
*with* `--stdin-filename x.sv` fires. `reg` inside a class body in a `.sv`
file fires. `reg` inside a string literal (`"reg in a string"`) and inside a
leading comment do **not** false-positive — confirmed live, not just by
reading the token-kind filter. **Pass.**
**Attack probes — class-body coverage and the fence/waiver asymmetry**:
`// vfmt: waive case-missing-default` inside a class method body suppresses
the finding — confirmed live. The fence question (does `// vfmt: off` inside
a class body protect a `--fix` edit, given the classes round found the
*formatter's own* `scan_nested` inactive there) — built a probe file with a
tab fenced inside a class body:
```systemverilog
class c;
// vfmt: off
int a;
// vfmt: on
endclass
```
`vfmt check --select no-tabs` **still reports** the tab (fences gate fixes,
not diagnostics — confirmed, not assumed). `vfmt check --select no-tabs
--fix` on the same file leaves the tab **untouched** — the fix is correctly
declined. `vfmt format` on the identical file, no `--fix`, silently
reformats the tab away, exactly reproducing the classes round's finding that
the formatter's own fence is inactive there. Read `fence::protected_regions`
(`crates/vlog_formatter/src/fence.rs:96`) to understand *why* these two
disagree: it is `collect` (the AST/`scan_nested`-based answer, which does not
recurse into class bodies, per the classes README) **unioned with**
`scanned_regions` (a pure line-based text scan with no notion of scope at
all, `fence.rs:124`) — the backstop exists for "the broken files only the
linter and the server see" but it fires unconditionally, so it also catches
a fence the AST scan missed. That is a real, confirmed mechanism, not a
guess — and it means `--fix` is *more* conservative inside a class body than
the formatter itself is, which is the harmless direction but is currently
**undocumented in both `docs/features/classes/README.md` and this README**.
Filed as a should-fix below. **Pass on behavior; documentation gap found.**
**Sabotage** — broke `is_upper_snake_case` in `naming.rs` to accept any
uppercase-first alphanumeric-or-underscore name (i.e. `"Width"` would wrongly
pass as `ALL_CAPS`). `cargo test -p vlog_linter`: exactly **one** test failed,
`naming::tests::upper_snake_case_accepts_what_parameters_write` (the negative
case `"Width"`). No `parameter-name-style` test caught it, because every
mixed-case name in that rule's own test file already happens to be valid
`CamelCase` regardless of the `ALL_CAPS` predicate, so the coverage for this
predicate lives only in `naming.rs`'s own unit tests — which is sufficient
(the failure is unambiguous and points straight at the broken predicate) but
worth knowing if a future preset gets a fourth caller. Reverted; `cargo test
-p vlog_linter` green again; `git diff -- crates/vlog_linter/src/naming.rs`
empty, confirmed byte-identical to the pre-sabotage state.
**Findings**
- *Should-fix, documentation gap (not a corruption, not a corpus regression;
the actual behavior is the safe/conservative direction).* Neither
`docs/features/classes/README.md` nor this README states that a
`// vfmt: off` fence inside a class body **does** protect `vfmt check
--fix` (via `fence::protected_regions`'s line-based backstop scan), even
though the classes round documented, correctly, that the same fence is
**inactive** for `vfmt format` itself (the AST-scoped `scan_nested` doesn't
recurse into class items). Both facts are true and now confirmed by test;
neither README says both in one place, so a reader of either document alone
would reasonably conclude the fence does nothing at all inside a class
body, which is false for the `--fix` path. Suggest a short paragraph in this
README's "Class-body coverage" section (or a line in
`docs/features/classes/README.md`'s existing fence-inactive note) stating
the asymmetry plainly, with the mechanism (`collect` vs `scanned_regions`)
named. Not fixed directly — it's a cross-cutting note that belongs to
whichever agent owns `crates/vfmt/src/lint.rs` / the fence handshake, not a
typo I can fix unambiguously in-place.
- *Minor nit, not blocking.* The Assumptions section says "A non-ASCII
identifier fails `lower_snake_case` etc. and is reported." In practice a
genuinely non-ASCII byte in an identifier does not reach any naming rule at
all: `vlog_linter::context`'s own comment says "a lex error leaves no
tokens (the lexer is all-or-nothing)", confirmed live — `vfmt check` on a
file containing `parameter int élan = 1;` exits 0 with **zero** findings
(not even the unrelated `module-filename`), while `vfmt format` on the same
file correctly refuses with a `lex error` (invariant intact, nothing
corrupted). So the practical claim is even truer than stated ("no practical
population" because it's unreachable, not just because it's rare) but the
wording "is reported" is not literally accurate for that case — pre-existing
`context.rs` behavior, not introduced by this round, not worth a code
change, just a one-clause wording fix if the README is touched again.
- No preset false positive or false negative found on any probed shape.
No panic on escaped, non-ASCII, or unparseable input.
No corpus regression: diff is exactly and only additive.
**Verdict**: all six claims **pass**. Nothing blocking. Two documentation
gaps filed above, both pre-existing/cross-cutting rather than owned by this
round's code.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 18. The
linter now stands at 13 rules with Verible-compatible names and
evidence-based defaults.**
Points reviewed and accepted:
1. **Both brief premises were falsified against Verible's published
docs and the deviations argued**: module-name-style ships OFF
because no Verible default exists to inherit (my brief said on —
the agent was right to override it with the round's own
default-rule); wire-reg-mixup's provenance correction is recorded
where the wrong claim lives. Checking the source instead of
trusting the brief is exactly what the house rewards, and QA
independently re-fetched the docs to confirm.
2. **Using Verible's exact rule names** (enum-name-style,
struct-union-name-style) instead of an invented umbrella means
vendored `verilog_lint:` waivers now suppress instead of being
ignored — compatibility as a design input, not an afterthought.
3. **The class-body walk closes the classes handshake** with honest
deltas (+6 findings, all real UVM code; always-* uniformity noted
as population-free) and the corpus baseline correctly re-measured
on this tree rather than inherited stale.
4. **Both zeroes proven** (166 conforming enums; the .v→.sv rename
yielding 209) — a zero you've probed is evidence; a zero you
assumed is a blind spot.
5. QA's fence-asymmetry finding is now documented in both owning
READMEs (lead notes in classes and shared-fence-filter): a fence
inside a class body protects fixes via the scan backstop even
though the formatter ignores it there. The non-ASCII lexing nit
belongs to the lexer's existing gap list.
Remaining §4 items stay honestly open: external waiver files,
per-rule style configuration (needs the vfmt.toml lint key), and the
--rules-doc CLI flag (handshake filed; rules_markdown() is ready).
+710
View File
@@ -0,0 +1,710 @@
# range-formatting
## Goal
Format only the lines the caller names and emit every other byte exactly as it
was written — `vfmt --lines M-N[,M-N...]`, and `textDocument/rangeFormatting`
on the same engine. This is the adoption story for a legacy tree: a formatter
that can only rewrite a whole 2000-line file is one that never gets turned on,
because the first patch it touches becomes unreviewable. Verible ships
`git-verible-verilog-format.sh` on top of exactly this, and `tools/vfmt-changed.sh`
is our version. A range is morally an **inverted fence**: the same
`Doc::Verbatim` splice `docs/features/format-fences/README.md` built, over
byte ranges the *caller* chose instead of ranges a comment marked.
## Semantics
### The unit is one item
> **An item whose lines meet a requested range is laid out exactly as a
> whole-file run would lay it out. Every other item is emitted as the source
> bytes it was written with.**
An **item's lines** are its whole *unit*: its leading comments, its
`(* attributes *)` and code, and the comment written after it on the same
line. Two consequences worth stating:
- Selecting a doc comment selects the declaration under it. The comment is
part of the unit, and laying out half a unit is not a thing the printer can
do.
- Selecting a **blank line** selects nothing. A blank line belongs to no
item, so a range that only covers blank lines leaves the file untouched.
This matters more than it sounds: without it, a range hitting the gap
between two items would descend into the module around them and normalize
the gaps at the boundaries for no reason at all.
A scope's **dangling comments** (the ones after its last item) are units of
their own, selected the same way.
### One level down: modules and packages are descended into
"An intersected item formats whole" is too coarse for the use case — *I edited
three lines of a 2000-line module*. So a **module** or a **package** whose
body contains a selected item is cut into three:
| part | what it is | when it is laid out |
|---|---|---|
| head | leading comments through the `;` that closes the header | its own lines are selected |
| body | the item list, planned recursively | per item, by the rule above |
| tail | the `endmodule`/`endpackage` line, its trailing comment included | its own lines are selected |
The three decisions are independent: editing the port list lays out the header
and leaves the body alone; editing one declaration lays out that declaration
and leaves the header and the closing keyword alone.
**Only modules and packages.** A `generate` region, a `class`, a
`begin`…`end`, a function or a task is **one unit**: selecting a line inside a
generate region lays out the whole region. They are item scopes too, but they
have no header worth keeping apart from their body, and the two shapes above
are the ones that are thousands of lines long in real RTL. Lifting this is a
small change to `scope_of` plus a head/tail doc for the new kind; it is not
done because nothing yet needs it.
**Statements are never descended into, deliberately.** Selecting one line of
an `always` block lays out the whole block. Going a level deeper means
splitting statement lists the same way item lists are split, which is a second
copy of the machinery for a case nobody has asked for; the item level already
buys the two-thousand-line-module win.
### A module that cannot be cut
The head/tail slices are emitted at column zero and carry their own
indentation, so every boundary has to fall on a line of its own. A module
written `module m; wire a; endmodule`, or one with an empty body, has no such
line: it is one unit, laid out whole or not at all. Same for a package.
### Runs
Consecutive unselected units are merged into **one** verbatim slice rather
than emitted one at a time. This is not an optimization — it is what makes
"everything else verbatim" true. Emitted separately, each unit would get an
item separator between it and the next, and the separator normalizes runs of
blank lines to one. Merged, the blank lines are *interior bytes of the slice*
and survive exactly.
### What still changes outside the range
Three things, all of them the same normalizations a fenced region already
lives with, and all tested:
1. **The file's tail.** Exactly one final newline, as in every run.
2. **Blank lines at a boundary.** The gap between a laid-out item and the
verbatim run next to it is written by the item separator, which collapses
two or more blank lines to one. Inside a run nothing is touched.
3. **Line terminators the formatter writes are `\n`.** A `\r` between two
units is inter-unit whitespace and nobody emits it; a `\r` *inside* a run
is an interior byte and survives. This is what a whole-file run already
does to a CRLF file, so it is consistent rather than new.
## Ranges
`--lines` takes 1-based, **inclusive** line ranges: `M-N`, a bare `M` for one
line, comma-separated (`3-9,40`) and repeatable (`--lines 3-9 --lines 40`).
The two forms mean the same thing; ranges are sorted and merged, and adjacent
ranges (`1-2,3-4`) fold into one because that changes no answer.
| input | answer | why |
|---|---|---|
| `5-1` | **error** | a reversed range is a typo, not an intent |
| `0`, `0-3` | **error** | lines are 1-based; `0` is a caller bug |
| empty piece (`1,,2`), empty spec, `x`, `1-2-3` | **error** | unparsable |
| `900-1000` on a 20-line file | **clamped**, i.e. it matches nothing | a wrapper deriving ranges from a diff cannot know where the file ends, and refusing would make the wrapper's job harder for no safety gain |
The parse happens during argument handling, so a bad spec exits 2 before any
file is read.
## Interaction rules
### `// verilog_format: off` outranks `--lines`
A fenced item is never laid out, whatever the caller selected. `off` means
hands off across all of vfmt (the position `docs/features/shared-fence-filter/README.md`
already took for `--fix` and the server's quick fixes), and a range is a
weaker signal than a comment somebody wrote into the source. Mechanically the
planner asks `fence::region_at` before it asks about lines, and the two
region lists are merged into one sorted, non-overlapping list, so the fence's
own bytes are emitted by the fence's own opener.
One case reads oddly and is correct: the `on` fence is the *leading comment*
of the item after the region, so selecting the `on` line selects that item.
The region itself still does not move.
### Alignment groups break at a range boundary
Alignment groups are mostly per-list *inside* one item — a port list, a
connection list — and those travel with their item, so a range boundary can
never fall inside one. **The exception is `param_decl_aligns`**, which groups
consecutive `parameter`/`localparam` *items* in a scope, and a range boundary
can absolutely fall inside that.
The answer needed no new code: `param_decl_row` already returns `None` for an
item inside a verbatim region (it was written for fences), and generalizing
that predicate from "fenced" to "verbatim" is the whole change. So an
unselected member leaves the group and keeps its bytes; the selected members
form their own group and align among themselves; a lone selected member has
nothing to align to and formats flush. Both passes see the same split, which
is why it is still a fixed point.
```systemverilog
// --lines 2-3
localparam int A = 1; // selected: these two align to their own column
localparam int BBBBB = 2;
localparam int C = 3; // not selected: byte-for-byte as written
```
### A file that does not parse is refused
Range formatting cannot rescue broken input. `format_range` calls the same
strict `parse_source` as `format_source`, so a parse error is an error and an
untouched file (exit 2), even when the range names none of the broken lines.
The tolerant parser exists for the LSP's diagnostics, not for the formatter —
splicing verbatim bytes around an `ItemKind::Error` would mean printing a
guess about code we could not read.
## Safety
The runtime net runs over the **whole output**, unchanged, and `verify.rs` was
not touched — no normalization was added, broadened or weakened, so CLAUDE.md
hard invariant #4 does not apply to this round.
- **Equivalence** (`verify_equivalence(source, output)`) is global and exactly
as strong as always. It holds by construction — a verbatim slice re-lexes to
the tokens it came from, and a laid-out item is ordinary formatter output —
and it is the backstop that catches any mistake in that reasoning. It
earned its keep during development: the first version of the split computed
the body's end from the last *item* and forgot the scope's dangling
comments, so the tail slice re-emitted a comment the run had already
emitted. Equivalence rejected it immediately.
- **Convergence** is the half that needed thought, because a *line* range is
not a stable name for anything once the text moves.
### Convergence: replay the decisions, not the line numbers
`format_range` runs:
1. `select(source, tree, lines)` → a `Selection`: one `Pick` per unit
(`Verbatim`, `Format`, or `Split { head, tail }`), in the order a
depth-first walk over item scopes visits them.
2. `format_selected(source, selection)` → the output.
3. `verify_equivalence(source, output)`.
4. `format_selected(output, selection)` — the **same** selection, replayed.
5. `verify_convergence(output, again)`.
The replay is sound because equivalence already proved the output's token
stream is the input's, comments included; the same tokens parse to the same
item tree, so the same walk visits the same units in the same order and pops
the same picks. What each unit *does* is then a fixed point for reasons the
whole-file formatter already establishes: a laid-out item is formatter output
being formatted again, and a verbatim slice is the same bytes. Alignment
groups are split identically in both passes because the split depends on the
picks, not on the text.
To keep that invariant honest, **the body of a module or package is always
walked, splittable or not**. The shape of the pick list then depends on the
item tree alone, never on whitespace — otherwise a module that was
unsplittable in the input but splittable in the output would consume picks
differently on the replay and the check would fail for a bookkeeping reason.
### Idempotency: what is and is not promised
**Promised, and checked at runtime:** replaying the same selection is a fixed
point. That is what "the output is stable" means for a partial run.
**True in practice, and tested:** running `vfmt --lines M-N` twice on the same
lines changes nothing the second time — *when the first run did not move the
selected lines*. Every hand-written case in `tests/ranges.rs` is of that kind,
which is the normal editing experience.
**Not promised:** the same *line numbers* after the text moved. Laying out a
construct can change how many lines it takes, and the second run's line
numbers then reach different constructs:
```systemverilog
// --lines 1-3, twice
module m #( → module m #(parameter P = 1) (input a); // pass 1
parameter P = 1 → wire x; // line 4 → 2
) (input a);
wire x; → module m #(parameter P = 1) (input a); // pass 2
endmodule → wire x; // now inside lines 1-3
```
That is another correct, fully verified partial run — not a broken fixed
point. Measured on the corpus: of 8236 range trials, 449 (5.5 %) reached
further on a second run with the same line numbers, and **every one of them
settled on that second run** (checked to 12 iterations; none needed a third).
**Also not promised, and this is the feature:** a partial run is not a fixed
point of the *whole-file* formatter. `vfmt` with no `--lines` afterwards will
reformat more. That is the point of having formatted less.
## CLI
```
--lines <M-N> format only the constructs meeting these 1-based, inclusive
line ranges; comma-separated and repeatable
```
- **Format only.** `vfmt check --lines` is an error: the linter has no notion
of a line range (waivers are its equivalent).
- **Explicit files, never a directory.** "Line 12 of everything under `rtl/`"
is not a thing anyone meant, so a directory input is an error. Several file
arguments are accepted and get the same ranges each — defined, but a wrapper
should invoke once per file, which `tools/vfmt-changed.sh` does.
- **Combines with** `--check`, `--diff`, `--stdout`, and stdin (`-`, with
`--stdin-filename`). `--check` exits 1 only if the *partial* format would
change something, which is what makes "CI checks the lines this PR touched"
possible.
- **The cache is off.** A `--lines` run neither reads nor writes it. Reading
would be wrong twice over: a hit skips the file entirely, including the very
lines the caller named; and writing would record a partially-formatted file
under the "already formatted" verdict, which is the one thing
`docs/features/format-cache/README.md` promises the cache only ever stores.
### `tools/vfmt-changed.sh`
The `git diff` half of TODO.md §2's follow-up. It reads `git diff -U0` hunk
headers, turns each `@@ -old +first,count @@` into `first-(first+count-1)`,
and calls `vfmt --lines` once per changed `.sv`/`.svh`/`.v`/`.vh` file. A hunk
with `count == 0` deleted only and contributes nothing. `--check`/`--diff` and
a base revision pass through, so `tools/vfmt-changed.sh --check origin/main`
is the CI form. A `vfmt --diff-base <rev>` flag *inside* the binary is still
open; the script answers the need without teaching the CLI about git.
## LSP
`documentRangeFormattingProvider` is advertised (it was the README's deferred
capability #1) and `format::range_formatting` serves it.
The protocol's `Range` is a half-open span of UTF-16 positions; the engine
wants inclusive lines, so **only the line numbers survive the conversion** —
which sidesteps the whole UTF-16 column question rather than solving it again.
One rule needs stating: an end position at character 0 of a *later* line is
the start of that line, not any of its content (an editor's "select these
three lines" ends at the start of the fourth), so such a range stops one line
short. An end at character 0 on the range's own start line still selects that
line.
The reply is still **one whole-document `TextEdit`**, and only when the text
actually changed. That is not a contradiction with "range formatting": the
engine's contract is all-or-nothing over the file (CLAUDE.md invariant #1),
and what makes the request a range format is which constructs were laid out,
not which bytes the edit is allowed to replace. A refusal produces no edit and
a `window/showMessage`, exactly as the whole-document handler does — the two
now share `Server::edits` and `Server::warn_about_config`.
## Assumptions
- **A node's span is its code extent, comments excluded** — the `spans`
convention. Both halves are load-bearing here, as they were for fences: the
attribute half is why a spliced item reproduces its `(* keep *)`, and the
comment half is why a unit's extent has to be computed as "leading comments
through trailing comment" rather than read off `Item::span`.
- **The formatter is only reachable through `format_source`/`format_range`**,
so the text spliced from is always the text the spans were lexed from.
- **The same token stream parses to the same item tree.** The convergence
replay rests on this; the parser is deterministic and reads nothing but the
tokens.
- **Slicing is char-boundary safe.** Every offset comes from a span or from a
scan over ASCII whitespace. Slices are still taken with `get()`: a `None`
would produce an empty region, which drops tokens, which equivalence
rejects — a failsafe, not a panic. (Multi-byte content is tested at the
engine, CLI-adjacent and LSP levels.)
- **Files are small enough that planning twice is free.** `format_range`
parses three times (once to select, once per pass). At Verilog file sizes
that is microseconds, and sharing a tree between the select and the first
pass would couple two things that are currently independent.
## Handshakes
**Consumed from `vlog_parser`:** `parse_source`, `LineIndex::line_col`,
`Item`/`Meta`/`Comment` spans, and the `Module` / `ItemKind::Package` shapes.
Nothing in `crates/vlog_parser` was changed and nothing new is asked of it.
**Consumed from `crate::fence`:** `collect`, `region_at`, `Region`, and two
helpers that became `pub(crate)` for this round — `line_start` and
`with_trailing_comments`. Both were already the right answer to "where does
this unit's line begin" and "how far does the comment after it reach"; a
second copy would be a second thing to keep in sync. **This is the only change
to `fence.rs`: two `fn` → `pub(crate) fn`, no behavior.**
**Promised to `vlog_formatter` callers:**
- `format_source` is unchanged in signature and in behavior. Verified rather
than argued: the whole-file `--stdout` output of all 578 formattable corpus
files is **byte-identical** to a binary built from the pre-change commit,
and the corpus TSV md5 matches exactly.
- New: `format_range(&str, &Config, &LineRanges) -> Result<String, FormatError>`,
and `LineRanges` (re-exported at the crate root). `range::{Selection, Plan,
Pick, Split, select, plan}` are public for the same reason `fence`'s are —
one definition of the answer — but only `format_range` and `LineRanges` are
meant for outside callers.
**Promised to `crates/vfmt` and `crates/vfmt_server`:** both call
`format_range` and nothing else new. `Options::lines` and
`Options::cache_enabled` are the CLI's own.
**`verify.rs` is untouched.** `git diff --quiet` on it and on
`tests/verification.rs` both exit 0. No normalization was added, broadened or
weakened, so invariant #4's attack-test requirement does not apply — and none
was needed: a verbatim slice is source bytes, so it re-lexes to exactly the
tokens it came from, and the units it replaces are exactly the ones whose
bytes it contains.
**Recursion budget (`docs/features/recursion-limit/README.md`):** unaffected.
The planner recurses only through nested module/package scopes, a subset of
the AST depth the parser already bounds, and builds no tree. `Doc::Verbatim`
is a leaf, as it was for fences.
## Status / TODO
- [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and
zero refused, past-EOF clamped) with unit tests for every spelling.
- [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in
both modes (from lines, and replaying picks), run merging, region
normalization.
- [x] `format.rs`: `format_range`, `format_selected`, `render` extracted from
`format_once`; `Fmt.splits`; `split_at`/`opens_at`/`slice`;
`split_item`/`head_doc`/`tail_doc`; `module()` split into `module_head`
+ body + closing; `is_fenced` → `is_verbatim`.
- [x] `fence.rs`: `line_start` and `with_trailing_comments` → `pub(crate)`.
- [x] `tests/ranges.rs` — 22 tests: the unit rule, header/footer/body
independence, packages, the generate and statement coarseness, fences
outranking ranges, alignment-group splitting, the parse-error refusal,
blank-line and comment preservation, multi-byte, the uncuttable module,
the spec grammar, the line-shift counterexample, and a corpus spot
check.
- [x] CLI `--lines`: comma and repeated forms, `--check`/`--diff`/`--stdout`/
stdin, directory refusal, cache bypass, `vfmt check` rejection — 6 CLI
tests + 2 arg unit tests.
- [x] LSP `documentRangeFormattingProvider` + `format::range_formatting` — 6
handler tests and one e2e leg over the wire with UTF-16 content.
- [x] `tools/vfmt-changed.sh`.
- [x] README.md usage block + a Range formatting section; TODO.md §2
checkbox; the one-line `vfmt-server` README annotation.
- [ ] **Not done, deliberately:** statement-level ranges (an intersected
`always` block lays out whole).
- [ ] **Not done, deliberately:** descending into `generate` regions,
classes, functions and tasks. One `scope_of` arm plus a head/tail doc
each, whenever a real file makes it hurt.
- [ ] **Not done:** a `vfmt --diff-base <rev>` flag. `tools/vfmt-changed.sh`
covers the need from outside; putting git inside the binary is a
separate decision.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, TODO.md §2/§6, and the Handshakes of `format-fences`,
`spans`, `vfmt-server` and `alignment` before writing anything. Baseline:
`cargo test -p vlog_formatter` **113 passed**, clippy silent, fmt clean.
(`cargo test --workspace` did not build at that moment — a concurrent
`vlog_linter` round had the tree mid-edit; it was green again before the
final run below, and nothing in `vlog_linter` was touched here.)
- **Chose "a range is an inverted fence" as the implementation, not just the
metaphor.** The fence machinery already answers "these bytes are emitted as
written, and the items they cover are skipped"; the only thing it could not
do was *open* a region at an item's code rather than at a comment. Adding
`opens_at` (a region whose `fence` offset equals the item's `span.start`)
made ranges fall out of the existing splice with no second mechanism. The
alternative — a parallel "skip this item" flag on `Fmt` — would have been a
second definition of verbatim, and the fence round's lesson is that one
definition is what keeps the safety net's argument short.
- **Runs, not per-item slices, because of blank lines.** The first sketch
emitted each unselected item as its own `Doc::Verbatim`. It passed
equivalence and looked right until a file with two blank lines between two
untouched declarations came back with one: the *separator between* the
slices is the formatter's, and it normalizes. Merging consecutive verbatim
units into one slice puts those bytes inside the slice, where nothing can
reach them. The residual — a boundary between a laid-out item and a run
still normalizes its one gap — is documented rather than chased, because it
is the same rule a fence boundary follows.
- **Descending: modules and packages only.** The brief's granularity call, and
the right one; the honest scope line is that a `generate` region is atomic,
which is documented in three places rather than hidden. Head and tail
extents are computed from the *scope*, not from the item kind — the header
ends at the last non-whitespace byte before the first body unit's line, the
footer starts at the `endmodule` line — so adding a kind later is one match
arm plus a head/tail doc.
- **`module()` was split into `module_head` + body + closing** so a split item
can lay out the header while the body stays verbatim. Pure extraction: the
`Doc` sequence is the same list, built in two functions instead of one, and
the zero churn on the `.cases` table is the evidence.
- **The convergence check was the real design problem, and the first two
answers were wrong.** Re-running with the same *line* ranges is not
well-defined (lines move); re-running with *no* ranges is not a fixed point
by construction (that is the feature). The answer that works is to record
the per-item decisions and replay them, which is sound precisely because
equivalence has already proved the two texts have the same token stream —
the check upstream is what makes the check downstream meaningful. Two
consequences fell out of that and are now invariants: the pick list is
indexed by a depth-first walk whose shape depends only on the item tree, and
the body of a module is therefore walked even when it cannot be split.
- **A construction bug the safety net caught, exactly as designed.** The
split's "where does the body end" used the last *item* and ignored the
scope's dangling comments, so a module ending in `// note` before
`endmodule` emitted that comment twice — once in the run, once in the tail
slice. `verify_equivalence` rejected it on the first probe with a token
index and both spellings. Fixed by taking the dangling comments' end when
there are any.
- **Two findings from the corpus, both kept as documentation rather than
papered over.** (a) The `on` fence is the next item's leading comment, so
selecting the `on` line selects that item — my first test asserted "nothing
changes" and the code was right. (b) A same-line-range second run can reach
further when the first run moved a line; measured at 449 of 8236 trials, all
settling on that second run. The runtime replay is unaffected by either.
- **`--lines` bypasses the cache** for two independent reasons, both written
at the `cache_enabled` call site: a hit skips the very lines the caller
named, and a miss would record a partial format under the "already
formatted" verdict the cache exists to promise.
- **The LSP handler converts only line numbers**, which is the cheapest
correct answer to the UTF-16 question: the columns are thrown away, so
there is nothing to get wrong. The one rule that needed a test is the
end-at-character-0 case every editor sends.
- Did not touch `verify.rs`, `vlog_parser`, `vlog_semantic`, `vlog_linter`
(a concurrent round owns it), `corpus/`, or the `.cases` tables. Did not run
`git commit`/`git push`.
**Results.**
- `cargo test --workspace`: **768 passed, 0 failed** (a moving number — the
concurrent `vlog_linter` round is landing tests in the same tree; it read
767 an hour earlier). This feature's own crates: `vlog_formatter` 113 →
**141** (+6 unit tests in `range.rs`, +22 in `tests/ranges.rs`), `vfmt`
91 → **99** (+2 arg unit tests, +6 CLI tests), `vfmt_server` 114 → **121**
(+6 handler tests, +1 e2e).
- `cargo clippy --workspace --all-targets`: silent, 0 warnings.
`cargo fmt --all --check`: clean.
- **No default-behavior change, verified two ways.** `tools/corpus_check.sh
corpus` gives TSV md5 `b74f2f167c57e381d46f3503363a79b3` — byte-identical
to a run of a binary built from a `git worktree` at the pre-change commit
(003e076); 820 files, 578 formattable (70.5 %), 10 ok-unchanged, 568
would-reformat, 242 parse-error, **0 verification errors, 0 crashes**. And
the whole-file `--stdout` output of all **578** formattable corpus files is
**byte-identical** between the two binaries (0 differing). The worktree was
removed afterwards.
- **Range sweep over the corpus**: every formattable file, ~12 evenly spread
3-line ranges each — **578 files, 8236 trials, 0 refusals**, i.e. range
formatting never refuses a file the whole-file formatter accepts, and the
safety net (equivalence + replayed convergence) passed on every one. 449
trials (5.5 %) were not a fixed point under the same *line numbers*; all 449
settled on the next run. The sweep harness was a scratch test, not checked
in; `tests/ranges.rs`'s corpus spot check is the committed version.
Files added: `crates/vlog_formatter/src/range.rs`,
`crates/vlog_formatter/tests/ranges.rs`, `tools/vfmt-changed.sh`, this README.
Files edited: `crates/vlog_formatter/src/{lib,format,fence}.rs`,
`crates/vfmt/src/{args,main}.rs`, `crates/vfmt/tests/cli.rs`,
`crates/vfmt_server/src/{main,server,format}.rs`,
`crates/vfmt_server/tests/e2e.rs`, `README.md`, `TODO.md`,
`docs/features/vfmt-server/README.md` (the deferred-capability annotation).
## QA log
### 2026-08-19 — QA agent
Read `CLAUDE.md`, this README, `range.rs`, the `format.rs`/`fence.rs`/`lib.rs`
diffs, `tests/ranges.rs`, the `vfmt`/`vfmt_server` diffs, and
`tools/vfmt-changed.sh` before touching anything. Verified by (a) rebuilding
and re-running the gates myself, (b) an independent binary-diff of the
no-default-change claim, (c) hand-written probe files against the real
release binaries (not just re-running the shipped test suite), and (d) one
deliberate sabotage of the convergence mechanism to confirm the safety net is
load-bearing rather than decorative. No BLOCKING findings. No file outside
this README's QA log was left modified (the sabotage below was applied and
reverted in the same sitting; diffed byte-for-byte against the pre-sabotage
`git diff` to confirm).
**Gates — pass.** `cargo build --release` clean. `cargo test --workspace
--release`: **768 passed, 0 failed** across 27 test binaries — recomputed by
hand from the per-binary counts, matches the dev's snapshot exactly.
`cargo clippy --workspace --all-targets --release`: silent. `cargo fmt --all
--check`: clean. `git diff --quiet` on `verify.rs` and
`tests/verification.rs`: both exit 0 (untouched, confirmed independently of
the dev's claim). `git status --porcelain -- '*.cases'`: no `.cases` churn.
`fence.rs`'s diff is exactly the two claimed `fn` → `pub(crate) fn` lines,
nothing else — read the whole diff, not just the summary.
**No default-behavior change — pass, verified independently, not just
re-run.** `tools/corpus_check.sh corpus` here: TSV md5
`b74f2f167c57e381d46f3503363a79b3`, byte-for-byte the value in the Work log.
Then, independently of the dev's worktree (which was already removed):
created my own `git worktree` at `003e076`, built its `vfmt --release`, and
compared `--stdout` output against the current binary over all 578
formattable corpus files (from the TSV's `ok-unchanged`/`would-reformat`
rows) — 0 differing via a `$()`-capture pass over all 578, then a second,
byte-exact `cmp` pass on a 20-file stride subset (every 29th file). Both
clean. Worktree removed after.
**Semantics (claim 1) — pass.** Hand probes against `target/release/vfmt`,
not just re-running `tests/ranges.rs`:
- Unit rule: a range on only a leading comment lays out the whole unit
(comment + declaration), sibling untouched — matches the doc's "selecting a
doc comment selects the declaration under it."
- Module split independence, probed three ways on one file: header-only range
leaves a **mis-indented** body byte-identical (checked as a substring, not
a line-diff, since the header's line count itself changes — `p2.sv` in the
scratchpad); a range on `endmodule` alone leaves header and body untouched;
two ranges (items 1 and 3) around a misformatted item 2 leave item 2 and
the blank lines around it byte-identical.
- Run merging: confirmed the bug class the doc says this prevents is real —
a CRLF probe (`p7b.sv`) with two consecutive *unselected* items merged into
one run showed the `\r` **between** them surviving (interior byte of the
run) while every `\r` at a unit **boundary** (header/body, run/tail, EOF)
was stripped, exactly per "Line terminators the formatter writes are `\n`."
This is the sharpest confirmation available short of literally reverting
the run-merge and watching a blank-line count change.
- Blank-line selection: `--lines` on a pure blank line is a no-op (confirmed
via CLI, matches `tests/ranges.rs`).
- Uncuttable module: `module m; wire a; endmodule` on one line lays out
whole, not partially — confirmed via CLI, matches the shipped test.
**Interactions (claim 2) — pass.**
- Fence wins: `--lines` on lines fully inside a `// vfmt: off` region leaves
the region untouched; the on-fence-line quirk (selecting the `on` line
selects the *next* item, not the region) reproduced independently.
- Alignment split: `ALIGNED`-shaped probe with lines 2-3 selected — the two
selected `localparam`s align to their own column, the third (unselected)
keeps its original spacing byte-for-byte; a lone selected member formats
flush with no padding. Matches the doc's worked example exactly.
- Unparseable file: `--lines 1` on a file broken at line 3 still exits 2 and
leaves the file untouched, even though line 1 never touches the break.
- Reversed/zero/junk ranges (`5-1`, `0`, `0-3`, `x`, `1-2-3`, empty spec) all
exit 2 with the file untouched, checked by diffing the file after each
attempt — confirms the parse happens before any file is opened.
- Past-EOF (`900-1000` on a 3-line file): exits 0, "1 file left unchanged",
file untouched — clamps rather than errors, as documented.
**Convergence (claim 3) — pass, and load-bearing (see sabotage below).**
- Same-selection replay inside one `format_range` call is the promised fixed
point; re-running `--lines` on the *same* ranges after a run that did not
move the selected lines is a no-op (`--check` exits 0) in every probe,
including a CRLF file and an alignment-group probe.
- The honest limit reproduced deliberately: a probe port-list header written
over 5 lines, `--lines 1-6`, shrinks to 1 line but the range (1-6) still
covers the whole shrunk output, so the *next* CLI run is still a fixed
point (no sweep, because the shrink didn't cross the range's own boundary).
Separately, re-derived the exact `a_line_shift_can_sweep_in_the_next_construct`
scenario by hand (a 3-line header that becomes 1 line, selected via
`--lines 1-3`) and confirmed the second run sweeps in the body item, and a
third run settles — matching the doc's 449/8236 finding's description of
the shape of the effect, not just trusting the number.
**CLI/cache/LSP (claim 4) — pass.**
- `--lines` forms (comma, repeated), `--check`/`--diff` combination (diff
patch applied cleanly with `patch` against a copy and matched the actual
`--lines` output byte-for-byte), stdin, directory refusal (exit 2, correct
message, file untouched), `vfmt check --lines` rejection (exit 2) — all
reproduced directly against the binary, not just by reading `cli.rs`.
- `--lines` bypasses the cache in both directions: verified via `cli.rs`'s
own test (already covers "warm cache, `--lines` run still does the work,
and writes nothing"); did not re-derive this one independently beyond
reading it, since it is a single boolean at one call site
(`args.rs::cache_enabled`) and the existing test already exercises both
the hit-skip and the no-write cases.
- LSP: drove the **real** `vfmt-server` release binary over stdio with a
hand-rolled Content-Length framer (independent of `e2e.rs`'s harness) —
`initialize` advertises `documentRangeFormattingProvider: true`; a range
mid-module (line 3 of a 3-item module) returns one whole-document
`TextEdit` containing only that line reformatted; a range on an
already-clean line returns `"result": []` (empty, no edit). Matches the
doc's "reply absent/empty when nothing changes" and "one whole-document
edit" claims. `cargo test -p vfmt_server` (part of the workspace run
above) is green, e2e included.
- Did not independently re-derive the end-at-character-0 UTF-16 conversion
math beyond reading `format.rs::range_formatting` and its unit tests
(`crates/vfmt_server/src/format.rs:80-90`) — the logic is a two-line `if`
with four unit tests covering exactly the boundary cases the doc names
(cursor-only, "select two lines" ending at char 0, single line via the same
rule, and a multi-byte line proving only line numbers survive the
conversion); re-tracing it by hand against each test agreed with both.
**vfmt-changed.sh — pass.** Scratch git repo, two files, three edited lines
(one in `a.sv`, two in `b.sv`): only the touched declarations moved, module
headers and untouched siblings stayed exactly as written. A deletion-only
hunk (`sed -i '' '3d'`, no added lines) was skipped entirely — file
untouched, confirmed by diff. `--check` pass-through: exit 1 when the
touched hunk would still reformat, exit 0 once clean, exit 2 when
`$VFMT` points at a nonexistent binary (the script's own guard, not vfmt's
exit code, but still the documented "2 = error" contract).
**Sabotage (required by CLAUDE.md invariant #4's spirit, even though this
round added no new normalization) — the replay is load-bearing.** Edited
`format_range` in `crates/vlog_formatter/src/format.rs` to re-derive the
second-pass selection with `range::select(&output, &sabotage_file, lines)`
(the caller's original line numbers, re-applied to the reparsed *output*)
instead of replaying `selection.picks` — i.e., exactly the "re-derive from
line numbers on pass 2" bug the Work log's convergence section describes as
the wrong answer. Rebuilt and ran `cargo test -p vlog_formatter --release`:
**2 failures**, both in `tests/ranges.rs`:
- `a_line_shift_can_sweep_in_the_next_construct` panicked inside
`format_range` itself: `Verification(NotConverged { line: 2, first: " wire
x;", second: " wire x;" })` (bytes verbatim: pass one's output kept
`wire x;`, the sabotaged replay reformatted it to `wire x;`) — the exact
mechanism the doc predicts:
lines 1-3 select only the header on pass one, but after the header
collapses to one line, the same line numbers reach into the body on the
sabotaged pass two, and the two passes disagree.
- `a_corpus_spot_check_touches_only_the_top_of_the_file` also failed, on a
real file (`corpus/picorv32/testbench_wb.v`): "formatting is not
idempotent; line 5 changed from `\treg clk = 1;` to ` reg clk = 1;`" —
confirms the bug is not a contrived-input artifact, it fires on real RTL
too.
Reverted the edit (`git diff crates/vlog_formatter/src/format.rs` back to
exactly the pre-sabotage diff, confirmed with a byte diff of the saved
pre-sabotage patch against the post-revert patch, plus `grep -n sabotage`
returning nothing). Rebuilt; `cargo test -p vlog_formatter --release`: 78
passed, 0 failed, back to clean. Re-ran the full workspace gate afterward
(build/test/clippy/fmt) to confirm the revert didn't leave the tree in a
different state than before I started — all four clean, 768/0 again.
**Conclusion:** every claim in the brief holds, verified independently
rather than by re-trusting the dev's numbers where an independent check was
feasible in the time available. No BLOCKING findings (no non-convergence
under a *held* selection, no bytes changed outside a selected unit, no
default-behavior change). The one substantive risk this feature carries —
that convergence could silently degrade if a future edit "simplified" the
replay back into a line-number re-derivation — has a sharp, fast-failing
regression signal: the sabotage above took under a minute to both introduce
and get caught by the existing `tests/ranges.rs` suite, with no new test
needed.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 18. The
legacy-codebase adoption story is complete: edit three lines of a
2000-line module and only three lines move — in the CLI, via git, and
in the editor.**
Points reviewed and accepted:
1. **Selection replay is the design contribution**: convergence over
line-addressed partial formatting is unsound by construction (lines
move), and replaying the per-item Selection — justified by the
equivalence check having already proven token identity — turns it
sound. QA's sabotage replaced replay with re-derivation and got
immediate NotConverged failures including on real RTL: the
mechanism is load-bearing, not decorative.
2. **The honest limit is measured and pinned**, not hidden: same LINE
NUMBERS can sweep in a neighbor when the first run moved lines
(449/8236 corpus trials, all settled next run), with a committed
counterexample test. Users of vfmt-changed.sh get self-stabilizing
behavior; the docs say why.
3. **Run-merged verbatim slices** — found by a probe, not reasoning —
is the kind of bug (separator-collapsed blank lines between
untouched items) that only surfaces when you treat "untouched"
as a byte-level promise. The head/body/tail module split with
independent decisions is the right granularity for the use case,
and one `scope_of` arm from going deeper when someone needs it.
4. **Every interaction decided and probed**: fence wins; alignment
groups split at verbatim boundaries; cache fully bypassed (a
partial format is not the cached clean verdict); unparseable files
still refuse; the LSP handler sidesteps UTF-16 columns entirely by
consuming only lines. Default behavior provably unchanged two ways
(TSV md5 + all-578 whole-file byte-compare against a pre-round
binary, re-derived independently by QA).
With this, the owner's full directive is delivered. What remains on
the backlog is the corpus-nominated queues/dynamic-arrays parse round
(41 files), the parked §4 linter items, and the LSP-side class
navigation gap — all documented where they live.
+5 -1
View File
@@ -28,7 +28,11 @@ behavior is unchanged byte for byte; the server gains the CLI's
- **Protecting more than the formatter emits verbatim is the harmless
direction.** The scan has no notion of scope and would be fooled by a fence
spelled inside a block comment; both only ever decline an edit, which costs
a fix, not correctness.
a fix, not correctness. (Lead note, per lint-rules-2 QA: a concrete
example of that width — the formatter's `collect` does not yet fire inside
class bodies, the classes round's filed gap, but the scan backstop does, so
a fence inside a class body protects `--fix` and server quick fixes even
though `vfmt format` ignores it there.)
- **`protected_regions` takes `&str` and parses internally, on purpose.** The
alternative — accepting a caller's `SourceFile` — would let the two front
ends feed different trees and get different answers, which is the drift this
+12 -4
View File
@@ -17,6 +17,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| LSP request | Engine it consumes | Notes |
|---|---|---|
| `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed |
| `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex` | Macro body, or declaration kind + snippet |
@@ -25,8 +26,11 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
Deferred, deliberately, and named in Status/TODO below: range formatting
(waits on TODO.md §2 `--lines`), ~~lint diagnostics (waits on `vlog_linter`)~~
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
`documentRangeFormattingProvider` is advertised and the handler converts the
UTF-16 `Range` to 1-based lines — see
`docs/features/range-formatting/README.md`**, ~~lint diagnostics (waits on `vlog_linter`)~~
**delivered by server-lint (round 13): lint findings publish as warnings in the
same notification as the parse errors, and `textDocument/codeAction` offers
their Safe fixes — see `docs/features/server-lint/README.md`**,
@@ -368,9 +372,13 @@ it was written rather than starting mid-line.
- [x] One end-to-end smoke test that spawns the built binary and speaks
framed JSON-RPC.
- [x] TODO.md §6 `vfmt_server` checkbox, annotated with what shipped.
- [ ] **Not done, deliberately:** `rangeFormatting`. It reuses TODO.md §2's
- [x] ~~**Not done, deliberately:** `rangeFormatting`. It reuses TODO.md §2's
`--lines`, which does not exist yet; advertising the capability before
the engine does is how an editor learns to distrust a server.
the engine does is how an editor learns to distrust a server.~~
Delivered by **range-formatting** (round 18): `--lines` exists, so the
capability is advertised and `format::range_formatting` serves it on the
same all-or-nothing contract as the whole-document request.
`docs/features/range-formatting/README.md`.
- [x] ~~**Not done:** lint diagnostics.~~ Delivered by **server-lint**
(round 13): the publisher gained the second source — in
the *same* notification, since LSP replaces rather than merges — plus
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Format only the lines a git diff touched — vfmt's answer to Verible's
# `git-verible-verilog-format.sh`.
#
# This is what makes vfmt adoptable in a dirty legacy tree: your patch comes
# out formatted, and not one byte outside it moves, so review sees the change
# you made rather than a reflow of the whole file.
#
# Usage: tools/vfmt-changed.sh [--check|--diff] [<rev>] [-- <pathspec>...]
#
# <rev> what to diff against; default: unstaged+staged work, i.e. HEAD.
# `tools/vfmt-changed.sh origin/main` formats a whole branch.
# --check / --diff are passed through to vfmt, so this works in CI.
#
# Exit status is vfmt's, per the frozen contract: 0 nothing to do, 1
# --check/--diff found changes, 2 an error (that file was left untouched).
#
# Only *added* lines are formatted: `git diff -U0` hunk headers give
# `@@ -old +first,count @@`, and a `count` of 0 means the hunk only deleted,
# so there is nothing on the new side to format.
set -eu
vfmt=${VFMT:-target/release/vfmt}
mode=""
rev="HEAD"
have_rev=0
while [ $# -gt 0 ]; do
case $1 in
--check|--diff) mode=$1; shift ;;
--) shift; break ;;
-*) echo "usage: $0 [--check|--diff] [<rev>] [-- <pathspec>...]" >&2; exit 2 ;;
*) rev=$1; have_rev=1; shift ;;
esac
done
[ "$have_rev" = 1 ] || rev=HEAD
command -v "$vfmt" >/dev/null 2>&1 || [ -x "$vfmt" ] || {
echo "no vfmt binary at $vfmt (cargo build --release? or set VFMT=)" >&2
exit 2
}
status=0
files=$(git diff --name-only --diff-filter=d "$rev" -- "$@" \
| grep -E '\.(sv|svh|v|vh)$' || true)
[ -n "$files" ] || exit 0
for file in $files; do
# `first,count` from every hunk header, as `first-last`, comma-joined.
ranges=$(git diff -U0 "$rev" -- "$file" \
| sed -n 's/^@@ -[0-9,]* +\([0-9]*\)\(,\([0-9]*\)\)\{0,1\} @@.*/\1 \3/p' \
| awk '{ count = ($2 == "" ? 1 : $2); if (count > 0) printf "%s%d-%d", sep, $1, $1 + count - 1; sep = "," }')
[ -n "$ranges" ] || continue
# shellcheck disable=SC2086 # $mode is one optional flag, deliberately split.
"$vfmt" $mode --lines "$ranges" "$file" || status=$?
done
exit $status