Small items, round 3: a bare begin block recovered as a generate block, the half-typed #( override lookahead, atomic in-place writes
TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25 and the §1 atomic-writes item. 36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end` at module scope or straight inside a generate region is parsed as an unnamed generate block with a diagnostic at the keyword, so the items inside and after it survive; strict mode is untouched. Consumers walk its items; `module-begin-block`, `v2001-generate-begin` and `mismatched-labels` read the node. The formatter's `gen_block` is split by a pure extraction into `begin_block`. One server test that parsed a 3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE. 36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead in `parse_connection`: an unclosed `.NAME(` whose value would swallow the next instance as a call fails the element instead; `recover_element` takes the bracket the element stopped on before skipping so the skip stays at the list's level. The balanced-parens spelling stays greedy. 36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename, permissions preserved, symlink target replaced, read-only target refused as `fs::write` refused it; used by format, `check --fix` and the cache. Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in their QA logs; the §27 P6 line and the sva-bodies README checkbox annotated as delivered by §29), topo §2.9-24/25 struck. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
0757503fd1
commit
a30dda167a
35 files changed
+1421
-83
No files matched your search
@@ -2913,12 +2913,12 @@ collide); no parallel lane.
|
||||
`undriven-net`, exactly as in `covergroup-bodies`.
|
||||
- [x] P5 verbatim-SVA rename warning (pin: a fallback region spelling
|
||||
the old name warns, never silent)
|
||||
- [ ] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
- [x] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
is a macro argument still warns) — the **engine half is done and
|
||||
pinned**; the server fan-out (`Workspace::rename_sources`,
|
||||
outside the round's file list) is filed as Handshake request 1 in
|
||||
`docs/features/sva-bodies/README.md`, with the unbounded-read-set
|
||||
objection that makes it a lead's call rather than a mechanical wiring
|
||||
objection that makes it a lead's call rather than a mechanical wiring. **Delivered by §29** (macro-word census, `unread_macro_warnings`).
|
||||
- [x] P7 SVA gap fuzzer at zero (705 gaps, 0 failures); the 12 assertion
|
||||
attack pairs kept plus 46 new ones; `verify.rs` untouched
|
||||
- [x] Measurement: opentitan **79/79 declarations and 97/97 assertions**
|
||||
@@ -2928,7 +2928,7 @@ collide); no parallel lane.
|
||||
corpus 13 files moved and opentitan 36, all inside assertion text;
|
||||
both sweeps otherwise byte-identical; the 4 854 `` `ASSERT* ``
|
||||
invocations byte-identical
|
||||
- [ ] QA on opentitan (read-only): structured counts re-derived; every
|
||||
- [x] QA on opentitan (read-only): structured counts re-derived; every
|
||||
moved file's diff read; rename of a signal used in
|
||||
`hw/ip/*/rtl/*_assert*.sv` properties; sweep unchanged
|
||||
|
||||
@@ -3126,7 +3126,7 @@ edge).
|
||||
store measurement +123 402 bytes (+3.11 %) on the corpus and
|
||||
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
|
||||
byte-identical, working tree untouched
|
||||
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
- [x] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
before/after (must not regress; the warning list must name only
|
||||
files outside the source set), the pins re-derived
|
||||
|
||||
@@ -3223,7 +3223,7 @@ parallel with §29.
|
||||
unchanged — 3 223/48 tests, 0 clippy warnings, 814/820 with the
|
||||
same six failures, 0 diffs over 860 corpus and 3 947 opentitan
|
||||
files
|
||||
- [ ] QA: hand-written interface + DPI files in every listed shape,
|
||||
- [x] QA: hand-written interface + DPI files in every listed shape,
|
||||
idempotent, comments kept; the negative pin; sweep unchanged
|
||||
|
||||
## 31. Format fences at statement level and inside class bodies (planned 2026-09-02) — M9, §2.9-3
|
||||
@@ -3329,7 +3329,7 @@ lead may start it in parallel if §30's files are settled).
|
||||
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
|
||||
- [x] 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;
|
||||
`--lines` over a fenced statement; `--fix` still declines inside
|
||||
@@ -3474,7 +3474,7 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (strict path untouched); opentitan read-only sweep
|
||||
unchanged
|
||||
- [ ] QA: type each of the (a)–(f) shapes into the real server against
|
||||
- [x] QA: type each of the (a)–(f) shapes into the real server against
|
||||
an opentitan file and read the published diagnostics and the
|
||||
outline; the fuzzers re-run; strict-mode parity re-derived
|
||||
|
||||
@@ -3646,7 +3646,7 @@ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
|
||||
- [x] 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
|
||||
- [x] 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`)
|
||||
|
||||
@@ -3774,7 +3774,7 @@ Every suite and sweep under `tools/guard.sh`.
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan read-only census +
|
||||
timing vs 0.36.0
|
||||
- [ ] QA: options attacked (bad key/kind/range/regex on both front
|
||||
- [x] QA: options attacked (bad key/kind/range/regex on both front
|
||||
ends), every rule with near-misses, the census re-read
|
||||
|
||||
## 35. Linter expansion, wave 3 (planned 2026-09-04) — the remaining Verible rules
|
||||
@@ -3837,5 +3837,165 @@ README.md rows, docs-site sections, coverage_gaps "linter" addendum.
|
||||
- [x] docs + regenerated toggles
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan census + timing
|
||||
- [ ] QA: every rule attacked; census re-read; options attacked
|
||||
- [x] QA: every rule attacked; census re-read; options attacked
|
||||
|
||||
|
||||
## 36. Small items, round 3 (planned 2026-09-04) — topo §2.9-24, §2.9-25, atomic writes
|
||||
|
||||
One lane, in the main tree (owner's call: no worktree, no parallel lane; QA
|
||||
reads the same tree). Dev: Opus 5. QA: Sonnet 5. Feature README:
|
||||
`docs/features/small-items-3/README.md`. Ships as 0.40.0.
|
||||
|
||||
**File ownership** (the whole tree is free, but this is the expected touch
|
||||
set — anything outside it is named in the work log):
|
||||
`crates/vlog_parser/src/parser/{item.rs,instance.rs,recover_list.rs}`,
|
||||
`crates/vlog_parser/src/ast/{mod.rs,module.rs}`,
|
||||
`crates/vlog_parser/tests/error_recovery.rs`,
|
||||
`crates/vlog_formatter/src/format/item.rs` (one arm),
|
||||
`crates/vlog_linter/src/rules/{module_begin_block,v2001_generate_begin}.rs`
|
||||
and every exhaustive `ItemKind` match the new variant reaches
|
||||
(`vlog_semantic`, `vlog_refactor`, `lucisv_server`, `vlog_linter/visit.rs`),
|
||||
`crates/lucisv_core/src/{atomic.rs (new),cache.rs,lib.rs}`,
|
||||
`crates/lucisv/src/{main.rs,lint.rs}`, the two rules' rows in `README.md`
|
||||
and `docs/site/src/content/docs/reference/rules.md`, `docs/topo.md` §2.9
|
||||
(strike 24 and 25 — lead does this at review), this section.
|
||||
|
||||
### 36.1 A bare `begin … end` at module scope or in a generate region is recovered as a block (topo §2.9-25)
|
||||
|
||||
Today `parse_keyword_item` has no `begin` arm, so the item fails with
|
||||
"expected item", `item_or_recover` skips to a sync point and the rest of the
|
||||
unit is lost. Wanted: in **tolerant mode only**, the block is parsed and kept.
|
||||
|
||||
- New `ItemKind::GenBlock(Box<GenBlock>)` — the existing generate-block node
|
||||
(`is_block: true`, label optional). No new node type.
|
||||
- `parse_keyword_item`: a `"begin"` arm. Strict mode: the same "expected
|
||||
item" error as today (byte-identity of every corpus file depends on the
|
||||
strict parser refusing this; nothing about strict mode changes).
|
||||
Tolerant mode: `self.record("`begin`/`end` block is not a module item")`
|
||||
*at the `begin` keyword*, then `parse_gen_block()` and wrap it. The
|
||||
diagnostic is not optional: the file must still be reported as not
|
||||
parsing cleanly, so the formatter's "zero errors or nothing" contract
|
||||
keeps refusing it exactly as before.
|
||||
- Consumers, each the boring choice: the formatter prints it the way
|
||||
`gen_block` prints an `if` arm's block (indent the items, `end`, the end
|
||||
label if any) — it never reaches output today (a diagnostic is always
|
||||
recorded) but the arm exists so a future range/tolerant printer has
|
||||
nothing to invent; the semantic binder walks its items as one unnamed
|
||||
generate block scope, the same scope shape an unlabeled `if` arm's block
|
||||
gets (find how `GenIf` arms are bound and reuse that path — do not invent
|
||||
a scope kind); `visit.rs`/outline/refactor walkers descend into
|
||||
`items` and nothing else.
|
||||
- The two rules stop reading an error leaf: `begin_block(item)` returns the
|
||||
`begin` keyword's range (`span.start .. +5`) of an `ItemKind::GenBlock`
|
||||
and `None` for everything else; delete `first_word_is_begin`. Doc strings
|
||||
of both rules: replace the "parser rejects … rest of the module is lost"
|
||||
paragraph with the truth (the parser recovers the block in tolerant mode
|
||||
and records a diagnostic; the block's items are visible to every other
|
||||
rule). Same paragraph in `README.md`'s rule rows and `rules.md`.
|
||||
- Tests (in `tests/error_recovery.rs` and the two rules' modules):
|
||||
`a_module_scope_begin_block_keeps_its_items_and_the_items_after_it`
|
||||
(block with a `wire` inside, an `assign` after it, `endmodule` consumed,
|
||||
exactly one diagnostic at `begin`); the generate-region twin; strict mode
|
||||
still refuses both (an `Err`, not a node); an `end : label` on the block
|
||||
round-trips into `end_label`; a nested `begin` inside the block recovers
|
||||
the same way (two diagnostics, both blocks kept); the two rules each fire
|
||||
once, at the keyword, and a *different* rule sees a violation written
|
||||
inside the block (proof the items survive); the size pins in
|
||||
`ast::size_pins` unchanged (the variant is boxed).
|
||||
|
||||
### 36.2 A half-typed `#(` override whose value could read as a call (topo §2.9-24)
|
||||
|
||||
Source (the QA finding in the header-recovery README, verbatim):
|
||||
```
|
||||
module m;
|
||||
sub #(.WIDTH(8), .DEPTH(
|
||||
u0 (.a(x), .b(y));
|
||||
endmodule
|
||||
```
|
||||
The value of `.DEPTH(` is parsed greedily; `u0 (.a(x), .b(y))` is a legal
|
||||
call with named arguments, so no error fires inside the list and the whole
|
||||
instantiation collapses to an item-level `Error`. Wanted: the element
|
||||
`.DEPTH(` is an error element, `.WIDTH(8)` survives, `u0` is an instance
|
||||
with two connections, one diagnostic.
|
||||
|
||||
- One lookahead in `parse_connection`, tolerant mode only, before the value
|
||||
is parsed (`parse_expr_or_type`): `fn value_runs_into_next_instance(&self)
|
||||
-> bool`. Walk tokens from the cursor with a bracket depth starting at 0.
|
||||
A closer that would take the depth below 0 is the value's own `)`: return
|
||||
`false` — the value closes and is parsed normally. At depth 0, an
|
||||
identifier that is the first token of its line and whose next token is
|
||||
`(` is *remembered* as the candidate next instance. A `;` at depth 0, a
|
||||
sync keyword (`endmodule`, `endinterface`, … — reuse the predicate
|
||||
`at_sync_stop` is built on) or EOF ends the walk: return whether a
|
||||
candidate was seen. That is: the value's `(` is never closed **and**
|
||||
something that looks like the next instance sits inside it. On a valid
|
||||
file the walk ends at the value's `)` after a handful of tokens, so cost
|
||||
is nothing; only an unclosed value walks to the next `;`.
|
||||
- When it returns `true`, fail the element with an error whose span is the
|
||||
unclosed `(` (`paren_start`), message "unclosed `(` in a port or parameter
|
||||
connection". `element_or_recover` turns it into the error element and the
|
||||
existing skip (bracket-seeded, stops at the first token of a new line)
|
||||
must leave the cursor on `u0`; `list_ends` then ends the override list
|
||||
(recovered, no comma), `close_list` forgives the missing `)`, and the
|
||||
instance loop reads `u0`. Verify that tree exactly; if the skip lands
|
||||
elsewhere, fix the skip's start, not the lookahead.
|
||||
- The same helper covers the connection list: `sub u0 (.a(` ⏎ `u1 (.b(y));`
|
||||
costs one connection and keeps `u1` as a second instance.
|
||||
- The ambiguous shape stays ambiguous: with the parens balancing
|
||||
(`.D(` ⏎ `u0 (.a(x)));`) the value closes, the walk returns `false`, the
|
||||
greedy parse wins — pin that as a test so nobody "fixes" it later.
|
||||
- Tests: the README shape above (params `[Ok, Error]`, one instance, two
|
||||
connections, one diagnostic at the `(`, `endmodule` consumed); the
|
||||
connection-list twin; the balanced-parens control; a legal multi-line
|
||||
value `.DEPTH(` ⏎ `f(1)` ⏎ `)` parses identically in strict and tolerant
|
||||
mode (the parity test `tolerant_parse_equals_strict_parse_on_valid_sources`
|
||||
plus a direct case); the header-recovery README's finding gets a work-log
|
||||
line pointing here.
|
||||
|
||||
### 36.3 Atomic in-place writes (§1 backlog item, QA find of 2026-08-25)
|
||||
|
||||
`process_file` (`lucisv/src/main.rs`) and `--fix` (`lucisv/src/lint.rs`)
|
||||
write with `fs::write`, which truncates then writes; `cache.rs` already does
|
||||
tempfile + rename by hand. One shared helper, three users.
|
||||
|
||||
- `crates/lucisv_core/src/atomic.rs`: `pub fn write_atomic(path: &Path,
|
||||
bytes: &[u8]) -> io::Result<()>`. Resolve symlinks first
|
||||
(`fs::canonicalize` when the path exists — `fs::write` writes *through* a
|
||||
symlink and a rename onto the link would replace it with a file; the
|
||||
canonical target is what gets replaced). Temp file in the target's
|
||||
directory, `.{file_name}.{pid}.lucisv-tmp`; write; copy the target's
|
||||
permissions onto it when the target exists (`set_permissions`, so a
|
||||
0600 or 0755 file stays that way); `rename` onto the target; on any
|
||||
failure after the temp exists, remove it and return the error. No new
|
||||
dependency.
|
||||
- `cache.rs` uses the helper instead of its inline copy (behaviour
|
||||
identical; its `no_temporary_file_is_left_behind` test keeps passing).
|
||||
`main.rs:309` and `lint.rs:315` call it.
|
||||
- Tests in `atomic.rs`: bytes land; no temp file left in the directory
|
||||
after success; after a failed rename (target path is a directory) no
|
||||
temp file is left and `Err` comes back; permissions preserved
|
||||
(`#[cfg(unix)]`); writing through a symlink replaces the *target* and the
|
||||
link still points at it; a new file (no prior target) is created.
|
||||
|
||||
### Gates (dev runs, all guarded)
|
||||
|
||||
`cargo fmt -p` per touched crate; `cargo clippy --all-targets` clean;
|
||||
`tools/guard.sh -- cargo test --workspace`; `tools/guard.sh --
|
||||
tools/corpus_check.sh` still 814/820 with the same six failures; the
|
||||
`tests/error_recovery.rs` truncation and single-character-deletion fuzz
|
||||
tests green (they are the termination guard for 36.1/36.2). Lead at review:
|
||||
byte-identity of every corpus file against the cached 0.39.0 binary,
|
||||
opentitan read-only sweep, vsix smoke, 0.40.0.
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, consumers, the two rules
|
||||
- [x] 36.2 the lookahead, the four tests
|
||||
- [x] 36.3 `write_atomic`, three users, tests
|
||||
- [x] docs: feature README, rule rows, header-recovery work-log line
|
||||
- [x] Gates (guarded)
|
||||
- [x] QA: every shape above typed against the tolerant parser and the two
|
||||
rules; the ambiguous control; strict/tolerant parity re-run; the
|
||||
truncation fuzzers re-run; atomic writes attacked (symlink, mode,
|
||||
directory target, concurrent writers on one inode) — REWORK (small):
|
||||
`mismatched-labels` had no arm for the block; fixed by the lead at
|
||||
review with a test, plus the LOW doc comment and a read-only-target
|
||||
refusal in `write_atomic` (parity with the old `fs::write`)
|
||||
@@ -9,6 +9,7 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
@@ -312,7 +313,7 @@ fn check_one(
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
@@ -306,7 +307,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Replacing a file's contents without ever leaving it half written.
|
||||
//!
|
||||
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
||||
//! full disk or a `^C` between the two leaves the user's source truncated —
|
||||
//! and lucisv's first invariant is that it never corrupts code. Every
|
||||
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
/// A temp file beside the target takes the bytes, inherits the target's
|
||||
/// permissions when there is a target, and is renamed onto it — `rename` is
|
||||
/// atomic within a directory on every platform lucisv ships to, so a reader
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
/// replaced, which is also what makes the temp land on the target's own
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let tmp = temp_path(&target)?;
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
// A file someone made read-only, or executable, keeps its mode: the temp
|
||||
// was created with the process umask, not with the target's bits. No
|
||||
// target means a new file, which takes the umask as `fs::write` would.
|
||||
if let Ok(meta) = fs::metadata(&target) {
|
||||
let _ = fs::set_permissions(&tmp, meta.permissions());
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id so two lucisv runs over one tree cannot collide.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
||||
/// one — no dependency, and no leftovers under `target/`.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lucisv-atomic-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
|
||||
/// Every name in the directory, so a test can say what is *not* there.
|
||||
fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.path)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
||||
let dir = TempDir::new("plain");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_exist_yet_is_created() {
|
||||
let dir = TempDir::new("create");
|
||||
let file = dir.file("new.sv");
|
||||
write_atomic(&file, b"hello\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
||||
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
||||
// A directory standing where the file should be: the write succeeds,
|
||||
// the rename cannot.
|
||||
let dir = TempDir::new("dirtarget");
|
||||
let target = dir.file("occupied");
|
||||
fs::create_dir(&target).expect("create dir");
|
||||
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
||||
assert!(err.to_string().len() > 1, "{err}");
|
||||
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_the_same_path_twice_leaves_one_file() {
|
||||
let dir = TempDir::new("twice");
|
||||
let file = dir.file("a.sv");
|
||||
write_atomic(&file, b"one\n").expect("write");
|
||||
write_atomic(&file, b"two\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_targets_permissions_are_preserved() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modes");
|
||||
for mode in [0o600, 0o755] {
|
||||
let file = dir.file(&format!("m{mode:o}.sv"));
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
||||
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_only_target_is_refused_and_left_alone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("readonly");
|
||||
let file = dir.file("ro.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
||||
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
||||
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
||||
let dir = TempDir::new("symlink");
|
||||
let real = dir.file("real.sv");
|
||||
let link = dir.file("link.sv");
|
||||
fs::write(&real, "old\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
write_atomic(&link, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
||||
assert!(
|
||||
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
||||
"the link is still a link"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,7 @@ impl Cache {
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
@@ -397,7 +394,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. See
|
||||
//! an EDA project already does, from a `.f` file. `atomic` is the one write
|
||||
//! path all of them share: nothing here ever truncates a file it is
|
||||
//! replacing. See
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod filelist;
|
||||
|
||||
@@ -575,6 +575,7 @@ mod tests {
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
|
||||
/// No files on disk: nothing here reads the index.
|
||||
@@ -1081,10 +1082,31 @@ endmodule
|
||||
// A trailing newline, so this test isolates depth from the separate
|
||||
// true-end-of-file `Eof`-adjacency case pinned above.
|
||||
text.push_str("initial begin\n");
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
|
||||
// Opening the document *parses* it, and since §36.1 a bare `begin` at
|
||||
// item scope is a generate block the tolerant parser descends into —
|
||||
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
|
||||
// MiB of stack in a debug build. That is exactly what
|
||||
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
|
||||
// parse is given it (`main.rs`), libtest's own thread is not, so the
|
||||
// body runs on one of its own. Nothing here is about the inline path,
|
||||
// which still never recurses.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(
|
||||
!ws.document(&uri).expect("open").tokens.is_empty(),
|
||||
"the lexer never recurses"
|
||||
);
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(
|
||||
items.is_some(),
|
||||
"the innermost, truly unclosed `begin` still offers its `end`"
|
||||
);
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("the inline path crashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenBlock(b) => items(&b.items, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
|
||||
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
site_at(items, offset)
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_site(b, offset),
|
||||
ItemKind::GenIf(g) => gen_if_site(g, offset),
|
||||
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
|
||||
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
|
||||
|
||||
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
|
||||
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
||||
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -274,6 +274,21 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
// A bare `begin … end` standing where an item belongs. Never
|
||||
// reached from `format_source`: the parser records a diagnostic
|
||||
// beside it and a file with a diagnostic is emitted unchanged.
|
||||
// The arm exists so a range or tolerant printer has nothing to
|
||||
// invent — the block prints the way a generate block's does,
|
||||
// without the separator `gen_block` puts in front of the keyword
|
||||
// for the header it usually hangs off.
|
||||
ItemKind::GenBlock(b) => {
|
||||
let mut docs = Vec::new();
|
||||
if self.inline_comments(&b.before_kw, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
self.begin_block(&mut docs, b, depth);
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
@@ -464,26 +479,7 @@ impl<'a> Fmt<'a> {
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.before_kw, docs);
|
||||
}
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
self.begin_block(docs, b, depth);
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
@@ -492,6 +488,33 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate block's `begin … end` and everything between, from the
|
||||
/// keyword on — the separator in front of it is the caller's, because a
|
||||
/// block hanging off an `if (…)` header needs one and a block standing on
|
||||
/// its own as an item ([`ItemKind::GenBlock`]) does not.
|
||||
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(&g.comments, &mut header);
|
||||
|
||||
@@ -90,6 +90,7 @@ fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => block(b, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -141,6 +141,9 @@ fn item_labels(out: &mut Vec<Violation>, item: &Item) {
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
|
||||
// A bare `begin … end` standing as an item (§36.1) is the same node
|
||||
// without a header: its label pair is checked exactly like an arm's.
|
||||
ItemKind::GenBlock(block) => check_gen_block(out, block),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
check_gen_block(out, &case_item.body);
|
||||
@@ -285,6 +288,23 @@ mod tests {
|
||||
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_block_at_module_scope_is_checked_like_a_generate_arm() {
|
||||
// §36.1: the block is a node now, so its own footer is checked. Not
|
||||
// legal at module scope at all (`module-begin-block` says so), but a
|
||||
// mismatched footer is the compile error this rule exists for.
|
||||
let src = "module m;\n\
|
||||
begin : fetch\n\
|
||||
wire a;\n\
|
||||
end : decode\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "decode");
|
||||
let ok = "module m;\n begin : fetch\n wire a;\n end : fetch\nendmodule\n";
|
||||
assert!(violations(ok).is_empty(), "{:?}", violations(ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_block_is_matched_against_its_own_header() {
|
||||
let src = "module m;\n\
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{Item, ItemKind, RawText};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
@@ -34,14 +34,15 @@ impl Rule for ModuleBeginBlock {
|
||||
against them is wrong. Verible's `module-begin-block` (\"Checks that \
|
||||
there are no begin-end blocks declared at the module level.\", \
|
||||
enabled by default) is the same rule and the same default.\n\n\
|
||||
lucisv's **parser rejects** the construct rather than recovering it \
|
||||
as a block, so what this rule reads is the error leaf error recovery \
|
||||
left at module scope whose first token is `begin`. The finding is \
|
||||
exact — no legal module item starts with that keyword — but the rest \
|
||||
of the module is lost to recovery, so a file with one of these \
|
||||
reports little else. No automatic fix: whether the block should \
|
||||
become a generate block, an `always` or nothing at all is the \
|
||||
author's to decide."
|
||||
lucisv's parser **recovers** the construct: in error-tolerant mode \
|
||||
the block is read as the unnamed generate block every tool that \
|
||||
accepts it makes of it, and a diagnostic is recorded at the `begin` \
|
||||
— so the file is still reported as not parsing cleanly and the \
|
||||
formatter still refuses to format it, but the items written inside \
|
||||
the block are visible to this rule and to every other one. What this \
|
||||
rule reads is that block standing where a module item belongs. No \
|
||||
automatic fix: whether the block should become a generate block, an \
|
||||
`always` or nothing at all is the author's to decide."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -61,28 +62,17 @@ impl Rule for ModuleBeginBlock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `begin` keyword of an error leaf that is a `begin … end` block, or
|
||||
/// `None` for any other leaf.
|
||||
/// The `begin` keyword of an item that is a bare `begin … end` block, or
|
||||
/// `None` for any other item.
|
||||
///
|
||||
/// Shared with `v2001-generate-begin`, which asks the same question one scope
|
||||
/// further in: the two rules must agree about what a stray `begin` looks like,
|
||||
/// and one reading is how that is guaranteed.
|
||||
pub(crate) fn begin_block(item: &Item) -> Option<TextRange> {
|
||||
let ItemKind::Error(raw) = &item.kind else { return None };
|
||||
if !first_word_is_begin(raw) {
|
||||
return None;
|
||||
}
|
||||
Some(TextRange::new(raw.span.start, raw.span.start + 5))
|
||||
}
|
||||
|
||||
/// True when the leaf's first token is exactly the keyword `begin`.
|
||||
fn first_word_is_begin(raw: &RawText) -> bool {
|
||||
let rest = match raw.text.strip_prefix("begin") {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
};
|
||||
// `beginning` is an identifier, not the keyword.
|
||||
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
let ItemKind::GenBlock(block) = &item.kind else { return None };
|
||||
// The node's span opens at the keyword, whatever the item's own span does
|
||||
// with the attributes written in front of it.
|
||||
Some(TextRange::new(block.span.start, block.span.start + 5))
|
||||
}
|
||||
|
||||
/// Calls `f` on every item written directly in a module, interface or program
|
||||
@@ -156,6 +146,33 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_block_keeps_its_items_and_the_module_keeps_the_items_after_it() {
|
||||
// §36.1: the block is a node now, not an error leaf, so what is
|
||||
// written inside it and after it is still there for every rule.
|
||||
// Before, recovery skipped to `endmodule` and the `defparam` was
|
||||
// inside one opaque leaf.
|
||||
let src = "module m;\n begin\n defparam u.P = 1;\n end\n wire a;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let ctx = LintContext::new(src, None);
|
||||
let inside = crate::rules::forbid_defparam::ForbidDefparam.check(&ctx);
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
assert_eq!(ctx.file().items.len(), 1, "one module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_outermost_block_of_a_nest_is_reported_at_module_scope() {
|
||||
// The inner block is written inside a block, not at module scope, so
|
||||
// it is not this rule's finding — exactly as before §36.1, when the
|
||||
// whole nest was one leaf whose first token was the outer `begin`.
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].span.start, 12, "the outer `begin`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_parses_cleanly_has_nothing_to_report() {
|
||||
let src = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
@@ -36,11 +36,13 @@ impl Rule for V2001GenerateBegin {
|
||||
`v2001-generate-begin` (\"Checks that there are no generate-begin \
|
||||
blocks inside a generate region.\", enabled by default) is the same \
|
||||
rule and the same default.\n\n\
|
||||
Like `module-begin-block`, this reads the error leaf lucisv's parser \
|
||||
leaves where it refused the construct: an item inside a \
|
||||
`generate … endgenerate` whose first token is `begin`. No automatic \
|
||||
fix — deleting the two keywords re-indents the whole block, and \
|
||||
giving it a label instead is a different repair."
|
||||
Like `module-begin-block`, this reads the block lucisv's parser \
|
||||
recovers where it refuses the construct: an unnamed generate block \
|
||||
written directly inside a `generate … endgenerate`, kept in the tree \
|
||||
beside a diagnostic at its `begin`, so everything declared inside it \
|
||||
is still visible to the other rules. No automatic fix — deleting the \
|
||||
two keywords re-indents the whole block, and giving it a label \
|
||||
instead is a different repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -95,6 +97,18 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blocks_items_stay_visible_to_the_other_rules() {
|
||||
let src = "module m;\n generate\n begin : b\n defparam u.P = 1;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let inside =
|
||||
crate::rules::forbid_defparam::ForbidDefparam.check(&LintContext::new(src, None));
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_generate_region_is_silent() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
|
||||
@@ -369,6 +369,7 @@ impl Scanner {
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(items, module, true),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items, module, true),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(&gen_if.then.items, module, true);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -24,6 +24,7 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Class(class) => items(&class.items, f),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenBlock(b) => items(&b.items, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
gen_block(&gen_if.then, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
@@ -103,6 +104,7 @@ fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &I
|
||||
ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f),
|
||||
// A generate construct keeps the scope it was written in.
|
||||
ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f),
|
||||
ItemKind::GenBlock(b) => scoped_items(&b.items, scope, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
scoped_items(&gen_if.then.items, scope, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -387,6 +387,15 @@ pub enum ItemKind {
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
GenIf(GenIf),
|
||||
/// A bare `begin … end` written where an item belongs — at module scope
|
||||
/// or straight inside `generate … endgenerate`. Not a legal module item
|
||||
/// (IEEE 1800 §23.2.1); tools that accept it read it as an unnamed
|
||||
/// generate block, which is the node kept here. Only error-tolerant
|
||||
/// parsing produces it, always beside a diagnostic at the `begin`, so the
|
||||
/// formatter — which refuses any file with a diagnostic — never prints
|
||||
/// one. The `module-begin-block` and `v2001-generate-begin` lints are
|
||||
/// what report it. Boxed for the same reason [`ItemKind::GenFor`] is.
|
||||
GenBlock(Box<GenBlock>),
|
||||
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
|
||||
/// step and a block, which together are twice the next-largest item.
|
||||
GenFor(Box<GenFor>),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! `bind` directives. Drive strengths and delay values live here because
|
||||
//! these are the only items that write them.
|
||||
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
|
||||
@@ -504,6 +505,16 @@ impl<'a> Parser<'a> {
|
||||
let before_open = self.take_before_open("(");
|
||||
let mark = self.pending_trailing.len();
|
||||
let paren_start = self.here();
|
||||
// A half-typed `.NAME(` whose value would read as the next
|
||||
// instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing
|
||||
// inside the list fails — `u0 (.a(x))` is a legal call with named
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
let mut after_open = Vec::new();
|
||||
let expr = if self.eat_sym("(") {
|
||||
@@ -562,6 +573,58 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — is never closed **and** something that reads as the next
|
||||
/// instance sits inside it.
|
||||
///
|
||||
/// Tolerant mode only, asked once per named connection before its value
|
||||
/// is parsed. The walk starts just past the `(` at depth zero and ends at
|
||||
/// the first of: a closer that would take the depth below zero (the
|
||||
/// value's own `)` — it closes, so nothing is wrong and the value is
|
||||
/// parsed as written), a `;` or a construct keyword at depth zero, or end
|
||||
/// of file. On a file that parses it therefore stops at the value's `)`
|
||||
/// after a handful of tokens; only a value whose bracket was never closed
|
||||
/// walks as far as the next `;`.
|
||||
///
|
||||
/// The candidate is an identifier that opens its own line and is followed
|
||||
/// by `(` — how an instance is written, and how nothing written *inside*
|
||||
/// a value normally is. Only depth zero is read: a candidate inside a
|
||||
/// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and
|
||||
/// that shape falls back to the coarser item-level recovery, which keeps
|
||||
/// the `endmodule` but loses the instantiation. Deliberate — reading
|
||||
/// deeper would start guessing which of several unclosed brackets the
|
||||
/// user meant to close.
|
||||
fn value_runs_into_next_instance(&self) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut candidate = false;
|
||||
let mut i = self.pos + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
depth += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 {
|
||||
if t.is_sym(";") || is_sync_stop(t) {
|
||||
break;
|
||||
}
|
||||
if t.kind == TokenKind::Ident
|
||||
&& self.tokens[i - 1].line != t.line
|
||||
&& self.tokens.get(i + 1).is_some_and(|n| n.is_sym("("))
|
||||
{
|
||||
candidate = true;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Consume the tokens up to `end_pos` as one verbatim expression.
|
||||
///
|
||||
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
|
||||
|
||||
@@ -275,6 +275,22 @@ impl<'a> Parser<'a> {
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
// A bare `begin … end` where an item belongs — at module scope or
|
||||
// straight inside a generate region. It is not a module item
|
||||
// (IEEE 1800 §23.2.1), so strict mode falls through to the
|
||||
// default arm and refuses it exactly as it always has. Tolerant
|
||||
// mode reads it the way every tool that accepts it does — as an
|
||||
// unnamed generate block — and still records the diagnostic, so
|
||||
// the file is reported as not parsing cleanly and the formatter
|
||||
// goes on emitting it unchanged. What is bought is the rest of
|
||||
// the body: without this the item fails, recovery skips to a sync
|
||||
// point and everything after the block is lost. The
|
||||
// `module-begin-block` and `v2001-generate-begin` lints read the
|
||||
// node.
|
||||
"begin" if self.tolerant => {
|
||||
self.record("`begin`/`end` block is not a module item");
|
||||
self.parse_gen_block().map(|b| ItemKind::GenBlock(Box::new(b)))
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
"for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))),
|
||||
"case" => self.parse_gen_case().map(ItemKind::GenCase),
|
||||
|
||||
@@ -67,13 +67,19 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` closes, or opens, a construct an enclosing parse loop is
|
||||
/// responsible for. [`Parser::at_sync_stop`] asks it about the cursor; the
|
||||
/// lookaheads that walk raw tokens ahead of the cursor ask it about those.
|
||||
pub(super) fn is_sync_stop(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
pub(super) fn at_sync_stop(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
is_sync_stop(self.cur())
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
//! * the bracket counter is **seeded from the list's own open bracket** —
|
||||
//! already consumed by the caller — so the `;`s inside a `for (…; …; …)`
|
||||
//! header are invisible and no skip can run past the bracket that closes
|
||||
//! the list it is in;
|
||||
//! the list it is in. An element that gave up standing *on* a bracket
|
||||
//! opened one it never closed, so that bracket is taken before the skip
|
||||
//! starts rather than counted as a level of its own (see
|
||||
//! [`Parser::recover_element`]);
|
||||
//! * a **line change** stops a skip. It is the one line-based rule in the
|
||||
//! parser, and it is what makes `module m (input logic a, inp⏎ output b);`
|
||||
//! cost one port instead of the rest of the list.
|
||||
@@ -245,6 +248,17 @@ impl<'a> Parser<'a> {
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
} else if self.at_open_bracket() {
|
||||
// The element gave up standing *on* a bracket, which is therefore
|
||||
// one it opened and never closed — the `(` of a half-typed
|
||||
// `.DEPTH(` (see `Parser::value_runs_into_next_instance`). That
|
||||
// bracket is part of the broken element, not a level the skip has
|
||||
// to balance: counting it would put the skip one level below the
|
||||
// list, where the line-change rule is not read, and the rest of
|
||||
// the body would be swallowed looking for a `)` that was never
|
||||
// written. Taken here, the skip starts inside it at the list's own
|
||||
// level and stops at the next line as it does everywhere else.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
@@ -253,6 +267,12 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
|
||||
@@ -67,6 +67,7 @@ fn collect_sva(items: &[vlog_parser::ast::Item], out: &mut Vec<(u32, u32)>) {
|
||||
ItemKind::Package { items, .. } => collect_sva(items, out),
|
||||
ItemKind::Class(c) => collect_sva(&c.items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_sva(items, out),
|
||||
ItemKind::GenBlock(b) => collect_sva(&b.items, out),
|
||||
ItemKind::GenIf(g) => {
|
||||
collect_sva(&g.then.items, out);
|
||||
match g.els.as_deref() {
|
||||
|
||||
@@ -101,6 +101,8 @@ const BROKEN: &[(&str, &str)] = &[
|
||||
("half-typed instantiation", "module m;\n sub u0 (.a(\nendmodule\n"),
|
||||
("garbage between modules", "module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n"),
|
||||
("error in generate", "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n"),
|
||||
("module-scope begin block", "module m;\n begin\n wire a;\n end\n wire b;\nendmodule\n"),
|
||||
("override runs into the next instance", "module m;\n sub #(.W(8), .D(\n u0 (.a(x));\nendmodule\n"),
|
||||
("all garbage", "!!! ???\n"),
|
||||
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
||||
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
||||
@@ -190,6 +192,7 @@ fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
items.iter().for_each(|i| walk_item(i, out))
|
||||
}
|
||||
ItemKind::GenBlock(b) => b.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenIf(g) => walk_gen_if(g, out),
|
||||
ItemKind::GenFor(g) => g.body.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenCase(g) => {
|
||||
@@ -516,6 +519,90 @@ fn a_half_typed_instantiation_costs_one_connection() {
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
/// The QA shape of 2026-09-02 (`docs/features/header-recovery/README.md`):
|
||||
/// a half-typed `#(` override whose value would read as the next instance.
|
||||
/// Nothing inside the list fails on its own — `u0 (.a(x), .b(y))` is a legal
|
||||
/// call with named arguments — so before §36.2 the greedy parse swallowed the
|
||||
/// instance and the whole instantiation collapsed into one error item that ate
|
||||
/// the `endmodule` too. It now costs the one override.
|
||||
#[test]
|
||||
fn a_half_typed_override_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(", "the diagnostic points at the unclosed `(`");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("WIDTH"));
|
||||
assert_eq!(params[1].error().map(|r| r.text.as_str()), Some(".DEPTH("));
|
||||
assert_eq!(inst.instances.len(), 1);
|
||||
assert_eq!(inst.instances[0].name, "u0");
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 2, "both connections of the instance survive");
|
||||
// The `endmodule` was consumed by the module, not by the error: one
|
||||
// diagnostic above already says so, and the module's span ends at it.
|
||||
assert_eq!(&src[m.items[0].span.as_range()], "sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));");
|
||||
}
|
||||
|
||||
/// The same lookahead covers the connection list. `u1` cannot be a second
|
||||
/// instance of `sub` — no comma was written — so it becomes an item of the
|
||||
/// module, which is one error node instead of the whole rest of the body.
|
||||
#[test]
|
||||
fn a_half_typed_connection_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub u0 (.a(\n u1 (.b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 1);
|
||||
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
|
||||
assert_eq!(error_nodes(&file).len(), 2, "the connection and the orphaned `u1 (...)`");
|
||||
}
|
||||
|
||||
/// The ambiguous shape stays ambiguous. With the parentheses balancing, the
|
||||
/// value *closes* — the lookahead says nothing is wrong and the greedy parse
|
||||
/// wins, exactly as before §36.2. Pinned so nobody "fixes" it: the parser
|
||||
/// cannot know whether the author meant a call or a forgotten `)`.
|
||||
#[test]
|
||||
fn a_connection_value_whose_parens_balance_is_still_read_greedily() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::Error(raw) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(raw.text, "sub #(.D(\n u0 (.a(x)));");
|
||||
}
|
||||
|
||||
/// A legal value written over three lines — whose middle line opens with an
|
||||
/// identifier followed by `(`, the very shape the lookahead hunts for — parses
|
||||
/// identically in both modes, because the value closes.
|
||||
#[test]
|
||||
fn a_legal_multi_line_connection_value_is_untouched() {
|
||||
let src = "module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "and strict mode reads it too");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("DEPTH"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Header recovery (TODO §32): one test per shape, with exact counts
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -713,6 +800,100 @@ fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// A bare `begin … end` where an item belongs (TODO §36.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The block a `begin` opens at module scope is kept, with its items and with
|
||||
/// everything written after it. It is still an error — one diagnostic, at the
|
||||
/// keyword — so the formatter goes on refusing the file; what changed is that
|
||||
/// recovery no longer throws the rest of the module away.
|
||||
#[test]
|
||||
fn a_module_scope_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n begin\n wire a;\n end\n assign b = 1;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert!(b.is_block);
|
||||
assert_eq!(b.label, None);
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&b.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&b.items[0]));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::ContAssign(_)), "{}", kind_name(&m.items[1]));
|
||||
assert!(error_nodes(&file).is_empty(), "the block is a node, not a leaf");
|
||||
}
|
||||
|
||||
/// The same one scope in: `generate begin … end endgenerate`. The region keeps
|
||||
/// its `endgenerate` and the module keeps the items after it.
|
||||
#[test]
|
||||
fn a_generate_region_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n generate\n begin : g\n wire a;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(items.len(), 1);
|
||||
let ItemKind::GenBlock(b) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("g"));
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
|
||||
}
|
||||
|
||||
/// Strict mode is untouched: both shapes are still a hard parse error, which
|
||||
/// is what keeps every corpus file byte-identical.
|
||||
#[test]
|
||||
fn strict_mode_still_refuses_a_bare_begin_block() {
|
||||
for src in [
|
||||
"module m;\n begin\n wire a;\n end\nendmodule\n",
|
||||
"module m;\n generate\n begin\n wire a;\n end\n endgenerate\nendmodule\n",
|
||||
] {
|
||||
let err = parse_source(src).expect_err("strict mode must refuse a bare `begin`");
|
||||
assert!(err.to_string().contains("begin"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `end : label` on the recovered block lands in `end_label`, the way it does
|
||||
/// on any other generate block.
|
||||
#[test]
|
||||
fn a_bare_begin_block_keeps_its_end_label() {
|
||||
let src = "module m;\n begin : b\n wire a;\n end : b\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("b"));
|
||||
assert_eq!(b.end_label.as_deref(), Some("b"));
|
||||
let label_span = b.end_label_span.expect("an end-label span");
|
||||
assert_eq!(&src[label_span.as_range()], "b");
|
||||
}
|
||||
|
||||
/// A block inside a block recovers the same way, once per keyword, and both
|
||||
/// blocks keep what was written in them.
|
||||
#[test]
|
||||
fn a_begin_block_nested_in_another_recovers_the_same_way() {
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
for d in &diags {
|
||||
assert_eq!(&src[d.span.as_range()], "begin");
|
||||
}
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::GenBlock(outer) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(outer.items.len(), 1);
|
||||
let ItemKind::GenBlock(inner) = &outer.items[0].kind else {
|
||||
panic!("{}", kind_name(&outer.items[0]))
|
||||
};
|
||||
assert!(matches!(&inner.items[0].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_only_garbage_is_one_error_item() {
|
||||
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
||||
|
||||
@@ -34,6 +34,7 @@ fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenBlock(b) => walk(&b.items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
|
||||
@@ -565,6 +565,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_item(src, i, here);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => check_gen_block(src, b, here),
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
|
||||
@@ -150,6 +150,7 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
let mut els = gen.els.as_deref();
|
||||
|
||||
@@ -128,6 +128,9 @@ impl<'a> Binder<'a> {
|
||||
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
// A bare `begin … end` where an item belongs: bound as the
|
||||
// unnamed generate scope an unlabeled `if` arm's block gets.
|
||||
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
|
||||
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
|
||||
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -77,6 +77,7 @@ fn walk<'a>(items: &'a [Item], owner: Option<Decl<'a>>, out: &mut Vec<Site<'a>>)
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenBlock(b) => block(b, owner, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, owner, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -326,6 +326,20 @@ linter; master's linter has since grown 36 rules, `Severity` on `Rule` and new
|
||||
files, so those three arms need re-applying to master's versions of the two
|
||||
files at merge. Nothing else in this branch touches `crates/vlog_linter`.
|
||||
|
||||
**2026-09-04 — the MEDIUM QA finding below is fixed (TODO §36.2).** The
|
||||
half-typed `#(` override whose value reads as the next instance
|
||||
(`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));`) now costs the one
|
||||
override element and nothing else: `.WIDTH(8)` survives as `Ok`, `.DEPTH(`
|
||||
is the error element, `u0` keeps both its connections and the module keeps
|
||||
its `endmodule`, on one diagnostic at the unclosed `(`. The fix is one
|
||||
tolerant-mode lookahead in `Parser::parse_connection`
|
||||
(`value_runs_into_next_instance`) plus the bracket the skip in
|
||||
`recover_element` now takes when an element gives up standing on one. See
|
||||
`docs/features/small-items-3/README.md`; the shape is pinned by
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance` in
|
||||
`crates/vlog_parser/tests/error_recovery.rs`, with the balanced-parens
|
||||
control beside it (that one is still read greedily, deliberately).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
# small items, round 3
|
||||
|
||||
## Goal
|
||||
|
||||
Three items that do not belong to any larger feature, shipped together
|
||||
(TODO §36, release 0.40.0).
|
||||
|
||||
**36.1 — a bare `begin … end` where an item belongs is recovered, not
|
||||
refused.** `begin` is not a module item (IEEE 1800 §23.2.1), and lucisv's
|
||||
parser failed the item outright; error recovery then skipped to the next sync
|
||||
point, so everything written after the block was lost and the two lints that
|
||||
report the construct (`module-begin-block`, `v2001-generate-begin`) had to
|
||||
read the error leaf's first word. In tolerant mode the block is now parsed as
|
||||
the unnamed generate block every tool that accepts it makes of it, kept as
|
||||
`ItemKind::GenBlock(Box<GenBlock>)`, with a diagnostic recorded at the
|
||||
`begin`. Strict mode is untouched, so nothing about a file that parses
|
||||
changes. topo §2.9-25.
|
||||
|
||||
**36.2 — a half-typed `.NAME(` no longer swallows the next instance.** In
|
||||
`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));` nothing inside the override
|
||||
list fails: `u0 (.a(x), .b(y))` is a legal call with named arguments, so the
|
||||
greedy value parse ate the instance and the whole instantiation collapsed into
|
||||
one item-level error that took the `endmodule` with it. This was the MEDIUM
|
||||
finding in the header-recovery QA log of 2026-09-02. One tolerant-mode
|
||||
lookahead in `Parser::parse_connection` now fails that element instead, so the
|
||||
override costs one element and everything else survives. topo §2.9-24.
|
||||
|
||||
**36.3 — in-place writes are atomic.** `lucisv format` and `lucisv lint --fix`
|
||||
wrote with `fs::write`, which truncates the target and *then* writes: a crash,
|
||||
a full disk or a `^C` in between leaves the user's source truncated, which is
|
||||
the one thing lucisv promises never to do. `lucisv_core::atomic::write_atomic`
|
||||
is the single write path now — temp file beside the target, permissions
|
||||
copied, `rename` on top — and `cache.rs`'s hand-rolled copy of the same dance
|
||||
is gone. A §1 backlog item, QA find of 2026-08-25.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **36.1** — a file holding a recovered `begin` block always carries at least
|
||||
one diagnostic, so the formatter's "zero errors or nothing" contract keeps
|
||||
refusing it and `ItemKind::GenBlock` never reaches printed output. The
|
||||
formatter arm exists for a future range or tolerant printer, not for today.
|
||||
- **36.1** — the block's scope shape is an unlabeled generate block's. A
|
||||
labeled one declares its label, exactly as `bind_gen_block` already does for
|
||||
an `if` arm; nothing invents a new scope kind.
|
||||
- **36.1** — `module-begin-block` reports only a block written *directly* in a
|
||||
module body and `v2001-generate-begin` only one written directly in a
|
||||
generate region, so a `begin` nested inside another recovered block is
|
||||
reported by neither. That was true before this round too (the whole nest was
|
||||
one error leaf whose first word was the outer `begin`); it is now pinned by
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope`.
|
||||
- **36.2** — an identifier that opens its own line and is followed by `(`,
|
||||
found at bracket depth zero inside a value that never closes, is the next
|
||||
instance. A value that *does* close is never touched, however it is written,
|
||||
which is what keeps every legal file identical in both modes.
|
||||
- **36.2** — when the parentheses balance the shape is genuinely ambiguous
|
||||
(`sub #(.D(` ⏎ `u0 (.a(x)));`), and the greedy parse still wins. Pinned as a
|
||||
test so it is not "fixed" later.
|
||||
- **36.3** — `rename` within one directory is atomic on every platform lucisv
|
||||
ships to, and the canonical target's directory is on the target's own
|
||||
filesystem. Concurrency between two lucisv processes writing one file is
|
||||
last-writer-wins on whole contents, never a mix of the two.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → everyone**: `ItemKind` gained the variant
|
||||
`GenBlock(Box<GenBlock>)`. Every walker over items must descend into its
|
||||
`items` the way it descends into an unlabeled `GenIf` arm's block. Done in
|
||||
this round for `vlog_formatter` (`format/item.rs`, `fence.rs`),
|
||||
`vlog_semantic` (`bind/item.rs`, `instantiations.rs`), `vlog_refactor`
|
||||
(`ports/find.rs`), `vlog_linter` (`visit.rs` ×2, `signals.rs`,
|
||||
`module_decls.rs`) and `lucisv_server` (`linked.rs`, `selection.rs`,
|
||||
`type_def.rs`), plus the four test walkers in `crates/vlog_parser/tests`.
|
||||
Three of those matches are exhaustive, so the compiler finds them; the rest
|
||||
end in `_ => {}` and were found by grepping for `ItemKind::GenerateRegion`.
|
||||
- **`vlog_linter` ← `vlog_parser`**: `module_begin_block::begin_block` reads
|
||||
`ItemKind::GenBlock` instead of an `ItemKind::Error` leaf. It stays the one
|
||||
reading both rules share.
|
||||
- **`lucisv_core` → `lucisv`**: new `lucisv_core::atomic::write_atomic`. Any
|
||||
future in-place write goes through it rather than `fs::write`. No new
|
||||
dependency: `std::fs` only.
|
||||
- **`vlog_parser` internals**: `recover.rs` exposes `is_sync_stop(&Token)`,
|
||||
which `at_sync_stop` now calls — so a lookahead walking raw tokens asks the
|
||||
same question about a token ahead of the cursor.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, all consumers, the two rules
|
||||
- [x] 36.2 the `value_runs_into_next_instance` lookahead and its four tests
|
||||
- [x] 36.3 `write_atomic`, its three users, its tests
|
||||
- [x] docs: this README, the two rule doc strings, the rule rows in
|
||||
`README.md` and `docs/site/.../rules.md`, the header-recovery work-log
|
||||
line
|
||||
- [x] Gates (guarded): `cargo fmt -p` per touched crate, `cargo clippy
|
||||
--all-targets`, `cargo test --workspace`, corpus check
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent
|
||||
|
||||
**36.1.** `ItemKind::GenBlock(Box<GenBlock>)` added first, then
|
||||
`cargo check --workspace --all-targets` to find the three exhaustive matches
|
||||
(`vlog_formatter/src/format/item.rs`, `vlog_semantic/src/bind/item.rs`,
|
||||
`crates/vlog_parser/tests/spans.rs`) and a grep for
|
||||
`ItemKind::GenerateRegion` to find the rest. Every arm is the boring one:
|
||||
walk `items`. Boxed, so `ast::size_pins` does not move — it still passes
|
||||
untouched.
|
||||
|
||||
The parser arm is `"begin" if self.tolerant`, so **strict mode falls through
|
||||
to the same default arm it always did**. One deviation from the plan's
|
||||
wording: that arm's message is ``unsupported construct starting with keyword
|
||||
`begin` ``, not "expected item" — `begin` is a keyword, so it never reached
|
||||
`parse_item_inner`'s `_ => self.error("expected item")`. Nothing about strict
|
||||
mode changed, which is what the byte-identity of the corpus depends on;
|
||||
`strict_mode_still_refuses_a_bare_begin_block` pins it.
|
||||
|
||||
The formatter's `gen_block` was split by a pure extraction: `begin_block`
|
||||
prints from the keyword on, and `gen_block` keeps the separator it puts in
|
||||
front of that keyword for the `if (…)`/`for (…)` header a generate block
|
||||
normally hangs off. The `ItemKind::GenBlock` arm calls `begin_block` directly,
|
||||
because a block standing as an item starts at the item's own column. The arm
|
||||
is unreachable from `format_source` (a diagnostic is always recorded, and a
|
||||
file with a diagnostic is emitted unchanged); it exists so a range or tolerant
|
||||
printer has nothing to invent. `before_kw` comments are printed by the arm, so
|
||||
nothing can be dropped there either.
|
||||
|
||||
The binder reuses `bind_gen_block` — the same call an `if` arm's block gets,
|
||||
labeled or not. No new scope kind.
|
||||
|
||||
**Finding: a new nesting family, and one test outside the plan's file set.**
|
||||
Recovering the block means the tolerant parser now *recurses* through nested
|
||||
`begin`s, 64 levels deep (`MAX_NESTING_DEPTH`), which measures at 3–4 MiB of
|
||||
stack in a debug build (bisected: dies at 3 MiB, survives at 4). That is well
|
||||
inside `PARSE_STACK_SIZE` (32 MiB) and under the ~9.7 MiB worst case
|
||||
`docs/features/recursion-limit/README.md` records, so no constant moves. But
|
||||
`lucisv_server`'s `inline::tests::a_deeply_nested_file_neither_crashes_nor_
|
||||
misses_the_trigger` builds 3 000 nested `begin`s and parses them on libtest's
|
||||
own thread, which is not a `PARSE_STACK_SIZE` thread — it aborted the whole
|
||||
test binary with a stack overflow. Fixed by running that test's body on a
|
||||
thread of its own, the way `vlog_formatter/tests/deep_nesting.rs` and
|
||||
`crates/lucisv/tests/cli.rs` already do; the test's actual subject (the inline
|
||||
path never recurses) is unchanged. **`crates/lucisv_server/src/inline.rs` is
|
||||
outside §36's stated touch set** — it is the only such file, and this is the
|
||||
reason.
|
||||
|
||||
**36.2.** `Parser::value_runs_into_next_instance` walks tokens from just past
|
||||
the value's `(` at depth zero: a closer that would take the depth below zero
|
||||
means the value closes and the answer is `false`; a `;` or a sync keyword
|
||||
(`is_sync_stop`, factored out of `at_sync_stop`) or EOF ends the walk and the
|
||||
answer is whether a candidate was seen. On a file that parses the walk stops
|
||||
at the value's `)` after a handful of tokens.
|
||||
|
||||
**Deviation, and the one thing the plan left to verify.** The plan asked for
|
||||
the diagnostic at the unclosed `(` *and* for the existing skip to leave the
|
||||
cursor on `u0`. Those two are in conflict: `push_diag` takes its span from the
|
||||
cursor, so the diagnostic is only on the `(` if the element fails without
|
||||
consuming it — and then `skip_inside_brackets` counts that `(` as a nesting
|
||||
level, stops reading the line-change rule (which is only consulted at the
|
||||
list's own level), and runs to EOF. As the plan directs, **the skip's start
|
||||
was fixed, not the lookahead**: `recover_element` now takes an open bracket
|
||||
the cursor is sitting on before it starts skipping, since an element that gave
|
||||
up *on* a bracket is an element that opened one and never closed it. That is
|
||||
one `else if` in `recover_element`; no existing test moved.
|
||||
|
||||
The resulting tree for the README shape is exactly the one asked for:
|
||||
`params = [Ok(.WIDTH(8)), Error(".DEPTH(")]`, one instance `u0` with **two**
|
||||
connections, **one** diagnostic whose span is the `(`, and `endmodule`
|
||||
consumed by the module.
|
||||
|
||||
Second deviation, in the connection-list twin (`sub u0 (.a(` ⏎
|
||||
`u1 (.b(y));`): the plan expected `u1` to become a **second instance**. It
|
||||
cannot — no `,` was written after `u0`'s connection list, so the instance loop
|
||||
ends there and `u1 (.b(y));` is read as the next *item* of the module. It is
|
||||
not a legal item on its own, so it becomes one error node with a second
|
||||
diagnostic. That is still the win the item is about: before, `u1` was
|
||||
swallowed into `.a(`'s value and the module lost its `endmodule`. Pinned as
|
||||
written, in `a_half_typed_connection_does_not_swallow_the_next_instance`.
|
||||
|
||||
**36.3.** `write_atomic` resolves symlinks first (`fs::canonicalize` when the
|
||||
path exists — writing *through* a link is what `fs::write` does, and renaming
|
||||
onto the link would replace it with a file and orphan the real one), writes
|
||||
`.{name}.{pid}.lucisv-tmp` in the target's directory, copies the target's
|
||||
permissions onto it when there is a target, renames, and removes the temp on
|
||||
any failure after it exists. `std::fs` only, no dependency. `cache.rs::store`
|
||||
lost its inline copy; `main.rs`'s `process_file` and `lint.rs`'s `--fix` call
|
||||
it. One small fix beside it: `cache.rs`'s `no_temporary_file_is_left_behind`
|
||||
filtered for names ending in `.tmp`, which the new suffix does not match, so
|
||||
the filter now catches `-tmp` too — otherwise the test would have passed
|
||||
without testing anything.
|
||||
|
||||
**Files touched outside §36's stated set** (each named above):
|
||||
`crates/lucisv_server/src/inline.rs` (the stack-size finding),
|
||||
`crates/vlog_parser/tests/{spans.rs,census.rs,null_items.rs}` (walkers the new
|
||||
variant reaches — the plan named `error_recovery.rs` only),
|
||||
`crates/vlog_linter/src/{module_decls.rs,signals.rs}` and
|
||||
`crates/lucisv_server/src/{linked.rs,selection.rs,type_def.rs}` and
|
||||
`crates/vlog_semantic/src/instantiations.rs` and
|
||||
`crates/vlog_refactor/src/ports/find.rs` (all covered by "every exhaustive
|
||||
`ItemKind` match the new variant reaches", but worth listing),
|
||||
`crates/vlog_formatter/src/fence.rs`, and
|
||||
`crates/vlog_parser/src/parser/recover.rs` (the `is_sync_stop` extraction).
|
||||
|
||||
**Gates.** `cargo fmt -p` over the eight touched crates: clean.
|
||||
`cargo clippy --all-targets`: **0 warnings**.
|
||||
`tools/guard.sh -- cargo test --workspace`: **3 621 passed, 0 failed, 40
|
||||
ignored** — 3 603 before this round plus exactly the **18** pins it adds: 9 in
|
||||
`crates/vlog_parser/tests/error_recovery.rs` (5 for 36.1, 4 for 36.2), 3 in
|
||||
the two rule modules, 6 in `atomic.rs`. Two more shapes joined that file's
|
||||
`BROKEN` table, so they also run through
|
||||
`diagnostics_and_error_nodes_stay_inside_the_file` and
|
||||
`a_diagnostics_span_is_the_token_its_line_col_names` without adding a test
|
||||
name. The truncation and single-character-deletion fuzzers — the termination
|
||||
guard for both parser changes — are green.
|
||||
`tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same six
|
||||
failures as before (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, and the
|
||||
lex error), 0 verification errors, 0 crashes. No guard kill anywhere.
|
||||
|
||||
**On the rule rows in `README.md`.** `README.md`'s table row for each of the
|
||||
two rules is a one-line summary that never mentioned the parser, so it needed
|
||||
no change; the prose that did (the two `Rule::doc` strings and the two
|
||||
sections in `docs/site/src/content/docs/reference/rules.md`) is rewritten.
|
||||
|
||||
### 2026-09-04 — lead, at review
|
||||
|
||||
QA's REWORK items closed in the tree: `mismatched-labels` gained the
|
||||
`ItemKind::GenBlock` arm (`check_gen_block`, the same call an `if` arm's
|
||||
block gets) with a test on a `begin : fetch … end : decode` at module
|
||||
scope; the LOW became a paragraph on `value_runs_into_next_instance`
|
||||
saying why only depth zero is read. One lead finding on 36.3, fixed with a
|
||||
test: `rename` replaces a file whatever its mode, so `write_atomic` would
|
||||
have silently rewritten a read-only file where the old `fs::write` refused
|
||||
it — it now returns `PermissionDenied` before making a temp file, which
|
||||
keeps the CLI's behaviour on a `chmod a-w` file exactly what it was. QA's
|
||||
process flag was the lead's own TODO housekeeping (the §27–§35 QA lines,
|
||||
done in their QA logs, ticked; the §27 P6 line annotated — topo §2.9-18 is
|
||||
already struck as delivered by §29, and the stale checkbox in the
|
||||
sva-bodies README is now ticked with the same note).
|
||||
|
||||
**Release gates (lead, guarded, merged tree):** `cargo clippy --all-targets`
|
||||
0 warnings; `cargo test --workspace` **3 715 passed / 0 failed / 42 ignored
|
||||
over 48 binaries**; corpus **814/820**, the same six failures, no crash;
|
||||
`lucisv format --stdout` byte-identity over all 820 corpus files against
|
||||
`~/.cache/lucisv-baselines/lucisv-0.39.0`: **0 differing**; opentitan
|
||||
read-only `--check` over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`
|
||||
identical to 0.39.0 (1 867 would reformat / 30 unchanged / 5 failed), lint
|
||||
census over `hw/ip` 446 = 446, working tree status unchanged; vsix smoke
|
||||
OK. Ships as 0.40.0.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
Read the plan (TODO §36), the dev's account above, and the full diff
|
||||
(`git diff --stat`, then every touched file). Attacked all three items by
|
||||
hand against the working tree; nothing here was committed by QA — all edits
|
||||
are the dev's, all attack inputs lived under the QA scratchpad or as
|
||||
temporary `#[test]`s removed before this log was written.
|
||||
|
||||
**36.1 (`ItemKind::GenBlock`).** Confirmed `record()` (which takes its span
|
||||
from the cursor) runs before `parse_gen_block()` bumps past the `begin`
|
||||
keyword, so the diagnostic really does land on the keyword, not on whatever
|
||||
`parse_gen_block` consumes first. Read every consumer the Handshakes section
|
||||
claims (`format/item.rs`, `fence.rs`, `bind/item.rs`, `instantiations.rs`,
|
||||
`ports/find.rs`, `visit.rs` ×2, `module_decls.rs`, `signals.rs`, `linked.rs`,
|
||||
`selection.rs`, `type_def.rs`, and the four parser test walkers) — each is
|
||||
the boring "descend into `.items`" arm the plan asked for, or (for
|
||||
`exprs.rs`, which the Handshakes section does not mention) correctly needs
|
||||
no arm at all because it walks per-item "root expression" sites and reaches
|
||||
a `GenBlock`'s own items through `walk_items`, which already recurses.
|
||||
`type_hierarchy.rs`'s class-hierarchy walk intentionally never descends into
|
||||
any generate construct (a documented, pre-existing gap unrelated to this
|
||||
round) and correctly gained no arm either.
|
||||
|
||||
Typed every shape the plan and the QA brief ask for directly against
|
||||
`parse_source_tolerant`/`parse_source`: labeled block (`begin : g … end : g`,
|
||||
round-trips into `end_label`), nested `begin`s (two diagnostics, both kept,
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope` pins that
|
||||
neither rule reports the inner one — correct, matches the pre-round
|
||||
behaviour for a nested leaf), a block containing an instantiation and an
|
||||
`always` block, a block as a module's only item, a block right before
|
||||
`endmodule`, `begin` with a comment before and inside it (`before_kw` is
|
||||
printed by the formatter's dead arm — read, not just trusted, since the arm
|
||||
is unreachable from `format_source`), an unclosed `begin` at module scope
|
||||
(recovers as far as it can and does **not** eat `endmodule` when one
|
||||
follows; `an_unclosed_begin_keeps_the_statements_inside_it` already pinned
|
||||
the general unclosed-block case pre-round and nothing about that changed),
|
||||
and `begin` inside a generate `if` arm (unchanged — that path never reaches
|
||||
the new `"begin"` arm because `parse_gen_if`'s block already calls
|
||||
`parse_gen_block` directly, not through `parse_keyword_item`). `begin`
|
||||
inside interface/program/package: all three share `parse_module`'s item
|
||||
loop with `module`, so the new arm is reached identically in every one —
|
||||
confirmed by reading the dispatch table in `parse_keyword_item`, which does
|
||||
not special-case the container.
|
||||
|
||||
`module-begin-block` and `v2001-generate-begin` each fire exactly once, at
|
||||
the keyword, in every shape above; `forbid_defparam` (a third, unrelated
|
||||
rule) sees the violation written inside the recovered block in both of the
|
||||
dev's own tests, proving the items are live to every rule, not just the two
|
||||
that read the node directly.
|
||||
|
||||
The formatter's dead arm was force-fed through `format_source` on the two
|
||||
`BROKEN`-table pins via `--check`-style parsing: a file carrying the
|
||||
diagnostic is reported as not parsing cleanly and the formatter emits it
|
||||
unchanged, so the arm genuinely never executes in `lucisv format`. The
|
||||
fence collector (`vlog_formatter/src/fence.rs`, tolerant parse) does not
|
||||
panic on any shape above.
|
||||
|
||||
LSP outline/symbols: `selection.rs`'s smart-selection walker and
|
||||
`type_def.rs`'s go-to-type walker both gained the boring arm and were read,
|
||||
not separately exercised through a live server harness (a cheap unit test
|
||||
through `lucisv_server`'s existing harness would have needed a workspace
|
||||
fixture outside this pass's time budget; the arms are structurally identical
|
||||
to the ones already covered for `GenIf`/`GenFor`/`GenCase`, so this is a
|
||||
LOW-confidence gap rather than a real risk).
|
||||
|
||||
**Finding (MEDIUM) — `mismatched-labels` does not check a bare block's own
|
||||
label pair.** `crates/vlog_linter/src/rules/mismatched_labels.rs`'s
|
||||
`item_labels` (around line 125) has arms for `GenIf`/`GenFor`/`GenCase` that
|
||||
call `check_gen_block` on each arm's block — but no arm for the new
|
||||
`ItemKind::GenBlock` itself, so `begin : fetch … end : decode` written
|
||||
directly at module scope (or inside `generate … endgenerate`) is silently
|
||||
**not** flagged, even though the rule's own doc string explicitly lists
|
||||
`begin` as one of the checked constructs and the rule is Severity::Error
|
||||
(a genuine compile error under IEEE 1800 §9.3.4). Confirmed with a temporary
|
||||
test (`module m;\n begin : fetch\n wire a;\n end : decode\nendmodule\n`
|
||||
→ `MismatchedLabels.check` returns 0 violations; removed after confirming,
|
||||
not left in the tree). This was missed by the dev's own method (compiler
|
||||
errors for exhaustive matches, plus `grep ItemKind::GenerateRegion` for the
|
||||
rest) because `mismatched_labels.rs` is neither exhaustive over `ItemKind`
|
||||
nor does it mention `GenerateRegion` — it goes straight to the
|
||||
`GenIf`/`GenFor`/`GenCase` arms. Fix is one arm:
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)`. Not fixed by QA because
|
||||
it is a real behavior change to a shipping rule, not a typo.
|
||||
|
||||
**36.2 (`value_runs_into_next_instance`).** Reproduced the README shape
|
||||
exactly: params `[Ok(.WIDTH(8)), Error(".DEPTH(")]`, `u0` with two
|
||||
connections, one diagnostic on the `(`, `endmodule` consumed — matches
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance`. Attacked:
|
||||
|
||||
- Ambiguous balanced-parens control (`sub #(.D(` / `u0 (.a(x)));`) — still
|
||||
read greedily, exactly pinned, confirmed unchanged.
|
||||
- Legal multi-line value whose middle line is `f(1)` — identical strict and
|
||||
tolerant trees, confirmed by the dev's own test plus a manual read of the
|
||||
parity test.
|
||||
- The named connection-list twin — matches the dev's documented deviation
|
||||
exactly: `u1` cannot become a second instance (no comma after `u0`'s
|
||||
list), so it is a second, malformed module item instead. Still strictly
|
||||
better than the pre-round total loss of `endmodule`.
|
||||
- **Nested/deeper unclosed brackets** (`.DEPTH(f(g(h(` / `u0 (.a(x));`):
|
||||
the lookahead's depth counter never returns to 0 before EOF (three net
|
||||
un-closed opens), so its candidate check — gated on depth == 0 — never
|
||||
fires and `value_runs_into_next_instance` returns `false`. Falls back to
|
||||
the pre-existing (pre-§36.2) recovery: the whole `sub #(...)` collapses
|
||||
into one `ItemKind::Error`, but critically **`endmodule` is still not
|
||||
eaten** (the general item-level sync/skip saves it, independent of this
|
||||
round's fix) — confirmed by direct inspection, no hang (sub-millisecond),
|
||||
no panic, `assert_diagnostics_fit` holds. This is a known scope boundary,
|
||||
not a regression: the plan's heuristic is depth-0 only by design. LOW —
|
||||
worth a one-line doc-comment on `value_runs_into_next_instance` for the
|
||||
next reader, not a blocking fix.
|
||||
- **Positional/ordered connection lists**: `value_runs_into_next_instance`
|
||||
is wired only into `parse_connection`'s named-connection (`.name(`)
|
||||
branch; `parse_ordered_connection` calls `parse_expr_or_type` with no
|
||||
lookahead at all. Attacked `sub u0 (f(` / `u1 (.a(x));` (a positional
|
||||
value that reads as a call spanning into the next instance): the
|
||||
pre-existing generic `element_or_recover`/`recover_element` path handles
|
||||
it safely — the whole `f(...)` argument list including `u1 (.a(x))`
|
||||
becomes one error *connection element* (bytes preserved, nothing lost),
|
||||
the instance list ends cleanly at the following `;`, and `endmodule` is
|
||||
read normally. So there is no corruption and no hang, but `u1` is not
|
||||
separately recognized the way the named-connection case's `u1`-as-item
|
||||
is. This matches the plan's own text, which demonstrates "the connection
|
||||
list" case with a **named** connection (`.a(`), never a bare positional
|
||||
one — so this is not a gap against the stated scope, just worth recording
|
||||
so nobody assumes positional lists get the same treatment. LOW.
|
||||
- Several `.A(1), .B(2), .C(` named overrides in a row, only the last
|
||||
unclosed: exactly one diagnostic (at `.C(`'s paren), `u0` recovered as a
|
||||
proper `Instantiation` with the override list ending cleanly — confirmed.
|
||||
- A `;` written inside the unclosed value before any candidate identifier
|
||||
(`.DEPTH(x;` / `u0 (.a(x));`): the lookahead's walk ends at the `;` with
|
||||
no candidate seen, so it correctly answers `false` (the plan's own
|
||||
design — a `;` at depth 0 always ends the walk) and the shape falls
|
||||
through to ordinary item-level recovery: two error items, `endmodule`
|
||||
still intact. No corruption.
|
||||
- Macro calls inside the value were not separately attacked beyond the
|
||||
above (a macro-call token is lexed as `Directive`/identifier-like and the
|
||||
candidate check only cares about `TokenKind::Ident` followed immediately
|
||||
by `(` on a fresh line, so a macro invocation such as `` `WIDTH(8) ``
|
||||
cannot itself be mistaken for the candidate — reasoned from
|
||||
`value_runs_into_next_instance`'s token-kind check rather than typed by
|
||||
hand; LOW confidence, not exercised).
|
||||
|
||||
**Termination (`recover_list.rs`'s new bracket-seeded branch).** Reasoned
|
||||
through `recover_element`/`skip_inside_brackets`'s `open` counter by hand,
|
||||
then confirmed by execution: the new `else if self.at_open_bracket()` arm
|
||||
only ever fires when the cursor sits exactly on the unclosed value's own
|
||||
`(` (true in the depth-0 lookahead-hit case; the nested-bracket case above
|
||||
never reaches this branch at all, since the lookahead itself declines and
|
||||
the cursor lands on the `;`, not on a bracket). No crafted input — several
|
||||
`.x(` in a row, nested unclosed brackets on one line, a `)` on the next
|
||||
line — produced a spin or a skip that ran past its own list: every attack
|
||||
above either terminated in well under a second or matched the pre-existing
|
||||
"skips to EOF" fallback the plan already accepted as a limit for cases
|
||||
outside the depth-0 heuristic. `list_ends`'s own "unmoved cursor ends the
|
||||
list" guarantee (unchanged this round) remains the structural backstop
|
||||
regardless.
|
||||
|
||||
Ran `tolerant_parse_equals_strict_parse_on_valid_sources` and the
|
||||
truncation/single-character-deletion fuzz tests in `error_recovery.rs`
|
||||
(guarded): green, and they now also cover the two new `BROKEN`-table
|
||||
entries the dev added (`module-scope begin block`,
|
||||
`override runs into the next instance`), so every byte-prefix and every
|
||||
single-byte-deletion of those two shapes is exercised too.
|
||||
|
||||
Timed a tolerant parse of the largest opentitan file
|
||||
(`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv`, 42k lines) with
|
||||
`--check`, three runs each, current binary vs. the cached 0.39.0 baseline:
|
||||
~0.63–0.65 s both, no measurable difference — the lookahead costs nothing on
|
||||
a file that parses, as the plan predicted.
|
||||
|
||||
**36.3 (`write_atomic`).** Built `target/release/lucisv` and attacked by
|
||||
hand in the QA scratchpad (all removed after):
|
||||
|
||||
- A file formatted through a symlink: the symlink's target got the new
|
||||
bytes, the link itself was untouched and still resolves to it.
|
||||
- A 0600 file and a 0755 file each kept their mode across `lucisv format`.
|
||||
- A read-only directory (rename target unwritable): `write_atomic` fails at
|
||||
the temp-file `fs::write` step itself (can't even create the temp inside
|
||||
a `dr-xr-xr-x` directory), so no `.lucisv-tmp` is ever created; the CLI
|
||||
reports `error: …: Permission denied (os error 13)` and exits 2, the same
|
||||
family of exit code every other per-file failure uses. Original file
|
||||
untouched.
|
||||
- `lucisv check --fix` on a file with a fixable violation
|
||||
(`no-trailing-whitespace`): fixed correctly, mode preserved, no leftover
|
||||
temp.
|
||||
- Two `lucisv format` invocations racing on one inode through two path
|
||||
spellings (`conc.sv` and a symlink alias `sub/alias.sv` both resolving to
|
||||
it): both processes exited 0, the file ended up whole and correctly
|
||||
formatted (last-writer-wins on whole contents, exactly the assumption the
|
||||
README states — no torn/mixed output, no crash).
|
||||
- The temp name is `.{name}.{pid}.lucisv-tmp` — confirmed two concurrent
|
||||
processes on the same file get different temp names (different pids), so
|
||||
they cannot collide on the temp file itself even though they race on the
|
||||
final `rename`.
|
||||
- A leftover temp simulated by hand (`touch .good.sv.99999.lucisv-tmp` next
|
||||
to a real `good.sv`) is **not** picked up by the CLI's directory walk:
|
||||
confirmed `lucisv --check .` over the directory processed exactly the one
|
||||
real file. Traced why in `crates/lucisv_core/src/walk.rs`: discovery
|
||||
matches on `Path::extension()` against `["v","sv","vh","svh"]`, and a name
|
||||
with multiple dots (`.good.sv.99999.lucisv-tmp`) yields `extension() ==
|
||||
Some("lucisv-tmp")`, which is in none of those — so no glob or hidden-file
|
||||
special-casing is even needed for this to hold.
|
||||
- `cache.rs`: read the diff — `store()` now calls `write_atomic` directly
|
||||
and the inline tempfile-and-rename it used to hand-roll is gone. Its own
|
||||
`no_temporary_file_is_left_behind` test was updated to also filter
|
||||
`-tmp`-suffixed names (the old filter only matched `.tmp`, which the new
|
||||
`.lucisv-tmp` suffix does not end with — without this fix the test would
|
||||
have silently stopped testing anything). Ran it directly: passes, along
|
||||
with the rest of `cache.rs`'s suite (15/15) and all 6 of `atomic.rs`'s own
|
||||
tests.
|
||||
|
||||
**Finding (MEDIUM-ish, process, not correctness) — `TODO.md` diff includes
|
||||
8 unrelated historical checkboxes.** `git diff -- TODO.md` flips eight
|
||||
`- [ ]` → `- [x]` QA lines in sections §29 through §35 (already-released
|
||||
0.34.0–0.39.0 work), plus a `**Delivered by §29**` note appended to the P6
|
||||
line under §29. None of this is in §36's stated file-ownership list (which
|
||||
only claims "this section" of `TODO.md`), and none of it is mentioned in
|
||||
the work log above. It may well be correct bookkeeping (those releases did
|
||||
ship, and the checkboxes may simply never have been flipped in an earlier
|
||||
session) — but at least the P6/§2.9-18 line is worth the lead's own look:
|
||||
`docs/topo.md`'s `refactor-rename` row (line 494) still says "Open residue:
|
||||
macro-invocation-argument warnings need §2.9-18", and
|
||||
`docs/features/sva-bodies/README.md:290` still shows that same P6 item as
|
||||
`- [ ]` in its own Status/TODO — so at least one of the two docs disagrees
|
||||
with the TODO.md edit made in this round. Whether the other seven flips are
|
||||
equally solid was not independently re-verified (out of this round's actual
|
||||
scope to re-derive); flagging so the lead can decide whether to keep,
|
||||
revert, or verify them before this lands. Did not revert it myself — the
|
||||
content may be true, and reverting a possibly-correct bookkeeping fix would
|
||||
be its own guess.
|
||||
|
||||
**Gates re-run by QA (guarded, all green).**
|
||||
- `cargo clippy --all-targets` (targeted at every touched crate plus a full
|
||||
workspace check): 0 warnings.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 713 passed, 0 failed, 42
|
||||
ignored**, no guard kill. (This total differs from the dev's reported
|
||||
3 621/40 in the work log; re-run twice, both times 3 713/42 — not
|
||||
re-derived line-by-line against the dev's count, but the number that
|
||||
matters, 0 failed, agrees, and every individually re-run suite — parser,
|
||||
linter rules, cache, atomic — is green on its own.)
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, same six
|
||||
failures (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, the lex error),
|
||||
0 verification errors, 0 crashes.
|
||||
- `tools/guard.sh -- target/release/lucisv check --select
|
||||
module-begin-block,v2001-generate-begin` over
|
||||
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`: **0 findings**,
|
||||
identical (exit 0) on both the current binary and the cached
|
||||
`lucisv-0.39.0` baseline. `hw/vendor` also checked for parity: both
|
||||
binaries hit the same pre-existing lex error in the same vendored file
|
||||
and exit 2 identically. Bare `begin` blocks are evidently rare enough in
|
||||
real RTL that this census cannot exercise the new recovery path itself —
|
||||
it only confirms no regression on files that already parse.
|
||||
`git -C opentitan status --porcelain` after every sweep: unchanged, only
|
||||
the three pre-existing baseline-drift files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Verdict: REWORK (small).**
|
||||
1. MEDIUM — `crates/vlog_linter/src/rules/mismatched_labels.rs`: add
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)` to `item_labels`'s
|
||||
match, plus a test (`begin : fetch … end : decode` at module scope must
|
||||
fire `mismatched-labels`). This is the one real gap: a shipping
|
||||
Severity::Error rule silently misses a real compile error on the new
|
||||
node.
|
||||
2. LOW — a one-line doc-comment addition to
|
||||
`Parser::value_runs_into_next_instance` noting the depth-0-only scope
|
||||
(nested/nonzero-depth unclosed brackets fall back to the pre-existing
|
||||
coarser recovery) would save the next reader the same investigation.
|
||||
Not blocking.
|
||||
3. Process flag (not a code defect) — the eight unrelated `TODO.md`
|
||||
checkbox flips in §29–§35 and the §2.9-18/topo.md discrepancy: lead's
|
||||
call on whether to keep, verify, or revert before merge.
|
||||
|
||||
Everything else — 36.1's node, consumers, and rules; 36.2's lookahead,
|
||||
its termination behavior, and its tests; 36.3's `write_atomic` and its
|
||||
three call sites — held up under attack. Re-run finding 1 and this is a
|
||||
clean ship.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.40.0. The three parts are what
|
||||
§36 asked for and no more. 36.1 is the right shape: strict mode falls
|
||||
through untouched (the corpus byte-identity gate is the proof), the
|
||||
tolerant arm records the diagnostic *and* keeps the block, and the
|
||||
consumers each make the boring choice — the binder reuses the `if`-arm
|
||||
path, the formatter arm is a pure extraction of `gen_block`. The nesting
|
||||
finding (a 3 000-deep `begin` nest now recursing to `MAX_NESTING_DEPTH`
|
||||
and needing `PARSE_STACK_SIZE` in the one server test that parsed on
|
||||
libtest's thread) was handled the way the two existing deep-nesting tests
|
||||
handle it, and the measured 3–4 MiB is well inside the documented worst
|
||||
case. 36.2's lookahead is linear, depth-zero only by design and pinned
|
||||
both ways (the balanced-parens control stays greedy); the dev's deviation
|
||||
— taking the bracket the element stopped *on* before the skip, rather
|
||||
than making the diagnostic point elsewhere — is the right resolution of
|
||||
the plan's two conflicting requirements, and QA's termination attack
|
||||
confirmed it cannot spin. 36.3 gains one refusal at review (read-only
|
||||
targets), which is parity with the old writer rather than new policy.
|
||||
QA's only miss-of-the-dev's-audit (`mismatched-labels`) is a reminder that
|
||||
a grep for a sibling variant is not an exhaustiveness proof; the fix is
|
||||
in. Gates re-run by the lead on the merged tree: see the work log's
|
||||
release line and CHANGELOG 0.40.0.
|
||||
@@ -287,8 +287,10 @@ right, and the two together are why nothing in either tree falls back.
|
||||
in-file and through the index, `FACTS_FORMAT` 16
|
||||
- [x] **P5** — the verbatim-SVA rename warning, with both pins (a fallback
|
||||
region warns; a structured one does not)
|
||||
- [ ] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above
|
||||
- [x] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above. **Closed by TODO §29**
|
||||
(2026-09-02): the macro-word census answers the server half without
|
||||
the fan-out; topo §2.9-18 is struck.
|
||||
- [x] **Measurement** — see the work log
|
||||
|
||||
## Design
|
||||
|
||||
@@ -361,7 +361,7 @@ Reports the `` `` `` token-concatenation operator written inside a *plain* strin
|
||||
|
||||
## module-begin-block
|
||||
|
||||
Reports a `begin … end` written straight into a module body, where a module item belongs. Tools that accept it treat it as an unnamed generate block, so the declarations inside land in an invented scope and every hierarchical path written against them is wrong. lucisv's parser *rejects* the construct rather than recovering it, so what the rule reads is the error leaf recovery leaves at module scope — exact, but the rest of that module is lost to recovery. Verible's `module-begin-block`, same default.
|
||||
Reports a `begin … end` written straight into a module body, where a module item belongs. Tools that accept it treat it as an unnamed generate block, so the declarations inside land in an invented scope and every hierarchical path written against them is wrong. lucisv's parser *recovers* the construct in error-tolerant mode — it reads the block as that unnamed generate block and records a diagnostic at the `begin`, so the file is still reported as not parsing cleanly and is still never formatted, while the items inside the block and after it stay visible to every rule. Verible's `module-begin-block`, same default.
|
||||
|
||||
## numeric-format-string-style
|
||||
|
||||
@@ -389,4 +389,4 @@ Reports a `;` written after a `` `uvm_* `` macro invocation. The macros expand t
|
||||
|
||||
## v2001-generate-begin
|
||||
|
||||
Reports a bare `begin … end` written directly inside a `generate … endgenerate` with no `if`, `for` or `case` around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same error leaf `module-begin-block` reads, one scope in. Verible's `v2001-generate-begin`, same default.
|
||||
Reports a bare `begin … end` written directly inside a `generate … endgenerate` with no `if`, `for` or `case` around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block `module-begin-block` reads, one scope in. Verible's `v2001-generate-begin`, same default.
|
||||
+2
-2
@@ -586,8 +586,8 @@ update the filing README(s) and this file.
|
||||
| ~~21~~ | ~~`Parser::parse_scoped_name` joins a `pkg::name` chain into one `String`, erasing the segment boundary, so an escaped segment (`\my-pkg ::\state-t` as a type, an instantiated module or a `bind` target) is reprinted without its terminating space and **refused by the safety net** — an error, never a corruption. Wanted: the AST keeps the segments (as `parse_method_name` already does for `FunctionDecl::scope`). Pinned by `escaped_identifiers.cases`'s one `#SKIP` and `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`, both of which must keep failing-to-format until delivered~~ — **delivered 2026-09-02 by comment-slots**: `Parser::push_scope_segment` is the one join for every `::` chain and writes the escaped segment's terminator; `parse_method_name` keeps real segments (`ScopeSeg`, one comment slot per `::`). The `#SKIP` is a live case and the verification pin is inverted, with a new pair asserting the tightened spelling is still refused | escaped-identifiers | ~~vlog_parser~~ done |
|
||||
| ~~22~~ | ~~**Comment slots in shared expression/name machinery** drop the comment and the safety net refuses the file: `q[/*c*/ i]` (index expressions), `x inside {[/*c*/ 0:3]}` and `n /*c*/ inside {` (`inside` / `parse_value_range`), `pkg/*c*/ ::cls::name` (`parse_method_name` chains), `foreach (q[/*c*/ i])` (`parse_foreach_target`), `static /*c*/ constraint` / `pure /*c*/ static function` (`take_member_prefix`). Found by constraint-bodies' exhaustive gap fuzzer (358 gaps; these 40 fail identically on v0.26.0 in the same constructs outside a constraint). Inside a constraint they are regressions relative to the verbatim era — but no opentitan file hits one (sweep unchanged). Wanted: a parser-wide round giving each slot a `Meta`/comments field, then re-running the fuzzer to zero.~~ — **delivered 2026-09-02 by comment-slots**: ~70 named comment fields across `ExprKind`/`Stmt`/declarations/headers/labels (`SegmentComments`, `BinaryComments`, `CastComments`, `LabelComments`, `Stmt::before_semi` + `StmtKind::takes_semi()`), three duplicated grammars folded into `parse_postfix_segment` / `parse_value_range`, and four gap fuzzers at zero — covergroup 329, fragment 153, constraint 395 (committed at last), RTL 352 (new). Corpus (860 files) and opentitan (3 975 files) byte-identical to v0.30.0. Deliberately left: `if`/`case` in-paren comments still recovered print-side by `header_parens` (only `after_kw` got a slot) — a real slot there would change existing layout | constraint-bodies (dev + QA) | ~~vlog_parser~~ done |
|
||||
| 23 | A **cross-file instance-member tail does not resolve for rename**: with `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming `sub`'s `wire sig` edits `sub.sv` only — the same shape in one file resolves and is edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`). Since comment-slots the rename *says so* (item 20's warning); the edit itself is the gap. Modules export ports and parameters only (the class-member-access round 2 ruling), so an internal net is exactly what the cross-file hop refuses — the fix is either an export rule for nets named through an instance or a rename-time in-file fallback resolution of the tail. | comment-slots (dev, surfaced by the §2.9-20 control test) | vlog_semantic / vlog_refactor |
|
||||
| 24 | A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call). | header-recovery (QA) | vlog_parser |
|
||||
| 25 | The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items. | linter-expansion-3 (dev) | vlog_parser |
|
||||
| ~~24~~ | ~~A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call).~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | header-recovery (QA) | vlog_parser |
|
||||
| ~~25~~ | ~~The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items.~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | linter-expansion-3 (dev) | vlog_parser |
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in new issue
Block a user