Compare commits

...
3 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 63bbc23e37 Release 0.35.0 — format fences at statement level and inside class bodies
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m16s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:46:24 -07:00
lucioandClaude Fable 5 a0ae5e5fa8 Format fences at statement level and inside class bodies
TODO section 31 (coverage_gaps M9, docs/topo.md 2.9-3).
fence::collect enters class bodies, functions, tasks and always/
initial/final blocks, and statement lists - begin/end, fork/join and
every compound body - through scan_stmt_scope/scan_nested_stmt on the
one scan_units both scope kinds share; stmt_docs/stmt_seq obey the two
swallowed-unit rules item_docs/item_seq had; fence regions merge into
range.rs's plan, which was load-bearing (a fenced statement has no
verbatim run behind it; proved by disabling it). A region opens only at
a line start (opens_line) - the rule the format-fences README has
stated since round 1 - so a fence after code on the same line is an
ordinary comment everywhere, which narrows one accidental item-level
shape (module m; // lucisv: off) and is ruled a drift fix. Deferred
with reasons: port lists, case-item label lists, same-line fences, a
property's locals. verify.rs, lucisv/src/lint.rs and
lucisv_server/src/lint.rs untouched.
Proof: 3 244 tests / 48 binaries, fences.cases 25 -> 38 with the
statement-level entry inverted, corpus 814/820 and 860 files byte-
identical to 0.34.0, opentitan: 4 of its 9 fenced files now keep their
fenced bytes and are fixed points, --check counts identical; 3 348
fence-injection trials with no new refusals.

docs/features/statement-fences/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:40:12 -07:00
lucioandClaude Fable 5 965c4ee25a TODO §33/§34 planned: linter expansion — severities, per-rule VS Code toggles, Error/Warning-class rules (wave 1); the Style class and per-rule options (wave 2)
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:57:31 -07:00
20 changed files with 1641 additions and 101 deletions

No files matched your search

+24
View File
@@ -4,6 +4,30 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
`// verilog_format: off` / `// lucisv: off` (and the `lucisv:` spelling)
now protect statements inside `begin … end`, `fork … join`, function
and task bodies and `always`/`initial`/`final` blocks, and items inside
a class body — not only items at module scope. A fenced region is
copied byte for byte, keeps its own indentation, and is a fixed point
under a second pass; an unmatched `off` runs to the end of its own
list. `--lines` range formatting honours a fenced statement inside the
selected range. Four opentitan files that already carried fences inside
functions and class bodies now keep those bytes.
One rule is applied uniformly: a fence must start its line (whitespace
or a finished block comment may precede it). A fence written after code
on the same line — `module m; // lucisv: off` — is an ordinary comment,
as the fence documentation has said since the feature shipped; it used
to open a region at module scope by accident.
Not yet fenceable, with reasons in the feature README: port lists,
case-item label lists, same-line fences, and a property's local
declarations.
## 0.34.0 — 2026-09-02
### Rename tells you what it could not reach
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.34.0"
version = "0.35.0"
[[package]]
name = "lucisv_server"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.34.0"
version = "0.35.0"
[[package]]
name = "vlog_refactor"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.34.0"
version = "0.35.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.34.0"
version = "0.35.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+26 -8
View File
@@ -302,8 +302,8 @@ both layouts are fixed points of re-formatting:
### Turning the formatter off
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
Everything between a `// verilog_format: off` and a `// verilog_format: on`
comment is emitted as the exact source bytes it was written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
@@ -317,12 +317,30 @@ module m;
endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
A fence works between **items** — module, package and class members, and
top-level items — and between **statements**: inside `begin`…`end`,
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
```systemverilog
class scoreboard;
function void build_phase();
// verilog_format: off
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
cfg.agent_cfg); // hand-wrapped, left alone
// verilog_format: on
endfunction
endclass
```
The fence must be a line comment that begins its own line, and its text must
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
and so is one written after code on the same line (`wire a; // lucisv: off`,
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
enclosing list and no further: the module body, the class body, the
`begin`…`end`, the function body, or the file. A fence inside a port list, a
parameter list or a `case` **label** list is still an ordinary comment. Full
rules: `docs/features/format-fences/README.md` and
`docs/features/statement-fences/README.md`.
### Range formatting (`--lines`)
+211 -7
View File
@@ -3314,14 +3314,21 @@ READMEs, README.md "Turning the formatter off", docs/topo.md §2.9-3
struck (lead), TODO §31. Runs after §29/§30 merge (format/ collides
with §30's routine.rs only at merge; disjoint files otherwise — the
lead may start it in parallel if §30's files are settled).
- [ ] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3
- [ ] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check
- [ ] 31.3 docs rewritten (format-fences README, README.md, the
- [x] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3 —
`Interface`/`Program` are `ItemKind::Module` and were already scanned,
there is no `Checker` node, and `PropSeqDecl.locals` is deferred (it is
the one `Vec<Item>` not printed through `item_seq`)
- [x] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check — the
planner now merges `collect`'s fences into `Plan.regions`, without
which `--lines` would have reformatted a fenced statement
- [x] 31.3 docs rewritten (format-fences README, README.md, the
inverted case), deferrals listed with reasons
- [ ] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical; opentitan fence census + sweep
- [x] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [x] Gates: fmt/clippy/`cargo test --workspace` 3 244/0/42 (was
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
keeping its own fenced bytes, `--check` counts unchanged
- [ ] QA: fences in every statement scope listed and in the three
deferred places (must be inert, never corrupt); an `off` with no
`on` in each scope (runs to the scope end only); nested fences;
@@ -3468,3 +3475,200 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
an opentitan file and read the published diagnostics and the
outline; the fuzzers re-run; strict-mode parity re-derived
## 33. Linter expansion, wave 1 (planned 2026-09-02) — severities, per-rule editor toggles, and the Error/Warning-class rules
Owner's ask: expand the linter toward what Verible's linter covers (62
rules, https://chipsalliance.github.io/verible/lint.html), expose every
rule in VS Code as a toggle grouped by severity so a user can enable or
disable rules one at a time or a whole severity at once, and put the
style rules and the "would likely fail to compile or synthesize" rules
first. Today: 17 rules, no severity notion (`Rule` has `name`,
`summary`, `doc`, `default_on`, `needs_workspace`, `fix`, `check`), every
editor diagnostic is `WARNING`, the editor surface is
`lucisv.lint.select`/`ignore` lists. Dev Opus 5, QA Sonnet 5. Feature
README: `docs/features/linter-expansion-1/README.md`. Runs in a
worktree in parallel with §31 (fences: `vlog_formatter`, README.md's
"Turning the formatter off" section only); this lane owns
`vlog_linter`, `lucisv/src/lint.rs` + args, `lucisv_server/src/
{settings,lint}.rs`, `editors/vscode/{package.json,README.md}`, README.md's
"Linting" section, `docs/site/.../reference/rules.md`.
**33.0 Severity, end to end.**
(a) `vlog_linter`: `pub enum Severity { Error, Warning, Style }` with
`as_str` (`error`/`warning`/`style`) and `Rule::severity(&self) ->
Severity` (no default — every rule states it; the reason goes in the
rule's `doc`). Assignments for the 17: **Error** — `multiply-driven`
(two procedural drivers of one variable is an elaboration error in
SystemVerilog), `wire-reg-mixup` (a procedural assignment to a net is a
compile error); **Warning** — `always-comb-blocking`,
`always-ff-non-blocking`, `case-missing-default`, `undriven-net`,
`unused-signal`; **Style** — `empty-item`, `enum-name-style`,
`explicit-parameter-storage-type`, `module-filename`,
`module-name-style`, `no-tabs`, `no-trailing-whitespace`,
`parameter-name-style`, `struct-union-name-style`, `unused-waiver`.
`Violation` carries the severity (set by the runner from the rule, not
by each rule). (b) `select_rules(select, ignore, …)` accepts a severity
name wherever a rule name is accepted — `--select style`, `--ignore
warning`, `[lint] ignore = ["style"]` — expanding to every rule of that
severity; an unknown name still fails naming the file. (c) CLI text
output becomes `FILE:LINE:COL: error|warning|style: message [rule]`
(the severity word is new; pin the old tests to the new shape); JSON
gains `"severity"`. Exit codes unchanged. (d) Editor:
`DiagnosticSeverity::ERROR` / `WARNING` / `INFORMATION` respectively;
`source` unchanged. (e) `--rules-doc` and `rules_markdown()`: a
Severity column, sections grouped by severity, the intro explaining the
three words.
**33.1 Editor toggles, generated from the registry.** In
`editors/vscode/package.json`: three master switches
`lucisv.lint.severity.error`, `.warning`, `.style` (boolean, default
true, `order` 10/11/12, description naming what each class means), and
one boolean per rule `lucisv.lint.rules.<rule-name>` (default = the
rule's default; `markdownDescription` = `**severity** — summary`; the
project-only rules say "on where lucisv can see the project"; `order`
sorted by severity then name so the Settings UI groups them; the
existing `lucisv.lint.select`/`ignore` stay, documented as the
power-user spelling). Generated, not hand-written: a
`crates/vlog_linter/examples/vscode_lint_settings.rs` (or a `tools/`
script driving `cargo run --example`) that prints the JSON fragment,
and a `crates/lucisv_server` test that parses package.json and asserts
the `lucisv.lint.rules.*` set, defaults and descriptions equal the
registry — the drift guard, so a new rule cannot ship without its
toggle. The server (`settings.rs`) reads all of them; the enabled set
is computed in one documented function `enabled_rules(settings,
has_oracle)` with this precedence, top to bottom: (1) the base set is
the defaults (`default_on`, and `needs_workspace` rules only with an
oracle); (2) a non-empty `select` replaces the base set; (3) a severity
switch that is off removes every rule of that severity; (4) an
explicitly set per-rule toggle sets or clears that rule; (5) `ignore`
removes — the off switch of last resort. Pinned by a table test.
Changing any of them republishes every open file, as select/ignore do.
The CLI has parity through select/ignore with severity names; no
per-rule flags (`--ignore rule` is that).
**33.2 New rules, Error class** (each a file under `rules/`, its own
tests, its doc with the Verible name where one exists, and a measured
false-positive count on opentitan — see QA):
- `mismatched-labels` (Verible, off there; **on** here, Error): an end
label that does not match its block's name (`end : wrong`, `endmodule
: other`) — a compile error. Reuse what linked-editing already pairs.
- `duplicate-declaration` (Error): the same name declared twice in one
scope (port and signal, two signals, two params). Ask the binder:
`Binder::declare` sees the second declaration — record it (a
`Semantics` query `duplicates()` or a per-scope check), skip generate
scopes and macro-expanded text; no false positive on `input clk`
+ `logic clk` non-ANSI redeclaration (legal) — pin it.
- `undeclared-identifier` (Error, `needs_workspace`): a use the file
did not resolve and the workspace overlay left `StillUnresolved`/
`NotFound`, excluding: names inside macro invocations, system names,
names a `` `define`` in scope produces, names the file's macro-word
census contains, hierarchical tails, names in a package this file
wildcard-imports when that package is not indexed. Measured on
opentitan; ships default-on only if the count of unexplained
findings on that tree is 0 — otherwise default-off with the
measurement and the reason in the doc.
- `unknown-port` and `unknown-parameter` (Error, `needs_workspace`): a
named connection `.x(…)` / override `.P(…)` naming a port or
parameter the instantiated module does not declare (the index
exports both). Silent when the module is not indexed or is declared
twice with different shapes.
**33.3 New rules, Warning class** (Verible name, default there → here):
- `forbid-defparam` (on → on): `defparam` is deprecated and rejected by
some tools.
- `invalid-system-task-function` (on → on): `$psprintf`, `$random`
(use `$urandom`), `$dist_*`, `$srandom` … Verible's list, cited.
- `truncated-numeric-literal` (on → on): a sized literal whose value
does not fit its width (`4'hFFF`).
- `undersized-binary-literal` (on → on, safe fix pads): `8'b1`; binary
only by default, as Verible.
- `suspicious-semicolon` (off → **on**): `if (x);`, `for (…);`,
`while (…);` — a body that is a null statement.
- `packed-dimensions-range-ordering` (on → on): a packed dimension
written `[0:N-1]`.
- `module-port` and `module-parameter` (on → on): positional
connections/overrides when more than one port/parameter.
- `explicit-function-task-parameter-type` (on → on): an untyped tf
argument is a 1-bit `logic` — a silent truncation.
- `plusarg-assignment` (on → on): `$value$plusargs` result unused /
`$test$plusargs` misuse, as Verible defines it.
- `instance-shadowing` (off → **on**): a declaration shadowing one in
an enclosing scope of the same unit (the binder knows).
- `forbid-negative-array-dim` (off → on): a negative literal in a
dimension.
- `void-cast` (on → on): `void'(…)` around anything but a function
call that has a return value (Verible's rule).
- `incomplete-assignment` (no Verible equivalent; Warning): in an
`always_comb`, a variable assigned in the `then` branch of an `if`
with no `else` (or in some `case` items, not `default`) and not
assigned unconditionally earlier in the block — latch inference.
Conservative by construction: only flag when the block has no
unconditional assignment to that variable before the `if`/`case`;
measured on opentitan.
**33.4 Docs and measurement.** README.md "Linting" (severities, the
toggles, select/ignore with severity names), `editors/vscode/README.md`
settings table, the docs-site rules page (hand-written prose today —
add the new rules with their severity and a note that `--rules-doc` is
the generated truth), CHANGELOG untouched (the lead writes it). For
every new rule: findings on the corpus and on opentitan `hw/`
(read-only `lucisv check`), with ten findings read and classified per
rule (true / false positive / needs judgment); opentitan is lint-clean
under Verible, so a Verible-equivalent rule that fires there needs an
explanation (their config disables it, or our reading differs — say
which). Timing: `lucisv check` over opentitan before/after (the
semantic rules already dominate; the new ones must not add more than a
few percent).
Files: crates/vlog_linter/src/{registry.rs, rule_docs.rs, violation.rs,
lib.rs, rules/mod.rs, rules/<new>.rs, context.rs (if a semantics query
is needed), visit.rs (new walkers)} + tests/cases/*.lint,
crates/vlog_linter/examples/vscode_lint_settings.rs (new),
crates/vlog_semantic (only if `duplicates()`/shadowing needs a query —
additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
+ tests, crates/lucisv_server/src/{settings.rs, lint.rs} + tests,
editors/vscode/{package.json, README.md}, README.md "Linting",
docs/site/src/content/docs/reference/rules.md, docs/features/
linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
- [ ] 33.0 `Severity` on every rule; select/ignore by severity; CLI
text/JSON; editor severities; `--rules-doc` grouped
- [ ] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [ ] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [ ] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [ ] 33.4 docs; measurements table in the README
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (formatter untouched); opentitan read-only
`lucisv check` census + timing
- [ ] QA: every new rule attacked with hand-written true positives and
near-misses; the false-positive census re-read; toggles exercised
through the real server (`workspace/didChangeConfiguration`)
## 34. Linter expansion, wave 2 (planned 2026-09-02, after §33) — the Style class and per-rule options
The style family from Verible, with the per-rule configuration the
naming rules need: `signal-name-style`, `interface-name-style`,
`macro-name-style`, `constraint-name-style`, `parameter-type-name-style`,
`dff-name-style`, `port-name-suffix`, `banned-declared-name-patterns`
(each with a `pattern`/style option), `line-length` (reads the
formatter's `line-length`), `posix-eof` (safe fix), `endif-comment`,
`forbid-line-continuations`, `one-module-per-file`, `package-filename`,
`typedef-enums`, `typedef-structs-unions`, `module-begin-block`,
`generate-label` + `generate-label-prefix`, `always-comb` (`@*` →
`always_comb`, safe fix), `legacy-generate-region`,
`legacy-genvar-declaration`, `v2001-generate-begin`,
`explicit-function-lifetime`/`explicit-task-lifetime`,
`positive-meaning-parameter-name`, `suggest-parentheses`,
`forbid-consecutive-null-statements`, `unpacked-dimensions-range-
ordering`, `uvm-macro-semicolon`, `create-object-name-match`,
`numeric-format-string-style`, `macro-string-concatenation`,
`disable-statement`, `forbidden-macro`/`forbidden-symbol` (list
options). Options: `[lint.<rule>]` tables in `lucisv.toml` (today
rejected by name — the parser exists) and `lucisv.lint.options.<rule>`
in the editor, validated against a per-rule option schema declared by
the rule (`Rule::options() -> &[OptionSpec]`), shown in `--rules-doc`.
Detailed plan to be written when §33 lands.
+153 -20
View File
@@ -3,7 +3,9 @@
//! A fenced region is emitted as the exact source bytes it was written with,
//! so nothing inside it is ever laid out. This module answers the two
//! questions that makes possible: which comments are fences, and which byte
//! ranges they select. Full spec: `docs/features/format-fences/README.md`.
//! ranges they select. Full spec: `docs/features/format-fences/README.md`,
//! plus `docs/features/statement-fences/README.md` for the class-body and
//! statement-list scopes.
//!
//! [`protected_regions`] and [`is_protected`] are the same answer for the
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
@@ -11,7 +13,10 @@
//! there is one definition of "what is fenced": see
//! `docs/features/shared-fence-filter/README.md`.
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
@@ -54,7 +59,15 @@ pub struct Region {
/// Every fenced region in `file`, sorted and non-overlapping.
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
let mut found = Vec::new();
scan_scope(src, &file.items, &file.dangling, &mut found);
match &file.fragment {
// A statement fragment is one statement list standing at file scope,
// its dangling comments ending it exactly as a file's items' do. The
// other fragment shapes are element lists, which are not fenceable.
Some(Fragment::Statements(stmts)) => {
scan_stmt_scope(src, stmts, &file.dangling, &mut found)
}
_ => scan_scope(src, &file.items, &file.dangling, &mut found),
}
found.sort_by_key(|r| r.fence);
// A region inside an already-fenced range never runs: the items holding
// it are emitted as source bytes, so they are never formatted. Dropping
@@ -146,50 +159,73 @@ fn scanned_regions(src: &str) -> Vec<Region> {
regions
}
/// Scan one item-list scope, then its nested scopes.
/// Scan one flat stream of units — each unit's leading comments, then its own
/// code extent — followed by the scope's dangling comments.
///
/// The scope is a flat stream of units — each item's leading comments, then
/// the item's own code — followed by the dangling comments. A region opens at
/// the first `off` in that stream and closes at the first `on` after it;
/// anything else, including a second `off`, is just text.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
/// A region opens at the first `off` in that stream and closes at the first
/// `on` after it; anything else, including a second `off`, is just text. An
/// item list and a statement list have exactly this shape, and it is the only
/// shape a fence pairs inside, which is why both scan through here.
fn scan_units<'u>(
src: &str,
units: impl Iterator<Item = (&'u [Comment], TextRange)>,
dangling: &[Comment],
out: &mut Vec<Region>,
) {
let mut open: Option<Region> = None;
let mut scope_end = 0usize;
for item in items {
for c in &item.meta.leading {
for (leading, span) in units {
for c in leading {
// An attribute followed by a comment puts a "leading" comment
// *after* the item's span starts. Opening a region there would
// *after* the unit's span starts. Opening a region there would
// emit the attribute twice, so such comments are not fences.
if c.span.start < item.span.start {
if c.span.start < span.start {
step(src, c, &mut open, out);
}
}
// A leading comment always ends before its item's code does, so the
// item's own end is the scope's high-water mark.
scope_end = item.span.end as usize;
// A leading comment always ends before its unit's code does, so the
// unit's own end is the scope's high-water mark.
scope_end = span.end as usize;
}
for c in dangling {
step(src, c, &mut open, out);
scope_end = c.span.end as usize;
}
if let Some(mut r) = open {
// An unmatched `off` runs to the end of the scope. The last item's
// An unmatched `off` runs to the end of the scope. The last unit's
// span stops before the comment trailing it on the same line, and
// `Meta.trailing` has no span to consult, so that comment has to be
// picked up from the source or it would be dropped.
r.end = with_trailing_comments(src, scope_end);
out.push(r);
}
}
/// Scan one item-list scope, then its nested scopes.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, items.iter().map(|i| (i.meta.leading.as_slice(), i.span)), dangling, out);
for item in items {
scan_nested(src, item, out);
}
}
/// Scan one statement-list scope, then its nested scopes.
///
/// The statement twin of [`scan_scope`], unit for unit — which is what keeps a
/// region aligned with statement boundaries and stops an unmatched `off` at the
/// list's end rather than at the `end`, `join` or `endfunction` past it.
fn scan_stmt_scope(src: &str, stmts: &[Stmt], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, stmts.iter().map(|s| (s.meta.leading.as_slice(), s.span)), dangling, out);
for stmt in stmts {
scan_nested_stmt(src, stmt, out);
}
}
/// Advance the open/closed state by one comment unit.
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
let start = c.span.start as usize;
match (fence_of(&c.text), open.is_some()) {
(Some(Fence::Off), false) => {
(Some(Fence::Off), false) if opens_line(src, start) => {
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
}
(Some(Fence::On), true) => {
@@ -202,8 +238,8 @@ fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>
}
}
/// Item scopes nested inside one item. Statement bodies are not scanned:
/// statement-level fences are out of scope (see the feature README).
/// Scopes nested inside one item: the item lists, and the statement lists an
/// item's body reaches.
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
match &item.kind {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
@@ -216,6 +252,57 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
scan_gen_block(src, &i.body, out);
}
}
ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out),
ItemKind::Function(f) => scan_stmt_scope(src, &f.stmts, &f.dangling, out),
ItemKind::Task(t) => scan_stmt_scope(src, &t.stmts, &t.dangling, out),
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
scan_nested_stmt(src, stmt, out)
}
_ => {}
}
}
/// Statement scopes nested inside one statement.
///
/// A statement *list* is a scope — `begin`…`end`, `fork`…`join*`. A
/// single-statement body is not, for the reason [`scan_gen_block`] refuses a
/// block-less generate item: there is no list for a fence to end in, and the
/// formatter lays that statement out inside a `Group`. So the bodies below are
/// walked into rather than scanned, and only the block one of them holds opens
/// a scope.
fn scan_nested_stmt(src: &str, stmt: &Stmt, out: &mut Vec<Region>) {
match &stmt.kind {
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
scan_stmt_scope(src, stmts, dangling, out)
}
StmtKind::If { then, els, .. } => {
scan_nested_stmt(src, then, out);
if let Some(e) = els {
scan_nested_stmt(src, e, out);
}
}
StmtKind::Assert { then, els, .. } => {
for s in then.iter().chain(els.iter()) {
scan_nested_stmt(src, s, out);
}
}
// A case item's *labels* are not a fenceable stream (see the feature
// README); the block one of them may hold is.
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for i in items {
scan_nested_stmt(src, &i.stmt, out);
}
}
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. }
| StmtKind::Labeled { stmt: body, .. } => scan_nested_stmt(src, body, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
scan_nested_stmt(src, inner, out)
}
_ => {}
}
}
@@ -242,6 +329,30 @@ fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
}
}
/// Whether a fence written at `at` begins the *content* of its line: nothing
/// but whitespace and finished block comments precedes it there.
///
/// This is what makes `begin // lucisv: off` an ordinary comment. The parser
/// hands a comment written after `begin` to the next *statement* as a leading
/// one, so without this test a region would open in the middle of a line and
/// take its first line's bytes from the wrong column. A fence preceded only by
/// another comment (`/* a */ // lucisv: off`) still opens one: that comment is
/// a unit of the same stream and prints on the line above.
fn opens_line(src: &str, at: usize) -> bool {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
let Some(mut before) = src.get(bol..at) else { return false };
loop {
before = before.trim_start();
if before.is_empty() {
return true;
}
match before.strip_prefix("/*").and_then(|b| b.split_once("*/")) {
Some((_, rest)) => before = rest,
None => return false,
}
}
}
/// 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.
@@ -323,6 +434,28 @@ mod tests {
assert_eq!(fence_of("// off"), None);
}
#[test]
fn a_fence_only_opens_a_region_at_the_start_of_its_line() {
// Whitespace before it, at any depth, and at the very first byte.
assert!(opens_line("// lucisv: off\n", 0));
assert!(opens_line("module m;\n // lucisv: off\n", 12));
assert!(opens_line("module m;\n\t\t// lucisv: off\n", 12));
// Another comment before it is still the start of the line's content.
let src = "module m;\n /* a */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
let src = "module m;\n /* a */ /* b */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
// Code before it is not — the two shapes the parser hands to the next
// node as a *leading* comment even though they trail code.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
let src = "module m; // lucisv: off\n wire a;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
// An unterminated block comment before it is not a finished comment.
let src = "module m;\n /* a // lucisv: off\n";
assert!(!opens_line(src, src.find("// lucisv").expect("fence")));
}
#[test]
fn a_fence_line_starts_at_its_indentation() {
let src = "module m;\n // lucisv: off\n";
+36 -4
View File
@@ -30,16 +30,48 @@ struct BlockDoc<'a> {
impl<'a> Fmt<'a> {
fn stmt(&self, s: &Stmt) -> Doc {
self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))
concat(self.stmt_docs(s))
}
/// One statement: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its code and trailing comment. The
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
/// written before the `off` fence are still emitted, because comments are
/// never dropped, and a statement the region swallowed emits nothing.
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
// A verbatim run whose first statement carries no leading comment opens
// at the statement's own code; there is no comment to emit it from.
if let Some(region) = self.opens_at(s.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(s.span) {
// The statement's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&s.meta);
// The last comment asked for a line break before code that is not
// coming. Whoever emits the next unit separates it itself.
if matches!(docs.last(), Some(Doc::HardLine)) {
docs.pop();
}
return docs;
}
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
}
/// Sequence of statements at one indent level, preserving single blank
/// lines between them. A statement a fenced region swallowed emits
/// nothing, and contributes no separator either.
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, s) in stmts.iter().enumerate() {
if i > 0 {
for s in stmts {
let stmt_docs = self.stmt_docs(s);
if stmt_docs.is_empty() {
continue;
}
if !docs.is_empty() {
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.stmt(s));
docs.extend(stmt_docs);
}
docs
}
+8 -1
View File
@@ -158,7 +158,14 @@ pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
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 }
// The fenced regions go in alongside the runs the picks made. An *item* a
// fence covers is already `Pick::Verbatim`, so its bytes are in a run
// either way; a fenced **statement** inside a laid-out item has no such
// run behind it, and without this the caller's `--lines` would reformat
// bytes the author fenced off. `normalize` folds the two into their union.
let mut regions = planner.regions;
regions.extend(planner.fences.iter().copied());
Plan { regions: normalize(regions), splits: planner.splits }
}
/// Sort the collected regions and fold everything that overlaps into one.
+246 -2
View File
@@ -372,7 +372,7 @@ wire a;
endgenerate
endmodule
====
# a statement-level fence has no effect this round
# a statement-level fence fences the statements between it and the on
module m;
always @(*) begin
// lucisv: off
@@ -382,15 +382,259 @@ y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a statement region keeps its own indentation, first line included
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
----
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
====
# an unmatched off runs to the end of the block, not past its end
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
----
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
====
# an unmatched off in a fork body stops at the join
module m;
initial fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
----
module m;
initial
fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
====
# fences work in a function body and stop at endfunction
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
----
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
====
# a fence inside a case item's block body fences that block only
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
====
# a fence written after begin on the same line is an ordinary comment
module m;
always @(*) begin // lucisv: off
x = 1;
y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a fence written after a module header on the same line is an ordinary comment
module m; // lucisv: off
wire a;
wire b;
endmodule
----
module m;
// lucisv: off
wire a;
wire b;
endmodule
====
# a fence inside a bodyless if is an ordinary comment
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
----
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
====
# fences work inside a class body
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
----
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
====
# an unmatched off in a class body stops at endclass
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
----
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
====
# a fence around a nested class fences the whole nested class
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
----
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
====
# a port-list fence is an ordinary comment, and the port list still formats
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
----
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
====
# a case-item label fence is an ordinary comment
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
====
# a blank line before the off fence survives, collapsed to one
module m;
wire z;
+136
View File
@@ -93,6 +93,142 @@ fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
}
}
#[test]
fn a_statement_region_is_emitted_byte_for_byte() {
// A fence between two statements of an `always` block: the hand-aligned
// interior, the blank line and the trailing comment all survive, and the
// statement after the `on` is formatted normally.
let src = "module m;\n always_ff @(posedge clk) begin\n // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on\n q2 <= d2;\n end\nendmodule\n";
let region =
" // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on";
let out = fenced(src, region);
assert!(out.contains("\n q2 <= d2;\n"), "formatting did not resume in the block:\n{out}");
}
#[test]
fn an_unmatched_off_in_a_statement_list_stops_at_the_end_of_that_list() {
// It must stop at the block's last statement — its trailing comment
// included — and never swallow the `end`, the `endfunction` or anything
// after them.
let src = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n end\n\n function int f();\n return 1;\n endfunction\nendmodule\n";
let out = fenced(src, " // lucisv: off\n x = 1;\n y = 2; // note");
assert!(out.contains("\n end\n"), "the block's `end` was swallowed:\n{out}");
assert!(out.contains("function int f();"), "the next item was not formatted:\n{out}");
assert!(out.contains(" return 1;"), "the next body was not formatted:\n{out}");
}
#[test]
fn a_fork_body_and_a_task_body_are_each_their_own_scope() {
let src = "module m;\n task automatic t();\n fork\n // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on\n p3 ();\n join\n z = 1;\n endtask\nendmodule\n";
let out =
fenced(src, " // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on");
assert!(out.contains(" p3();"), "the statement after the `on` was not formatted:\n{out}");
assert!(out.contains(" z = 1;"), "the task body after the fork was not formatted:\n{out}");
}
#[test]
fn a_class_body_is_a_fenceable_scope() {
let src = "class c;\n int a;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on");
assert!(out.contains(" int a;\n"), "{out}");
assert!(out.contains(" int d;\n"), "{out}");
}
#[test]
fn an_unmatched_off_in_a_class_body_stops_at_endclass() {
let src = "class c;\n // lucisv: off\n int a; // note\nendclass\n\nclass d;\n int b;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int a; // note");
assert!(out.contains("class d;\n int b;\n"), "the next class was not formatted:\n{out}");
}
#[test]
fn a_fence_sharing_its_line_with_code_is_an_ordinary_comment() {
// `begin // lucisv: off` reaches the scan as the *leading* comment of the
// first statement, mid-line. Honouring it would open a region whose first
// line came from the wrong column; it is an ordinary comment instead.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n y = 2;\n end\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" x = 1;"), "the fence fired mid-line:\n{out}");
// The same rule at item level: a header's own line is not a fence line.
let src = "module m; // lucisv: off\n wire a;\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" wire a;"), "the fence fired mid-line:\n{out}");
}
#[test]
fn the_three_deferred_places_are_inert_and_never_corrupt() {
// A port list, a case-item label list, and the single-statement body of a
// bodyless `if`: a fence in each is an ordinary comment, and the code
// around it is laid out exactly as it would be without one.
let cases = [
"module m (\n // lucisv: off\n input logic a,\n output logic b\n);\nendmodule\n",
"module m;\n always @(*) case (s)\n // lucisv: off\n 2'b00: a = 1;\n 2'b01: a = 2;\n endcase\nendmodule\n",
"module m;\n always @(*)\n // lucisv: off\n if (c) x = 1;\nendmodule\n",
];
for src in cases {
let out = fmt(src);
verify_equivalence(src, &out).expect("output is token-equivalent to the input");
assert_eq!(fmt(&out), out, "second pass changed the output:\n{out}");
assert!(out.contains("lucisv: off"), "the fence comment was dropped:\n{out}");
assert!(!out.contains(" a = 1"), "the fence fenced:\n{out}");
assert!(!out.contains("input logic"), "the fence fenced:\n{out}");
}
}
#[test]
fn a_corrupted_statement_or_class_region_is_still_rejected_by_the_safety_net() {
// The same attack as at item level, aimed at the two new scopes: a fence
// is not a licence to change bytes, and a hand-built "output" that
// reformats, drops or adds anything inside one must fail equivalence.
// Every pair changes the *token stream*, which is the question
// `verify_equivalence` answers; that a region's bytes are also reproduced
// exactly — spacing included, which no token check can see — is what the
// `fenced` helper asserts in the tests above.
let stmt = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n";
let stmt_corrupted = [
// a literal rewritten inside the region
"module m;\n initial begin\n // lucisv: off\n x = 7;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// the region's trailing comment dropped
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2;\n // lucisv: on\n end\nendmodule\n",
// the `off` fence itself dropped
"module m;\n initial begin\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement added inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n z = 0;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement dropped from inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n // lucisv: on\n end\nendmodule\n",
// the `on` fence turned into an ordinary comment
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: onward\n end\nendmodule\n",
// the block's `end` swallowed into the region's last line
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\nendmodule\n",
];
let class = "class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let class_corrupted = [
// a type rewritten inside the region
"class c;\n // lucisv: off\n bit b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
// a member dropped from inside the region
"class c;\n // lucisv: off\n int b = 2;\n // lucisv: on\n int d;\nendclass\n",
// a member added inside the region
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n int e;\n // lucisv: on\n int d;\nendclass\n",
// `endclass` swallowed
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\n",
// a fence comment dropped
"class c;\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
];
for (src, corrupted) in [(stmt, &stmt_corrupted[..]), (class, &class_corrupted[..])] {
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
for bad in corrupted {
assert!(
verify_equivalence(src, bad).is_err(),
"a corrupted fenced region was accepted:\n{bad}"
);
}
}
}
#[test]
fn the_matcher_agrees_with_what_the_formatter_honours() {
// The unit tests in `fence.rs` pin the matcher; this pins that the
+34
View File
@@ -218,6 +218,40 @@ fn a_fence_outranks_a_range() {
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
}
const WITH_STMT_FENCE: &str = "\
module m;
initial begin
a = 1;
// lucisv: off
b = 2;
cc = 3;
// lucisv: on
d = 4;
end
endmodule
";
#[test]
fn a_statement_fence_outranks_a_range_too() {
// A fenced *statement* sits inside an item the caller's lines select, so
// there is no verbatim run behind it: the plan has to carry the fence
// itself or the region would be laid out. Selecting any line of it, or
// the whole block, must leave those bytes exactly as written.
for spec in ["4", "5", "6", "7", "2-10"] {
let out = fixed_point(WITH_STMT_FENCE, spec);
assert!(
out.contains(" // lucisv: off\n b = 2;\n cc = 3;\n // lucisv: on\n"),
"spec {spec} reformatted the region:\n{out}"
);
}
// Laying out the whole block still formats what is outside the region.
let out = fixed_point(WITH_STMT_FENCE, "2-10");
assert!(out.contains(" a = 1;"), "{out}");
assert!(out.contains(" d = 4;"), "{out}");
// And a range that misses the block entirely changes nothing at all.
assert_eq!(fixed_point(WITH_STMT_FENCE, "1"), WITH_STMT_FENCE);
}
const ALIGNED: &str = "\
module m;
localparam int A = 1;
+9 -6
View File
@@ -60,7 +60,7 @@ request.
| M6 | ~~Indexed hierarchical `bind` target (`bind top.gen[0].u_core …`).~~ | bind README non-goals. | Delivered by TODO §26: `BindDirective::target` is a `Vec<PathSegment { name, span, index }>` and `at_bind_directive` steps over one `[…]` per segment. Shipped with the §2.9-15 semantics in the same round — a lone target resolves as a module or interface, a connection's port half against the bound-in module and its expression half in the target's scope. Real but unmeasured: still zero corpus and opentitan hits. |
| M7 | Semantic lints (`unused-signal`, `undriven-net`, `multiply-driven`) ship **off by default**. | linter-core / semantic-lints READMEs; blocked on topo §2.9-6 (workspace-wide "does any file mention this name"). | These are the lints RTL engineers want most; the index now has reference postings and `files_spelling`, so §2.9-6 is closer than when filed. |
| M8 | ~~Lint rules do not descend into verbatim regions~~ — **closed at 0.33.0 for what parses**, by construction: the rules read the reference table, and a structured assertion contributes ordinary references to it. A `signals.rs` `opaque_span` remains only for a region that fell back. | assertions / clocking-wave / sva-bodies READMEs. | Same root as C1; resolved with it. |
| M9 | Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3). | format-fences / classes READMEs. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
| ~~M9~~ | ~~Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3).~~ — **closed at 0.34.0+ by TODO §31.** Class bodies and every statement *list* (`begin`…`end`, `fork`…`join*`, function/task bodies, `initial`/`always`/`final` bodies, a `case` item's block body, a statement fragment) are fenceable scopes; `--lines` still loses to a fence. Two of the three named places stay out, with reasons: port/parameter lists and `case` **label** lists print mid-line inside a `Group`, where `Doc::Verbatim` (column-0, break-forcing) cannot stand — that wants a new printer primitive, not a scan arm. Measured on OpenTitan, which has 9 fenced files: four now keep their fenced bytes, including a 110-line class-body region. | statement-fences README; format-fences / classes / shared-fence-filter READMEs amended. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
| M10 | Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree. | error-recovery README (QA-confirmed). | Editing experience: diagnostics cascade while typing a header. |
| M11 | Anonymous aggregate members (`enum {A,B} x;`) not symbols (topo §2.9-13); cast type `state_t'(0)` records no reference. | overlay-promotion README; probe: enum *typedef'd* members do work. | Partial: named enums navigate, anonymous ones do not. |
| M12 | No `lint` key in `lucisv.toml` (topo §2.9-4); no `--rules-doc`. | four READMEs. | Config surface, not language — but it gates per-project rule selection. |
@@ -149,11 +149,14 @@ signal named only inside a property edits it, references list it, and the
"at least identifier occurrences" fallback the C1 row asked for was
overtaken rather than built (what the grammar cannot read still rewinds to
the byte-exact capture, and rename *names* those regions instead of going
quiet). What the tables above still leave open, by weight: M9 statement-level
and class-body format fences
(§2.9-3); M10 error recovery inside headers and lists; the second half of
quiet). What the tables above still leave open, by weight: M10 error recovery
inside headers and lists; the second half of
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M13's small
interface/DPI grammar arms are closed (TODO §30) — with one narrowing
recorded there: a single `import` may carry one prototype, not a
comma-separated list of them. The three stale READMEs named under the
order were reconciled in the 0.33.0 documentation pass.
comma-separated list of them. M9's format fences are closed too (TODO §31,
§2.9-3), with the same kind of narrowing recorded in its row: the two
mid-line list positions (port/parameter lists, `case` label lists) stay
inert, because a column-0 verbatim slice has no place inside a `Group`. The
three stale READMEs named under the order were reconciled in the 0.33.0
documentation pass.
+13 -4
View File
@@ -184,7 +184,14 @@ indexed, hovered or navigable.** That is a real LSP gap, not an oversight, and
it is the natural next round for that crate. **Delivered 2026-08-19 by
`class-semantics`** — see `docs/features/class-semantics/README.md`.
**Requested of `vlog_formatter::fence` (out of this feature's scope):**
**Requested of `vlog_formatter::fence` (out of this feature's scope) —
DELIVERED 2026-09-03 by TODO §31 / `docs/features/statement-fences`.**
`scan_nested` now carries the arm this section asked for verbatim
(`ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out)`), plus
the statement scopes a class's methods hold, so the probe below is now
formatted exactly as its module twin is and the asymmetry the lead note
describes is closed. The original request, kept for the record:
`scan_nested` enumerates the item scopes a fence can live in — module,
package, generate region, generate `if`/`for`/`case` — and ends in a `_ => {}`
catch-all, so a class body is not scanned. Probed and confirmed:
@@ -332,9 +339,11 @@ non-zero verification-error count.
- [ ] **Not done, deliberately:** canonical layout for constraint and
covergroup bodies. Two grammars, no layout convention worth inventing,
and the verbatim path is corruption-proof by construction.
- [ ] **Not done, out of scope:** fences inside class bodies (`fence.rs`, one
arm) and lint-rule coverage of class members (`visit.rs`, one arm).
Both filed under Handshakes.
- [x] **Fences inside class bodies** (`fence.rs`, one arm) — filed under
Handshakes, delivered 2026-09-03 by TODO §31
(`docs/features/statement-fences/README.md`).
- [ ] **Not done, out of scope:** lint-rule coverage of class members
(`visit.rs`, one arm). Filed under Handshakes.
- [ ] **Not done:** `` `uvm_field_int (x, y)`` — a macro invocation with a
space before its `(`. Ten of the 70 still-blocked ex-`extends` files die
on this, and it is the documented `macro-items` gap (their Assumptions,
+64 -36
View File
@@ -36,20 +36,27 @@ Consequences, all deliberate and all tested:
- **Block comments are not fences.** `/* verilog_format: off */` is an
ordinary comment. Restricting fences to `//` keeps a fence a whole-line
thing and keeps the region boundaries at line granularity.
- **A fence must be a leading comment**, i.e. it must start a line (nothing
but whitespace, or another comment, before it on that line). A comment on
the same line as preceding *code* is attached to that code as *trailing*
trivia, and `Meta.trailing` is an `Option<String>` with no span — there is
nothing to splice from. So `wire a; // lucisv: off` is an ordinary comment.
See Handshakes for the parser change that would lift this.
- **A fence must be a leading comment that begins the content of its line**
(nothing but whitespace, or finished block comments, before it there). Two
shapes fall outside that. A comment on the same line as preceding *code* is
usually attached to that code as *trailing* trivia, so `wire a; //
lucisv: off` is an ordinary comment — see Handshakes for the parser change
that would lift this. But not always: after a `begin`, or after a module
header's `;`, the parser hands such a comment to the **next** node as a
*leading* one, mid-line. `fence::opens_line` refuses those too, which is
what makes the rule above true rather than aspirational. (It was not, until
`statement-fences` — until then `module m; // lucisv: off` opened a region
whose first line was sliced from mid-line. Fixed there, with the case
pinned; the block-comment exception below is deliberate and unchanged.)
- The alias and the long form are interchangeable: an `off` in either
spelling is closed by an `on` in either spelling.
## Semantics
Fences select whole **items** (module items, package items, top-level items),
Verible-style. Think of an item list as a flat stream of *units*: each item's
leading comments, then the item's own code (its `(* … *)` attributes and
Fences select whole **items** (module items, package items, class members,
top-level items) and, since `statement-fences`, whole **statements**,
Verible-style. Think of a list as a flat stream of *units*: each element's
leading comments, then the element's own code (its `(* … *)` attributes and
trailing comment included), and finally the scope's dangling comments.
- A region **opens** at the first `off` fence in that stream and **closes**
@@ -68,44 +75,56 @@ trailing comment included), and finally the scope's dangling comments.
open `off`; both are just bytes inside the region, or an ordinary comment.
Fences do not nest and do not count.
- **An unmatched `off` runs to the end of its scope** — the last byte of the
containing item list, which is the end of the last item (its same-line
containing list, which is the end of the last element (its same-line
trailing comment included) or of the last dangling comment, whichever comes
last. At file scope that is the last byte of content in the file. It does
**not** leak into the enclosing scope: an `off` inside a module body is
closed by the module's `endmodule` at the latest, and an `on` written after
`endmodule` belongs to the file scope and cannot close it.
closed by the module's `endmodule` at the latest, an `off` inside a
`begin`…`end` by that block's `end`, and an `on` written after the closing
keyword belongs to the enclosing scope and cannot close it.
- **Fences never cross a scope boundary**, which is what keeps a region
aligned with item boundaries: a region can never end in the middle of an
item, so the formatter never has to print half of one.
aligned with element boundaries: a region can never end in the middle of an
item or a statement, so the formatter never has to print half of one.
### Out of scope this round: statement-level fences
A fence inside an item body — between two statements in an `always` block,
between two case items, inside a port list — **has no effect**. It is
formatted as an ordinary comment. Only `Item` lists are fenceable:
### The fenceable scopes
| fenceable scope | |
|---|---|
| file | `SourceFile.items` + `dangling` |
| package body | `ItemKind::Package` |
| module body | `Module.items` + `dangling` |
| module / interface / program body | `Module.items` + `dangling` |
| class body | `ClassDecl.items` + `dangling` |
| `generate` region | `ItemKind::GenerateRegion` |
| generate `begin`…`end` | `GenBlock` with `is_block` |
| `begin`…`end` | `StmtKind::Block` |
| `fork`…`join`/`join_any`/`join_none` | `StmtKind::ForkJoin` |
| function / task body | `FunctionDecl.stmts`, `TaskDecl.stmts` + `dangling` |
| statement fragment | `Fragment::Statements` |
Not fenceable: statement lists (`begin`/`end`, `fork`, function/task bodies),
case-item lists, port/parameter/connection lists, and the single-item body of
a bodyless `if (X) item;` in a generate (there is no list for a fence to end
in, and the formatter lays that item out inside a `Group`).
The statement scopes are reached from `ItemKind::{Always, Initial, Final,
Function, Task}` and from every compound statement that can hold a block —
`if`/`else`, `case`/`randcase` item bodies, the loops, a timing control, a
`wait`, an immediate `assert`, a labelled statement. Details, and the
statement half of the scan, in `docs/features/statement-fences/README.md`.
**Still not fenceable**, each for a reason recorded in that README:
port/parameter/connection lists and case-item *label* lists (their elements
print mid-line inside a `Group`, where a column-0 `Doc::Verbatim` cannot go);
the single-element body of a bodyless `if (X) …`, in a generate or in a
statement (there is no list for a fence to end in); same-line trailing fences;
and `PropSeqDecl.locals`, the one `Vec<Item>` not printed through `item_seq`.
The interaction worth knowing: an `off` at item level whose matching `on` was
written inside a *statement* is an unmatched `off`, so it runs to the end of
the item list rather than stopping at the `on`. That errs toward *more*
verbatim text, never toward reformatting something the author fenced off.
the item list rather than stopping at the `on` — and that `on`, in the
statement scope, is a stray `on`, i.e. an ordinary comment. That errs toward
*more* verbatim text, never toward reformatting something the author fenced
off.
## Splice mechanics
`fence::collect(src, &file)` walks the item scopes once, before any
formatting, and returns a sorted, non-overlapping `Vec<Region>`:
`fence::collect(src, &file)` walks the scopes once, before any formatting,
and returns a sorted, non-overlapping `Vec<Region>`:
```rust
struct Region { fence: usize, start: usize, end: usize }
@@ -192,11 +211,14 @@ either, so no stray blank lines appear where the region swallowed items.
- `Comment.span` / `Comment.text` / `Comment.blank_before` — the fence
matcher and the region boundaries.
- `Item.span` (code extent, attributes in, comments out) — region membership
for an item's code.
- `Item.span` / `Stmt.span` (code extent, attributes in, comments out) —
region membership for an element's code.
- The item-scope shapes: `SourceFile{items,dangling}`, `Module`,
`ItemKind::Package`, `ItemKind::GenerateRegion`, `GenBlock`, `GenIf`,
`GenFor`, `GenCase`.
`GenFor`, `GenCase`, `ClassDecl`.
- The statement-scope shapes, added by `statement-fences`:
`StmtKind::Block`, `StmtKind::ForkJoin`, `FunctionDecl`/`TaskDecl`
`stmts` + `dangling`, and `Fragment::Statements`.
Nothing in `crates/vlog_parser` was changed, and nothing new is required of
it for this feature to work as documented.
@@ -233,8 +255,11 @@ column 0, newlines included. It is treated as containing a hard line
(`contains_hard_line`, `Printer::fits`), so it can never be measured for a
flat layout. The one contract it relies on: it is only ever emitted right
after a line break or at the very start of the output, which is where the
"strip the indentation just written" step is correct. Both current emitters
(`Fmt::leading_comments`, `Fmt::dangling`) satisfy that.
"strip the indentation just written" step is correct. Every emitter satisfies
that: `Fmt::leading_comments`, `Fmt::dangling`, `Fmt::file`, `item_docs`
(through `item_seq`, whose callers all break first) and — since
`statement-fences` — `stmt_docs` (through `stmt_seq`, likewise, the statement
fragment at the start of the output being the one "or".)
## Status / TODO
@@ -255,9 +280,12 @@ after a line break or at the very start of the output, which is where the
must reject.
- [x] README.md Style section mentions fences.
- [x] TODO.md §2 fences item checked.
- [ ] **Not done, deliberately:** statement-level fences (documented above).
- [ ] **Not done:** same-line (`trailing`-trivia) fences — blocked on a
parser change, see Handshakes.
- [x] **Statement-level fences and class-body fences** — delivered
2026-09-03 by `docs/features/statement-fences/README.md` (TODO §31,
coverage_gaps M9, topo §2.9-3). The scope table above is the current
answer; this feature's own code was extended, not replaced.
- [ ] **Not done:** same-line (`trailing`-trivia) fences — the parser change
landed (see Handshakes), the rule it would need has not been decided.
## Work log
+16 -1
View File
@@ -32,7 +32,22 @@ behavior is unchanged byte for byte; the server gains the CLI's
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 `lucisv format` ignores it there.)
though `lucisv format` ignores it there.) **That example is stale as of
2026-09-03: TODO §31 (`docs/features/statement-fences/README.md`) taught
`collect` the class bodies and the statement lists, so the formatter and the
backstop now agree there. The union is still wider than `collect` alone —
the scan has no notion of scope, would be fooled by a fence spelled inside a
block comment, and pairs an `off` with the next `on` anywhere in the file —
but the specific asymmetry named above is closed. Neither
`protected_regions` nor `is_protected` changed: same signatures, same
contracts, and `crates/lucisv/src/lint.rs` and
`crates/lucisv_server/src/lint.rs` are byte-identical. One shape got
*narrower*, not wider, and it is the only one: `module m;
// verilog_format: off` used to be a region `collect` reported (the line
scan never saw it — the trimmed line is not a fence text), so `--fix`
declined inside it. That comment is no longer a fence at all, so nothing
there is protected any more. Right answer, but a narrowing; recorded here
because this file is where "what is protected" is supposed to be legible.**
- **`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
+638
View File
@@ -0,0 +1,638 @@
# statement-fences
## Goal
`// verilog_format: off` … `// verilog_format: on` selected whole **items**
only. A fence written between two statements of an `always` block, inside a
function or task body, inside a `fork`, or between two members of a `class`
was formatted as an ordinary comment — the hand-aligned tables RTL authors
protect at module scope had no escape hatch one level down, and DV code, which
lives almost entirely inside class bodies and methods, had none at all. This
round adds those scopes: a class body scans as the item list it already is,
and statement lists (`begin`…`end`, `fork`…`join*`, function/task bodies, the
body of an `initial`/`always`/`final`) scan through a statement twin of the
item scan. Closes coverage_gaps M9 and topo §2.9-3, and closes the asymmetry
`shared-fence-filter` documented: `protected_regions`' line scan already
declined to *edit* inside these fences, while the formatter happily laid them
out. Nothing here widens what a fence is or what it emits — a region is still
a slice of source bytes.
## Assumptions
- **A statement list is a fence scope; a single-statement body is not.** The
bodies of `if`, `for`, `while`, `repeat`, `forever`, `foreach`, `do while`,
a timing control and an immediate `assert` are walked *into* but are not
scopes themselves, for the reason `scan_gen_block` refuses a block-less
generate item: there is no list for a region to end in, and the formatter
lays that statement out inside a `Group`, where a column-0
break-forcing `Doc::Verbatim` has no correct place. Only the `begin`…`end`
or `fork`…`join*` such a body may hold opens a scope.
- **A fence must begin the content of its line.** Nothing but whitespace and
finished block comments may precede it there. This is `fence::opens_line`,
and statement scanning is what forced it: the parser hands a comment written
after `begin` on the same line to the *next statement* as a leading comment,
so without the test `always @(*) begin // lucisv: off` would open a region
whose first line was sliced from the middle of a line. It is also what the
format-fences README already claimed the rule was — see the deviation in the
work log.
- **`Stmt.span` is the statement's code extent, its attributes included and
its comments excluded, and it reaches its own `;`.** Both halves are
load-bearing, exactly as `Item.span`'s are: the attribute half is why
splicing a statement reproduces its `(* … *)`, the comment half is why a
statement's leading comments can be emitted while its code is skipped, and
the `;` half is why a region ending at a statement never cuts a token in
half. Verified by probe (`x = 1;` spans the `;`).
- **A statement scope's end is the last statement's `span.end`, extended over
the comment trailing it on the same line.** `Meta.trailing` carries a span
now, but the scan reads the source rather than the node, so that one
function (`with_trailing_comments`) answers the question for items and
statements alike. Without it an unmatched `off` would drop that comment —
hard invariant #3.
- **A region never straddles two scopes**, so regions are pairwise nested or
disjoint, and `collect`'s existing "sort by `fence`, then drop any region
whose `fence` precedes the previous region's `end`" filter still leaves a
list sorted by both ends — `region_at`'s `partition_point` precondition.
The argument is unchanged from item scopes and is spelled out under
Handshakes.
- **Every `stmt_seq` caller emits a line break before it.** `Doc::Verbatim`'s
one contract is that it is only ever emitted right after a line break or at
the very start of the output; `block_doc`, the `fork` arm, `function`,
`task` all push a `HardLine` before the sequence, and the statement-fragment
path is the start of the output. Audited by grep, listed in the work log.
## Handshakes
**Consumed from `vlog_parser` (nothing new is required of it):**
- `Stmt.meta.leading` / `Stmt.span` — the units of a statement scope, the
same pair `Item` supplies.
- The statement-scope shapes: `StmtKind::Block`, `StmtKind::ForkJoin`,
`FunctionDecl.stmts` + `.dangling`, `TaskDecl.stmts` + `.dangling`, and the
bodies reached from `ItemKind::{Always, Initial, Final}`.
- The item-scope shape `ClassDecl { items, dangling }`.
- `Fragment::Statements` — a statement fragment is one statement list at file
scope, so `collect` scans it as one.
**Promised to `vlog_formatter` callers: no public signature changed.**
`fence::collect`, `fence::region_at`, `fence::protected_regions` and
`fence::is_protected` keep their signatures and their contracts.
`crates/lucisv/src/lint.rs` and `crates/lucisv_server/src/lint.rs` are
byte-identical. What *did* change is `collect`'s answer: it now reports
regions the line scan already reported, which narrows the union
`protected_regions` returns toward the truth and can only ever decline the
same edits or fewer.
**`region_at`'s precondition still holds.** Two regions are nested or
disjoint: a region lives in one scope's unit stream, running from its `off`
fence to an `on` in the same stream or to that scope's own end, and scopes
nest. A statement region therefore lies wholly inside the item whose body
holds it, and an item-level region either contains that item entirely or ends
before it starts. Sorting by `fence` and dropping every region whose `fence`
falls before the previous region's `end` leaves a disjoint list, which is
sorted by both ends.
**`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4's obligation does not arise — and
none was needed: a region 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. Equivalence holds by construction and the check runs
unchanged as the backstop. New corrupted-region attack pairs for a statement
region and a class-body region are in `tests/fences.rs`, modelled on the five
that already guard item regions. Note what a *token* check cannot see: a
whitespace-only rewrite inside a region is token-equivalent, so the attack
pairs are all token-stream corruptions and the byte-exactness of a region is
asserted separately, by the `fenced` helper.
**`range.rs`: the plan now carries the fences.** `range::plan` extends its
manufactured verbatim runs with `fence::collect`'s regions before
`normalize` folds the two into their union. At item level this changes no
answer — a fenced item is already `Pick::Verbatim`, so its bytes were in a run
either way — but a fenced **statement** inside a laid-out item has no run
behind it, and without the merge `--lines` over such an item would have
reformatted bytes the author fenced off. A fence outranks a range, as before.
**Recursion budget (`docs/features/recursion-limit/README.md`): unaffected.**
`scan_nested_stmt` recurses only through statement nesting the parser already
bounds (`parse_stmt` is gated at the same 320 layers), builds no tree, and
`Doc::Verbatim` is a leaf.
**Requested of nobody.** No handshake request was filed; every file this round
needed was in its own ownership list.
## Deferred, with reasons
- **Port and parameter lists, and case-item label lists.** Their elements are
printed inside a `Group`, mid-line. `Doc::Verbatim` is column-0 and forces a
break — it cannot stand inside a group — and `Doc::Inline`, the only
mid-line verbatim primitive, carries no region indentation, so a region
spliced there would drift on every pass. This wants a different printer
primitive, not another scan arm. A fence in either place stays an ordinary
comment; pinned by `the_three_deferred_places_are_inert_and_never_corrupt`
and by two `.cases` entries.
- **Same-line (trailing-trivia) fences.** `wire a; // lucisv: off` is an
ordinary comment. Unblocked since `Meta.trailing` gained a span
(comments-round, 2026-08-19) but still deliberately inert: accepting it
means deciding whether the region starts on the *next* line, which is a
different rule from "the region starts at the fence's line start", and
nothing has asked for it.
- **The single-statement body of a bodyless `if (x) y = 1;`**, and the
single-item body of a bodyless generate `if` before it — same `Group`
reason as the lists above.
- **`PropSeqDecl.locals`** — a `Vec<Item>` that is *not* printed through
`item_seq`: `sva.rs` prints each local with `with_meta` and then the
property spec, which is not an item. The list has no end a region could
stop at without inventing one. Left alone; `Interface` and `Program` need
no arm because both are `ItemKind::Module`, which has been scanned since the
first round, and there is no `Checker` node in the AST at all.
- **The cross-level pairing rule is unchanged.** An item-level `off` closed by
a statement-level `on` is still an unmatched `off` — it runs to the end of
its own item list — and the `on` is a stray `on` in the statement scope,
i.e. an ordinary comment. That errs toward *more* verbatim text, never
toward reformatting something the author fenced off.
## Status / TODO
- [x] 31.1 class bodies: `ItemKind::Class` arm in `scan_nested`; the other
item-list carriers checked and named (`Interface`/`Program` are
`ItemKind::Module`, already scanned; no `Checker` node exists;
`PropSeqDecl.locals` deferred with a reason). Cases: a fence around one
member, around a nested class, an unmatched `off` stopping at
`endclass`, comments before the `off`.
- [x] 31.2 statement lists: `scan_units` (the shared unit stream),
`scan_stmt_scope`, `scan_nested_stmt`, the `Always`/`Initial`/`Final`/
`Function`/`Task` arms, the merge into `collect`'s sorted list, the
`stmt_seq`/`stmt_docs` rules, the `opens_line` gate, the
trailing-comment scope end, and the `range.rs` planner merge.
- [x] 31.3 docs rewritten: format-fences README ("Out of scope" replaced by
the real scope table), classes README handshake ticked,
shared-fence-filter README's asymmetry note corrected, `README.md`
"Turning the formatter off", `docs/coverage_gaps.md` M9 struck.
- [x] Attack pairs (a statement region, a class-body region) plus the
`fenced` triple for every new scope; `verify.rs` untouched.
- [x] Gates: `cargo fmt -p vlog_formatter`, `cargo clippy --all-targets
--workspace`, `cargo test --workspace`, corpus 814/820 byte-identical to
0.34.0, opentitan fence census + read-only sweep.
- [x] QA: PASS (2026-09-03). No CRITICAL/HIGH findings; two MEDIUM items
for the lead's ruling (`docs/topo.md` edited outside the dev's file
list; the `opens_line` narrowing, recommended as a drift fix) and one
LOW informational note. Full log below.
## Work log
### 2026-09-03 — dev agent (Opus 5)
Baseline measured first, in a throwaway `git worktree` at `HEAD`:
`cargo test --workspace` **3 234 passed, 0 failed, 42 ignored**.
**31.1 — class bodies (one arm, as planned).** `ItemKind::Class(c) =>
scan_scope(src, &c.items, &c.dangling, out)` in `scan_nested`. The other
item-list carriers were checked, since the plan asked for them by name:
`Interface` and `Program` are not separate nodes — both are `ItemKind::Module`
(`Module::end_kw` picks the closing keyword), so they have been fenceable
since the first round; there is **no** `Checker` node in the AST (grep over
`crates/vlog_parser/src/ast`); `GenBlock`, `GenerateRegion` and `Package` were
already scanned. The only `Vec<Item>` left unscanned is `PropSeqDecl.locals`,
deferred above with its reason. `format/class.rs` needed **no change** — the
class body has always printed through the fence-aware `item_seq`/`dangling`,
which is why one scan arm was the whole feature.
**31.2 — statement lists.**
- `scan_scope`'s body became `scan_units`, a scan over an iterator of
`(leading comments, code extent)` pairs plus the scope's dangling comments.
`scan_scope` and the new `scan_stmt_scope` are each three lines on top of
it. This is a pure refactor of the item path — the attribute guard
(`c.span.start < span.start`), the high-water mark and the
unmatched-`off` trailing-comment scan all live in one place now instead of
two, and the item-level output is unchanged.
- `scan_nested_stmt` walks the statement tree and opens a scope only at
`Block` and `ForkJoin`. `If`/`Assert` (both arms), `Case`/`RandCase` (each
item's body), `For`/`While`/`DoWhile`/`Repeat`/`Forever`/`Foreach`/
`Labeled` and the `Timing`/`Wait` bodies are walked through.
**Deviation from the plan, deliberate:** `Assert` and `Labeled` are not in
§31.2's list. They are structurally identical to `If`'s arms and to a bare
body — a `foo : begin … end` labelled block is a common DV shape — and
including them adds no scope kind, only reach.
- `scan_nested` gained the four item-side entries: `Function`/`Task` scan
their `stmts` + `dangling` as a scope; `Always`/`Initial`/`Final` hand their
body statement to `scan_nested_stmt`, which finds the `begin`…`end` inside
it.
- `collect` now dispatches on `SourceFile::fragment`: a `Fragment::Statements`
file is one statement list at file scope and scans as one.
**Deviation, deliberate:** §31.2 did not mention fragment mode. It is three
lines, `items` is empty for every fragment (verified in
`parser/directive.rs::read_fragment`), and leaving it out would have made
"statement lists are fenceable" false on the LSP's fragment path alone.
- `format/stmt.rs`: `Fmt::stmt_docs` is the statement twin of `item_docs` —
the region an offset *opens*, else the leading comments alone when the code
is swallowed (with the dangling `HardLine` dropped), else the statement.
`stmt` is now `concat(stmt_docs(s))` and `stmt_seq` separates on "did this
unit emit anything" instead of on the index, which is byte-identical to the
old formulation when no fence is present — the untouched snapshot suite is
the proof.
- `range.rs`: `plan` extends its runs with `planner.fences` before
`normalize`. See Handshakes for why; `normalize`'s doc comment already
described folding a fence and a run into their union, and this is the caller
that makes that sentence true.
**The line-start gate, and the one behaviour change outside the new scopes.**
`step` now opens a region only when `opens_line(src, start)`: whitespace and
finished block comments may precede a fence on its line, code may not. It was
forced by `always @(*) begin // lucisv: off`, which the parser hands to the
first inner statement as a *leading* comment — mid-line — where a region would
have started at the wrong column. Applying the test only to statement scopes
would have left the rule two rules, so it is applied everywhere, and that
changes one item-level shape: `module m; // lucisv: off` used to open a region
and now does not. Three reasons this is the right call rather than a
regression: the format-fences README has documented the rule as "*it must
start a line (nothing but whitespace, or another comment, before it on that
line)*" since the first round, so the code was the thing that drifted; the
existing `.cases` entry "a fence written after code on the same line is not a
fence" states the same rule for the case where the comment lands as *trailing*
trivia; and it narrows what fires, which cannot corrupt. The documented
`/* a */ // lucisv: off` exception is preserved deliberately — a block comment
before the fence is a unit of the same stream. Pinned by
`a_fence_sharing_its_line_with_code_is_an_ordinary_comment` and two `.cases`
entries. Corpus impact: none, it holds zero fences. **One consequence worth
stating plainly**, because it is the only place this round *narrows*
anything: `protected_regions` used to protect a `module m; // lucisv: off`
region (via `collect`; the line scan never saw it, since the trimmed line is
not a fence text), so `lucisv check --fix` and the server's quick fixes
declined to edit there. They no longer do — which is right, since that
comment is no longer a fence by any definition, but it is a narrowing and not
just a widening. Probed directly (`is_protected` false for that shape, true
for a statement fence, a class-body fence and an unmatched `off` in a task
body).
**File sizes, measured** (production lines: non-blank, non-comment, outside
`#[cfg(test)]`): `fence.rs` 226 → **246**, `format/stmt.rs` 573 → **590**,
`range.rs` 320 → **325**. All three stay inside CLAUDE.md's 300–600 band, and
nothing was pushed over a threshold. `format/stmt.rs` is the one to watch: at
590 it is close enough that the *next* addition to it should go in a new
module. Splitting it was not done here on purpose — a split is a pure move
and belongs in its own change, not tangled with a behaviour change.
**Not changed, on purpose:** `verify.rs`, `protected_regions`/`is_protected`,
`crates/lucisv/**`, `crates/lucisv_server/**`, `format/class.rs`,
`format/item.rs` (the two rules a swallowed unit obeys were already there and
`stmt_docs` mirrors them rather than sharing a helper — the two take different
node types and factoring them would cost a trait for one caller each).
**Results.** `cargo test --workspace` **3 244 passed, 0 failed, 42 ignored**
(baseline, measured in a worktree at `HEAD`: 3 234 / 0 / 42) — +10 tests:
8 in `tests/fences.rs`, 1 in `tests/ranges.rs`
(`a_statement_fence_outranks_a_range_too`, confirmed to fail without the
`range.rs` merge), 1 unit test in `fence.rs` for `opens_line`. `fences.cases`
goes 25 → 38 entries (+13; the entry "a statement-level fence has no effect
this round" was *inverted* rather than added, as §31.3 said it would be).
`cargo test -p vlog_formatter` 285 (was 275).
`cargo clippy --all-targets --workspace` **0 warnings**.
`cargo fmt -p vlog_formatter` clean — note it reformats the crate's tests
too, which is where the one unrelated-looking hunk in `tests/fences.rs` comes
from. `verify.rs` and `tests/verification.rs` untouched (`git diff --quiet`
on both).
Corpus: `scripts/corpus_gate.sh corpus` → `{"passing":814,"total":820,
"pct":99.3}`, the same six failures by the same categories, **0 verification
errors, 0 crashes**. Byte-identity against the 0.34.0 release binary
(`/tmp/lucisv-0.34.0-baseline`), `--stdout` per file over all **860** corpus
sources: **0 differences** — as expected, the corpus contains **zero** fence
comments (0 files match `verilog_format: (off|on)|lucisv: (off|on)`).
**OpenTitan (read-only; `--check` and `--stdout` only).** Census first: **9**
of 3 947 sources carry fence comments, 33 comment lines in all, and many sit
inside class bodies, task bodies and `fork` blocks — so files *could* move,
and four did. Old-vs-new `--stdout` over the whole tree: **4 differences of
3 947**, every one of them the fenced bytes now being preserved:
| file | what changed |
|---|---|
| `hw/ip/lc_ctrl/dv/env/lc_ctrl_env.sv` | a fenced `uvm_config_db#(…)::set(…)` call inside a `function` body keeps its hand-wrapped argument layout instead of being re-broken one-per-line |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_errors_vseq.sv` | a fenced **class-body** region (two `virtual task`s, ~110 lines) keeps its hand-written ternaries, comment placement and blank lines |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_jtag_access_vseq.sv` | the closing `on` fence keeps its own (odd, 5-space) indentation, because the fence comment is part of the region |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_jtag_priority_vseq.sv` | the blank line written between the `on` fence and the next statement is dropped — the documented "after the region" rule, now reaching statement level |
**Injection stress, the way the first fence round did it** (harness in the
scratchpad, not checked in; seed `0x2026_0903_dead_beef`, replayable). Four
random `off`/`on` line pairs injected into every corpus file that parses, each
compared against a **paired control** where the same two lines are ordinary
comments of identical width — the control matters, because injecting any
comment into a port list or an expression is a known pre-existing refusal
class (corpus-bugs README) and an unpaired comparison blames it on the fence.
Result over **3 348 trials** across 854 files:
```
trials=3348 fence_refusals=39 plain_refusals=39 new=0
honoured=3309 byte_exact=1976 same_level=1202 same_level_byte_exact=850
```
**Zero** verification failures attributable to fencing, and no panic. The
byte-exact figure (1 976 of 3 309 runs reproduce the whole `off`-line-through-
`on`-line slice contiguously) is a *floor*, not a defect rate: a randomly
placed pair lands as often as not in a position where the fence is inert by
design — a port list, a case label, a header line, an expression — or at two
different nesting levels, where the `off` is unmatched and correctly stops at
its own scope's end instead of reaching the `on`. Restricting to pairs whose
two lines share an indentation (a crude same-scope proxy, and only a proxy —
two sibling blocks share an indent too) lifts it to 850 of 1 202. What the
run rules out is the thing that matters: no injected fence ever made the
formatter produce output the safety net had to refuse when the same comment
in the same place would not have.
Each diff is assertion-free in the sense that matters: the `+` side is the
file's own source bytes. All four are fixed points under a second pass
(checked explicitly), and `--stdout` succeeding at all means
`verify_equivalence` and `verify_convergence` both passed inside
`format_source`. The read-only `--check` sweep reports **identical** counts
before and after (3 896 would reformat, 72 unchanged, 11 failed to format),
and `git -C ../opentitan status --porcelain` shows only the three
pre-existing modified files (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`).
Files touched: `crates/vlog_formatter/src/fence.rs`,
`crates/vlog_formatter/src/format/stmt.rs`,
`crates/vlog_formatter/src/range.rs`,
`crates/vlog_formatter/tests/fences.rs`,
`crates/vlog_formatter/tests/cases/fences.cases`, this README,
`docs/features/format-fences/README.md`, `docs/features/classes/README.md`,
`docs/features/shared-fence-filter/README.md`, `docs/coverage_gaps.md`,
`README.md`, `TODO.md` (§31 only). No `git commit`/`push`.
## QA log
### 2026-09-03 — QA agent (Sonnet 5)
All checks run read-only against the uncommitted main tree, plus one
throwaway `git worktree` (`.claude/worktrees/qa-play-31`, removed when done)
for the two experiments that needed source edits (the narrowing probe and
the `range.rs` load-bearing check). Never ran `git checkout`/`stash`/
`reset`/`clean` in the main tree. `git status --porcelain` before and after
this pass is identical to what the dev left: no file outside the dev's own
edits was touched.
**1. Gates — all confirmed independently, not just re-reading the dev's
numbers.**
- `cargo fmt --all -- --check`: clean (exit 0).
- `cargo clippy --all-targets --workspace`: 0 warnings; `git diff` of the
three touched files has no `#[allow]`.
- `cargo test --workspace --no-fail-fast`: summed the 48 `test result:`
lines myself — **3 244 passed, 0 failed, 42 ignored**, matching the
claimed baseline delta (3 234 → 3 244).
- `cargo test -p vlog_formatter`: summed to **285** (32+1+5+14+2+23+208+0),
matching the claimed 275 → 285.
- `git diff --stat -- crates/vlog_formatter/src/verify.rs crates/lucisv/src/lint.rs crates/lucisv_server/src/lint.rs`:
empty, all three.
- Changed-file set: `git status --porcelain` lists exactly the files named
in Handshakes/Work log, **plus `docs/topo.md`**, which is *not* in the
ownership list given to me (TODO §31's own "Files:" line marks
`docs/topo.md §2.9-3 struck (lead)` as the lead's job, not the dev's).
The content of that edit is accurate and consistent with everything
else (checked below), so this is a process note, not a defect: the
edit is already made, uncommitted, in the working tree ahead of lead
review. **MEDIUM** (process, not correctness) — flagging for the lead's
ruling, not blocking.
**2. Byte-identity — reproduced independently, not by trusting the dev's
numbers.**
- Built `cargo build --release -p lucisv` myself.
- Corpus: copied `corpus/` to two scratch trees, formatted one with
`/tmp/lucisv-0.34.0-baseline` and the other with the new binary
in-place, `diff -rq` the two trees: **0 differences** across all 860
files. `scripts/corpus_gate.sh corpus` → `814/820, 99.3%`, same failure
categories, 0 verification errors, 0 crashes.
- OpenTitan (read-only throughout — only `--stdout`/`--check`, and I
verified `git -C .../opentitan status --porcelain` was clean of
anything but the three pre-existing files both before and after):
- Census: `grep -rlE 'verilog_format: (off|on)|lucisv: (off|on)'` over
`hw/` → **9 files**, matching the dev's count.
- Copied the whole `hw/` tree (3 947 sources) to two scratch trees,
formatted one with each binary, `diff -rq`: **exactly 4 differing
files**, and they are the same 4 the dev named
(`lc_ctrl_env.sv`, `lc_ctrl_errors_vseq.sv`,
`lc_ctrl_jtag_access_vseq.sv`, `lc_ctrl_jtag_priority_vseq.sv`). Both
binaries exit 2 (pre-existing parse failures elsewhere in the vendor
tree, unrelated).
- Read all four diffs. `lc_ctrl_env.sv`: the new output's fenced lines
are byte-for-byte the same text as `git show HEAD:...` at that
location (checked directly). `lc_ctrl_jtag_access_vseq.sv`: confirmed
the source really does have 5 leading spaces before that `on` fence
(`awk` line dump), so the "odd indentation preserved" claim is real,
not a typo. `lc_ctrl_jtag_priority_vseq.sv`: the blank line after the
`on` fence is dropped, matching the documented after-region rule.
`lc_ctrl_errors_vseq.sv`: found the single real fence pair by grep
(lines 918/1030 — the other six `verilog_format: off/on` comments in
that file all carry trailing text, e.g. "- avoid bad formatting", so
per the fence grammar they are correctly **not** fences and correctly
untouched); a Python regex extraction confirmed the new output's
~110-line fenced slice is identical to the same slice in
`git show HEAD:...` of the file.
- Second-pass fixed point: ran the new binary again on all four new
outputs — byte-identical (`diff -q` clean) for all four.
- Comment census (counting `//`-bearing lines) on all four files:
original source, old-binary output, new-binary output all match
exactly (8, 196, 41, 21 respectively) — no comment dropped.
- `--check` over `hw/` with both binaries: identical counts, **3 896
would reformat, 72 unchanged, 11 failed**, both before and after.
**3. Break it — 15 hand-written files** (scratchpad `qa-31/breakit/`),
one per scope/edge named in the task: `begin…end`, `fork…join`, a function
body, a bodyless `always_comb` (no `begin`), a whole `if`/`else`, a `case`
item body, a class item and a nested class, an item-level `off` closed by a
statement-level `on` (two variants), an unmatched `off` in a statement list
stopping before `endfunction`, `begin // lucisv: off` (same-line, ordinary
comment), a block comment sharing the fence's line (the documented
exception), a fence with trailing text (ordinary comment), deep nesting
(fork inside if inside if), a fenced statement under `--lines` (five range
specs against the CLI directly, not just the dev's `ranges.rs` test), and
`check --fix` on two shapes.
Every file that parsed produced output — `format_source` calls
`verify_equivalence`+`verify_convergence` internally, so every successful
`--stdout` already proves equivalence; I additionally re-ran the output
through the binary a second time and diffed byte-for-byte for all 15 —
**all fixed points**. Comment line counts (`//`/`/*` occurrences) match
input to output on all 13 of the scope/edge files. Specific findings:
- The bodyless `always_comb` case: confirmed the fence comment survives
(never dropped) while `x = 1;` is laid out normally (collapsed
spacing) — correctly inert, not a scope, as documented.
- The nested-fence pairing rule (item `off` / statement `on`): built a
case with `wire a;` after the `initial begin...end` inside the same
module, both with distinctive multi-space padding. Confirmed the
**entire module body up to and including that `wire` declaration** came
out byte-for-byte raw (padding preserved), while a `wire b;` written
*after* it was laid out normally — i.e. the unmatched item-level `off`
swallows everything to the end of its own item list, the inner
statement-level `on` is correctly inert, and the fence does not leak
into the next item. Matches the documented rule exactly.
- `--lines`: ran the CLI directly (not the dev's own test) with
`--lines 4` and `--lines 1-9` over a file with a mid-block fence: both
left the fenced statements untouched while reformatting the
surrounding, already-clean statements — a fence outranks a range,
confirmed against the real binary.
- `check --fix`: crafted two files, one with the narrowing shape
(`module m; // lucisv: off` followed by a stray `;` null item) and one
with a genuine statement fence around a stray tab character. Ran
`check --fix` with **both** `/tmp/lucisv-0.34.0-baseline` and the new
binary on copies of each:
- Narrowing shape: old binary reports the `empty-item` violation but
does **not** fix it (declined, protected); new binary fixes it
(deletes the `;`) and the violation disappears from the report
entirely. This is the real, user-visible consequence of the
narrowing, confirmed live rather than by reading the dev's prose.
- Genuine statement fence: **both** binaries report the `no-tabs`
violation but decline to fix it — the tab stays untouched by both.
Statement-level protection for `--fix` holds.
No dropped comment, no non-fixed-point, no moved byte inside a region in
any of the 15 files.
**4. The narrowing — reproduced at both the formatter and the
`is_protected`/`protected_regions` layer**, and the CLI `--fix` layer
above.
- Quoted the format-fences README exactly as of round 1
(`git show 02f6865:docs/features/format-fences/README.md`): *"A fence
must be a leading comment, i.e. it must start a line (nothing but
whitespace, or another comment, before it on that line)."* The dev's
claim that this rule predates the code is correct — verified by reading
round 1's own text, not by trusting the work log's paraphrase.
- Built two throwaway worktrees (`qa-play-31` at the dev's patch,
`qa-baseline-31` at plain `HEAD`) and added a temporary probe test to
each (`tests/fences.rs`, never touching the main tree). Confirmed
directly: `protected_regions`/`is_protected` on `module m; //
lucisv: off\n wire a;\nendmodule` returns **not protected** on the
dev's patch and **protected** on plain `HEAD` — the narrowing is real
at the API level the CLI's `--fix` and the server's quick fixes both
call, not just in the formatter's own byte-for-byte splice.
- A genuine statement fence and a genuine class-body fence both remain
protected in the same probe, and `collect`'s own (scope-aware) answer
for an unmatched `off` in a task body stops exactly at `endtask`
(verified the region's `end <= task_end`), never past it — the crude
line-scan half of `protected_regions`'s union has no notion of scope
and may still over-protect further (documented, and I confirmed it: it
ran the same unmatched-`off` region to end of file), which only ever
*declines* an edit and is unrelated to this feature.
- Both worktrees removed after use (`git worktree remove --force`);
`git status --porcelain` on the main tree confirmed unaffected
throughout.
**Recommendation on the narrowing: drift fix, not a regression.** The
documented rule predates this round by two releases (round 1, commit
`02f6865`); the code was the thing out of step with its own spec, not the
other way around; the change only removes protection, it adds none (an
already-verified-safe direction per invariant #1); and the shape it stops
matching (`module m; // lucisv: off`, comment trailing the header on the
same line) was never advertised as supported in any README, changelog, or
`.cases` file before this round touched it. I found no place where a user
was told this specific shape worked. Concur with the dev: ship it as a
drift fix, MEDIUM severity recorded for the lead's ruling only because it
is a live user-visible behavior change (a real `--fix` decision flips),
not because anything is wrong with it.
**5. Attack pairs.** Read the dev's new corrupted-region pairs in
`tests/fences.rs` (7 statement-region + 5 class-region corruptions) — all
plausible, all target genuine token-stream changes (literal rewrites,
dropped/added statements or members, fence-comment tampering, swallowed
closer). Added two of my own in the `qa-play-31` worktree:
- A single literal changed inside an otherwise-intact statement region —
rejected by `verify_equivalence`, as expected.
- The `on` fence's *effective* position moved one statement earlier: first
tried a whitespace-only variant (`y = 2;` → `y = 2;`, fence text left
in place) and it was **accepted** by `verify_equivalence` — not a bug,
the documented boundary ("a whitespace-only rewrite inside a region is
token-equivalent") applies identically to item-level regions since round
1 and `verify.rs` is untouched this round, so there is no new widening
to attack-test under invariant #4. Replaced it with two variants that
are genuine token corruptions (a literal changed inside the region; the
`on` fence's own text moved a line, laundering a statement from
verbatim to laid-out) — both correctly rejected.
- **LOW note, not a defect**: worth restating in the feature README
(already is, in Handshakes) that the safety net's defense against a
whitespace-only corruption inside *any* fenced region — item or
statement — is the formatter's own verbatim-copy code path, unit- and
snapshot-tested directly, not `verify_equivalence` after the fact. This
is pre-existing and out of scope for this round.
**6. `range.rs` load-bearing claim — reproduced.** In `qa-play-31`,
commented out the one line `regions.extend(planner.fences.iter().copied());`
in `range::plan`: `cargo test -p vlog_formatter --test ranges
a_statement_fence_outranks_a_range_too` **failed** exactly as predicted
(spec `4` reformatted the fenced statement, collapsing `b`/`cc`'s
spacing). Restored the line: the test **passed**. The claim is not
decorative — the merge is genuinely load-bearing.
**7. Docs.** Read all four amended READMEs in full
(`format-fences`, `classes`, `shared-fence-filter`, plus the new
`statement-fences`) and `README.md`'s "Turning the formatter off" and
`docs/coverage_gaps.md`'s M9 row.
- `format-fences/README.md`: "Out of scope" is now a real "The fenceable
scopes" table plus a "Still not fenceable" list; matches the code
(checked the `scan_nested`/`scan_nested_stmt` match arms directly
against the table's rows).
- `classes/README.md`: the filed handshake is marked delivered with the
exact arm quoted; matches `fence.rs`'s actual diff.
- `shared-fence-filter/README.md`: the stale-asymmetry note is correctly
marked stale with a dated correction; the "one shape got narrower"
paragraph matches finding 4 above word for word.
- `README.md`: the new class-method example is realistic UVM shape and
formats correctly when I ran it (spot-checked). The "must begin its own
line" and "no further" wording matches the code.
- `docs/coverage_gaps.md`: M9 struck with an accurate closing note (the
two deferred mid-line positions named correctly); the "what's still
open" paragraph at the bottom updated consistently.
- `TODO.md` §31: all four sub-checklists ticked match delivered work;
only the QA line is unchecked, correctly, since QA had not run.
Deferrals (port/parameter lists, case-item *label* lists, same-line
fences, `PropSeqDecl.locals`) are each named with a real, checkable
reason in the statement-fences README's own "Deferred, with reasons"
section, and I independently exercised the three deferred shapes
(break-it §3, `t4`/port-list/case-label cases already covered by the
dev's own `the_three_deferred_places_are_inert_and_never_corrupt` test,
which I read and agree models them correctly).
**Findings summary.**
- MEDIUM: `docs/topo.md` was already edited in the uncommitted tree,
outside the file-ownership list this task gave me and outside what
TODO §31's own "Files:" line assigns to the dev (marked "(lead)"). The
content is accurate; flagging only the process order for the lead.
Not blocking.
- MEDIUM (ruling requested, not a defect): the `opens_line` narrowing —
see finding 4. Recommend: accept as a drift fix.
- LOW (informational, not a defect): the safety net's blind spot for a
whitespace-only corruption *inside* a region is unrelated to this
round's changes to `verify.rs` (there are none) and predates it at item
level; noted for the record only.
- No CRITICAL or HIGH findings. No corruption, no dropped comment, no
non-fixed-point output, no moved byte inside any region, no reach past
a scope's own end, no range reformatting a fenced byte, and `verify.rs`
confirmed untouched (`git diff --stat` empty) with its existing token
check independently re-exercised and holding for every genuine
corruption I constructed.
**Verdict: PASS.**
## Review
**2026-09-02 — lead.** Accepted. The round did what the plan asked and
found the two things the plan could not see: that `range.rs` must merge
fence regions into its plan because a fenced *statement* has no verbatim
run behind it (proved by breaking it), and that the line-start rule has
to be one rule — `opens_line` everywhere — because the parser hands a
same-line fence after `begin` to the first inner statement as a leading
comment. The narrowing that follows (`module m; // lucisv: off` no
longer opens a region, and the backstop stops protecting that shape) is
ruled a drift fix: the format-fences README has said "it must start a
line" since round 1 (QA quoted the commit), the statement-level case
already behaved that way, and a fence hiding after code is exactly the
ambiguity the rule exists to remove. `scan_units` as the one scan under
both scope kinds is the right shape; the three extra walker arms add
reach, not scope kinds. Deferred with reasons and recorded: port lists,
case-item labels, same-line fences, a property's locals. Proof:
corpus byte-identical (zero fences there), opentitan's four fenced
files now keep their bytes and are fixed points, 3 348 injection trials
with no new refusals. QA's note that a whitespace-only change inside a
region is invisible to `verify_equivalence` is a documented, pre-
existing property of item-level fences too (a region is source bytes;
the formatter never rewrites them) and is not this round's obligation.
`format/stmt.rs` at 590 production lines is the next lane's first
split. Ships in 0.35.0.
+2 -1
View File
@@ -383,6 +383,7 @@ recursion-limit, whose edges sit in §2.1). Code edges:
| `sva-bodies ──▶ assertions / constraint-bodies / covergroup-bodies / comment-slots / refactor-rename / semantic-lints` | depends | (2026-09-02) The SVA half of coverage_gaps C1/M8. `property`/`sequence` declarations, concurrent `assert`/`assume`/`cover`/`restrict property`, `expect`, `cover sequence` and `default disable iff` are real nodes: `sequence_expr`/`property_expr` as one precedence-climbing extension of `parse_expr` (the README's table is IEEE 1800-2017 **Table 16-3** row by row — QA caught two rows transcribed from Table 11-2 instead: `nexttime`/`s_nexttime` sit on `not`'s row, and the whole loosest row — `always`/`eventually`/`accept_on`/`reject_on`/`sync_*`/`if`/`case` — is read position-independently with a `property_expr` operand at precedence 0; a right-associative operator at or below `iff` likewise reads its right operand at 0), typed formals, assertion variables, action blocks as the statements they are — behind a `Rewind` snapshot with a byte-exact per-construct verbatim fallback that fires on 0 of 4 792 files. Nothing reserved: operator words are text-matched in SVA position only. One layout rule: top-level `\|->`/`\|=>`/`##`/`and`/`or` break one per line at the parent's indent when the spec does not fit. SVA gap fuzzer 705/0; 46 attack pairs plus the accepted transformation; `verify.rs` untouched; `tests/census.rs::sva_lines` proves every changed line of the 49 moved files lies inside an SVA construct. Semantics: `SymbolKind::{Property, Sequence}`, `ScopeKind::PropSeq`, instances resolve in-file and cross-file (`FACTS_FORMAT` 15 → 16); rename/references/lints see inside; `Scope::sva_fallback_warnings` for what would fall back. Output moved in 13 corpus + 36 opentitan files, all inside assertion text. |
| `macro-word-census ──▶ semantic-lints-on / refactor-rename / index-persistence / lint-rules-2` | depends | (2026-09-02, TODO §29) `FileFacts::macro_words` (`words::harvest_raw`, tag `MW`, `FACTS_FORMAT` 16 → 17) and `WorkspaceIndex::files_naming_in_macros`; `lucisv_server::rename` warns about every file naming the old name inside a macro invocation that lies outside the set `rename_sources` built — the §2.9-18 ruling made real, nothing read. `vlog_refactor::Scope` promoted to the crate root (pure move). `lucisv check --rules-doc` prints `rules_markdown()` (§2.9-5). |
| `interface-dpi-arms ──▶ interfaces / dpi-export / comment-slots` | depends | (2026-09-02, TODO §30, M13) Modport method prototypes (`import task drive(int x)`) through `Parser::parse_tf_header`/`Fmt::tf_header`, the single header parse and print the function/task declarations now share; bound `Target::InScope` with the formals in a scope of their own; one prototype per `import`/`export` group (the comma list stays an error, recorded). Unnamed DPI formals behind `parse_tf_ports(allow_unnamed)`, the empty-name convention on `TfArg::name`. `const /*c*/ ref` gap owned (`TfArg::after_const`). Zero corpus population; 4 807 files byte-identical. |
| `statement-fences ──▶ format-fences / classes / shared-fence-filter / range-formatting` | depends | (2026-09-02, TODO §31, M9) Fences at statement level and inside class bodies; `protected_regions`/`is_protected` signatures untouched so `lucisv/src/lint.rs` and `lucisv_server/src/lint.rs` are byte-identical; `verify.rs` untouched. One narrowing: a fence written after code on the same line is an ordinary comment everywhere now (it already was at statement level and in the documented rule). |
| `constraint-bodies ──▶ classes / out-of-class-constraints / dv-statements / safety-net` | depends | (2026-09-02, round 1 of coverage_gaps C1) `ItemKind::Constraint(ConstraintDecl)` with a structured `ConstraintSet` (`Expr{soft}`, `Implication`, `If`, `Foreach`, `SolveBefore`, `Unique`, `DisableSoft`, `Directive`, `Empty`), `ExprKind::Dist`, and `WithConstraint.block` as `ConstraintBody::{Items, Verbatim}`. The parser takes a `Rewind` snapshot (cursor, **both pending-comment buckets**, depth, links, `open_conds`, diagnostics length), attempts the structured body, and on any error restores it and re-runs v0.26.0's verbatim capture character for character — so an unknown shape *is* the old behavior, not an approximation (pinned on text, slice and `col`). **No keywords reserved**: `soft`/`dist`/`solve`/`before` are matched by text like `restrict`, so `token.rs`, `pairs.rs`, the editor grammar and `tests/grammar.rs` are untouched and `logic before;` keeps working; `:=`/`:/` stay two tokens with a span-adjacency check (a `:/` token would swallow `:/* c */`). Canonical layout: one item per line, `}` at the header column, dist weights as a braced list; a `with` block keeps the source's one-line-or-not shape. `verify.rs` untouched; the constraint attack pairs re-derived plus new ones. Exhaustive arms paid in `format.rs`, `bind.rs`, `tests/spans.rs`; `visit.rs` gets an explicit no-op arm (no items/statements inside). **QA rework**: comments after the round's own text-matched words were dropped; the dev answered with an exhaustive gap fuzzer (a `/*C*/` in every inter-token gap of 15 fixtures, 358 gaps, format + idempotency demanded) and 14 named comment fields plus `ConstraintItemKind::takes_semi()` (one owner of the `;`) and `Parser::gap_before` (the closer-side twin of `take_before_open`); 96 regressions vs v0.26.0 became 40, all in shared machinery outside this lane — §2.9-22. Opentitan: 1 993 of 2 009 bodies structured (fallbacks: 10 macro-item bodies, 6 non-LRM shapes), failure set unchanged, per-file tolerant diagnostics identical, 48 DV files idempotent with comment streams byte-identical. |
| `covergroup-bodies ──▶ constraint-bodies / classes / safety-net` | depends | (2026-09-02, round 2 of coverage_gaps C1) `ItemKind::Covergroup(Box<CovergroupDecl>)` with `CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}`, `BinDecl { wildcard, kind, name, array, spec: BinSpec::{Values, Transitions, Default, DefaultSequence, Select}, with_expr, iff }`, `SelectExpr` for `binsof … intersect … && !binsof`, one `CoverageEvent` enum. Same `Rewind` fallback as constraints — v0.27.0's flat scan re-run character for character on any failure — and no keywords reserved (`coverpoint`, `bins`, `cross`, `binsof`, `intersect`, `wildcard`, `ignore_bins`, `illegal_bins`, `option`, `type_option` by text). **Two guards in shared expression machinery, the round's one risk**: `at_postfix_segment` refuses `[` followed by `*`/`->`/`=` (no index can start with those — it is what lets `1'b1[*5]` be a transition repeat), and a `no_with` flag while a bin spec operand is read (so the bin's own `with (…)` filter is not eaten as an array-method iterator argument); `(`-disambiguation is by position, the LRM's own rule. `plain_expr_list` → `plain_list` and `constraint_parens` → `guard_parens`, shared with `iff`/`with`. `verify.rs` untouched, twelve attack pairs. The gap fuzzer was built in from day one (329 gaps, 52 fail, all §2.9-22 shared machinery — *asserted* by running each shape outside a covergroup). Opentitan: 544 of 544 covergroups structured, 87/87 DV covergroup files idempotent, failure set and per-file diagnostics identical. `on_type.rs` keeps `covergroup` OPAQUE by argument. |
| `fragment-mode ──▶ error-recovery / define-table / lexer-cleanup / covergroup-bodies` | depends | (2026-09-02, coverage_gaps H4 corrected) Class-body and module-item `.svh` fragments already parsed — the file-scope item loop *is* the class-item loop; the three shapes that did not (statement lists, enum-member lists, cover-item lists) become `SourceFile::fragment: Option<Fragment>` (`items` empty iff `fragment` is `Some`). Detection is a whole-file rule, not an error-message match: the FIRST STRUCTURAL item failed (directives, macro items and null items are legal in every body and do not count; a tolerant `Ok` that recorded a diagnostic counts as failed — the `if … else` generate-vs-statement parity bug), the file does not open with a design-unit keyword, and a shape consumes the file to EOF, tried narrowest-first (cover items → enum members → statements: the wider grammars mis-read the narrower). Each shape re-lexes a fresh token stream — `Rewind` deliberately does not restore the tokens' comment buckets, right for verbatim captures and fatal here. Shared loops lifted (`parse_enum_members`, `parse_cover_items`); formatter prints a fragment at indent 0 through existing printers; binder gives statements a file `Block` scope and enum variants file scope; **no census change** (a fragment's variants are not exported — `pkg::CUSTOM_1` must not resolve to a name that does not exist), FACTS stays 12. Separately, the lexer continues a `` `define `` whose formal-argument `(` touches the name and is still open at end of line, no backslash needed until the list closes — `cip_base_vseq__tl_errors.svh`'s real blocker. Corpus 813 → 814/820; opentitan 12 → 10, exactly the two predicted files. |
@@ -560,7 +561,7 @@ update the filing README(s) and this file.
|---|---|---|---|
| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core |
| 2 | A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive | vlog-semantic (item 2); restated by class-semantics | vlog_parser |
| 3 | `fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off) | classes | vlog_formatter (fence.rs) |
| ~~3~~ | ~~`fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off)~~ — **delivered 2026-09-02 by statement-fences (TODO §31)**: `scan_nested` enters class bodies, functions, tasks, `always`/`initial`/`final`; statement lists (`begin…end`, `fork…join`, every compound body) are fenceable through `scan_stmt_scope`/`scan_nested_stmt` on the shared `scan_units`; `stmt_docs`/`stmt_seq` obey the two swallowed-unit rules; fence regions merge into `range.rs`'s plan (load-bearing — a fenced statement has no verbatim run behind it). A region opens only at a line start (`opens_line`), so `module m; // lucisv: off` no longer opens one — the rule the format-fences README has stated since round 1. Deferred with reasons: port lists, case-item label lists, same-line fences, `PropSeqDecl.locals`. Opentitan: 4 of its 9 fenced files now keep their fenced bytes. | classes | ~~vlog_formatter (fence.rs)~~ done |
| ~~4~~ | ~~A `lint` key in `lucisv.toml` (`[lint.<rule>]` config; selected-rules list) with CLI>config precedence~~ — **delivered 2026-09-02 by semantic-lints-on**: `[lint] select = […] / ignore = […]` in `lucisv.toml` (CLI over config, key by key; unknown rule names fail the run naming the file; `[lint.<rule>]` tables rejected by name — per-rule config stays filed) and `lucisv.lint.select/ignore` settings (registry-validated, republish on change). | linter-core; restated by lint-rules-2, semantic-lints, server-lint | ~~config-discovery / lucisv_core~~ done |
| ~~5~~ | ~~`lucisv check --rules-doc` printing `rules_markdown()`~~ — **delivered 2026-09-02 by macro-word-census (TODO §29.3)**: `lucisv check --rules-doc` prints `rules_markdown()` and exits 0, takes no files, is lint-only; the example binary is gone | lint-rules-2 | ~~crates/lucisv~~ done |
| ~~6~~ | ~~Workspace-wide "does any file mention this name" query — the precondition for the semantic lints defaulting on~~ — **delivered 2026-09-02 by semantic-lints-on**: `FileFacts::words` (one identifier harvest, `vlog_semantic::words`, lifted from the server's candidates) and `WorkspaceIndex::files_mentioning` / `mentioned_outside(name, own_file)`; `FACTS_FORMAT` 12 → 13. The three rules consult a `MentionOracle` and are on by default whenever one exists. | semantic-lints | ~~vlog_semantic (index)~~ done |
+9
View File
@@ -5,6 +5,15 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.35.0 — 2026-09-02
- **Format fences work inside procedural blocks and classes.**
`// lucisv: off` … `// lucisv: on` now protects statements inside
`begin … end`, `fork … join`, function and task bodies and
`always`/`initial`/`final`, and items inside a class body — byte for
byte, including with range formatting. A fence must start its line;
one written after code on the same line is a plain comment.
## 0.34.0 — 2026-09-02
- **Rename warns about macro arguments it could not edit**, naming every
+6 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.34.0**. Its platform packages include both
The current release is **0.35.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -326,6 +326,11 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.35.0 highlights
Version 0.35.0 lets format fences protect statements inside procedural
blocks, function and task bodies, and items inside class bodies.
## Release 0.34.0 highlights
Version 0.34.0 makes rename name the macro arguments it cannot edit,
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.34.0",
"version": "0.35.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",