Add error-recovery and format-fences (jointly: entangled in format.rs)
error-recovery (vlog_parser): parse_source_tolerant never fails —
errors become positioned ParseDiagnostics and ItemKind::Error /
StmtKind::Error leaves (raw text + span, nesting invariant intact),
with recovery at documented sync tokens, bracket-balanced skipping,
and stray-closer collapse. Strict parse_source is byte-identical in
behavior (shared grammar, tolerant flag). Guarantees tested:
tolerant==strict on 500 valid sources; depth/links budgets neither
reset nor leak across recovery (mutation-tested); no panic across
27k+ truncation cuts, every single-char fixture deletion, 1MB of
semicolons (500k recoveries, 344ms). The future LSP parses mid-edit
code; the formatter still refuses on the first error.
format-fences (vlog_formatter): // verilog_format: off|on and
// vfmt: off|on emit fenced item ranges as exact source bytes via
spans (Doc::Verbatim), Verible-style item-level regions per scope,
unmatched off to end of scope, byte-exact including indentation and
idempotent at every join (24 adversarial probes). ~2000 corpus fence
injections: zero region byte changes, zero new verification
failures. verify.rs untouched; with no fences output is
byte-identical (corpus TSV md5 unchanged).
Also surfaced and queued in TODO: comment-in-list refusals
(112/1868 injection trials) and the double-blank leading-comment
nit — the next comments round.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{error-recovery,format-fences}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
901a78ccb2
commit
02f68655b5
16 files changed
+3069
-70
No files matched your search
@@ -107,6 +107,30 @@ configurable via `--indent` / `--line-length` or a `vfmt.toml`, see
|
||||
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
|
||||
through verbatim
|
||||
|
||||
### Turning the formatter off
|
||||
|
||||
Items between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
comment are emitted as the exact source bytes they were written with,
|
||||
indentation included — the escape hatch for hand-aligned tables and the
|
||||
like. `// vfmt: off` / `// vfmt: on` is an accepted alias.
|
||||
|
||||
```systemverilog
|
||||
module m;
|
||||
// verilog_format: off
|
||||
localparam int A = 1; // hand-aligned, left alone
|
||||
localparam int LONGER = 22;
|
||||
// verilog_format: on
|
||||
localparam int B = 3; // formatted normally
|
||||
endmodule
|
||||
```
|
||||
|
||||
The fence must be a line comment on its own line, and its text must match
|
||||
exactly — `// vfmt: off for now` is an ordinary comment, not a fence. An
|
||||
`off` with no matching `on` runs to the end of the enclosing item list
|
||||
(module body, package body, generate block, or the file). Fences select
|
||||
whole items; one written between two *statements* has no effect yet. Full
|
||||
rules: `docs/features/format-fences/README.md`.
|
||||
|
||||
## Supported syntax
|
||||
|
||||
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
|
||||
@@ -43,12 +43,15 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
|
||||
## 2. Formatter features
|
||||
|
||||
- [ ] **[V] Format-off fences.** Support `// verilog_format: off` /
|
||||
- [x] **[V] Format-off fences.** Support `// verilog_format: off` /
|
||||
`// verilog_format: on` (accept a `vfmt: off/on` alias). Verible
|
||||
implements this as "emit the original byte range verbatim" — the trivia
|
||||
in `Meta` already carries comments, so detect fences during formatting in
|
||||
`format.rs` and splice source text by span. Requires nodes to carry
|
||||
byte spans (see §5, it's needed for LSP anyway).
|
||||
→ `crates/vlog_formatter/src/fence.rs`; grammar, item-level semantics and
|
||||
join rules in `docs/features/format-fences/README.md`. Item scopes only —
|
||||
statement-level fences are documented as not implemented.
|
||||
- [ ] **[V] Range formatting: `--lines M-N[,M-N...]`.** Format only
|
||||
constructs intersecting the given line ranges; emit everything else
|
||||
verbatim. This is what makes adoption in dirty legacy codebases possible
|
||||
@@ -64,6 +67,16 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
and localparam/parameter lists. This needs original-spacing info
|
||||
preserved through the lexer — record "excess spaces before token" as
|
||||
trivia.
|
||||
- [ ] **Comment inside port/param lists and assignment patterns is
|
||||
dropped → refused** (found at scale by format-fences QA: 112 of 1868
|
||||
corpus injection trials refuse with exit 2). The failsafe holds, but
|
||||
this is the largest remaining comment-attachment gap; fix alongside the
|
||||
three documented expression refusals (replication, compact bracket,
|
||||
assign-value) from docs/features/formatter-bug-fixes and corpus-bugs.
|
||||
- [ ] **Two leading comments separated by one blank line come out
|
||||
separated by two** (format-fences QA find, pre-existing): `leading`
|
||||
pushes a HardLine after each comment and a BlankLine before the next.
|
||||
Fix churns snapshots; take it with the comments round above.
|
||||
- [x] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix
|
||||
`patch` mode: print a unified diff instead of rewriting, for CI logs and
|
||||
code review.
|
||||
@@ -209,11 +222,16 @@ later:
|
||||
token, comment and node; `vlog_parser::line_index::LineIndex` for
|
||||
offset↔line:col; token-level losslessness is a test
|
||||
(`crates/vlog_parser/tests/spans.rs`).
|
||||
- [ ] **Error-tolerant parsing mode.** A formatter may refuse broken input;
|
||||
- [x] **Error-tolerant parsing mode.** A formatter may refuse broken input;
|
||||
an LSP cannot — code is mid-edit most of the time. Add recovery in
|
||||
`parser.rs`: on statement-level error, record a diagnostic, skip to a
|
||||
sync token (`;`, `end`, `endmodule`), continue. Formatter keeps requiring
|
||||
zero errors; the LSP consumes the partial tree.
|
||||
→ `vlog_parser::parse_source_tolerant(src) -> (SourceFile,
|
||||
Vec<ParseDiagnostic>)`; unparsable ranges become `ItemKind::Error` /
|
||||
`StmtKind::Error` leaves. Sync tokens, the four guarantees and the
|
||||
deliberate gaps (no tolerant *lexer*, no recovery inside headers or lists)
|
||||
in `docs/features/error-recovery/README.md`. `parse_source` unchanged.
|
||||
- [ ] **Keep the CST lossless.** Current design (trivia in `Meta`) is
|
||||
format-oriented; verify every source byte is reachable from the tree
|
||||
(tokens + trivia + spans). A `reconstruct(tree) == input` round-trip test
|
||||
|
||||
@@ -25,6 +25,12 @@ pub enum Doc {
|
||||
Concat(Vec<Doc>),
|
||||
/// Emitted only when the enclosing group is broken.
|
||||
IfBreak(String),
|
||||
/// Source bytes copied through untouched, newlines and all, starting at
|
||||
/// column 0: the indentation the preceding line break wrote is stripped
|
||||
/// first, so the text keeps its own. Always forces enclosing groups to
|
||||
/// break. Only valid right after a line break or at the start of the
|
||||
/// output — see `docs/features/format-fences/README.md`.
|
||||
Verbatim(String),
|
||||
}
|
||||
|
||||
pub fn text(s: impl Into<String>) -> Doc {
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//! `// verilog_format: off` / `// verilog_format: on` fences.
|
||||
//!
|
||||
//! A fenced region is emitted as the exact source bytes it was written with,
|
||||
//! so nothing inside it is ever laid out. This module answers the two
|
||||
//! questions that makes possible: which comments are fences, and which byte
|
||||
//! ranges they select. Full spec: `docs/features/format-fences/README.md`.
|
||||
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
/// Which side of a fence a comment spells.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Fence {
|
||||
/// `// verilog_format: off` — stop formatting here.
|
||||
Off,
|
||||
/// `// verilog_format: on` — resume formatting here.
|
||||
On,
|
||||
}
|
||||
|
||||
/// The fence a comment spells, if it spells one exactly.
|
||||
///
|
||||
/// The match is exact after trimming, not a prefix: a comment that merely
|
||||
/// starts with a fence (`// vfmt: off-by-one`) is an ordinary comment, because
|
||||
/// a fence firing by accident is worse than one that never fires.
|
||||
pub fn fence_of(text: &str) -> Option<Fence> {
|
||||
match text.strip_prefix("//")?.trim() {
|
||||
"verilog_format: off" | "vfmt: off" => Some(Fence::Off),
|
||||
"verilog_format: on" | "vfmt: on" => Some(Fence::On),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A range of source bytes to emit exactly as written.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Region {
|
||||
/// First byte of the `off` fence comment itself — the region's identity,
|
||||
/// and what tells the one comment that *opens* a region from the ones it
|
||||
/// merely contains.
|
||||
pub fence: usize,
|
||||
/// First byte emitted: the start of the fence's line, so the region keeps
|
||||
/// its own indentation on its first line too.
|
||||
pub start: usize,
|
||||
/// One past the last byte emitted.
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
/// Every fenced region in `file`, sorted and non-overlapping.
|
||||
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
|
||||
let mut found = Vec::new();
|
||||
scan_scope(src, &file.items, &file.dangling, &mut found);
|
||||
found.sort_by_key(|r| r.fence);
|
||||
// A region inside an already-fenced range never runs: the items holding
|
||||
// it are emitted as source bytes, so they are never formatted. Dropping
|
||||
// those leaves a list sorted by both ends, which is what makes the
|
||||
// lookup below a binary search.
|
||||
let mut regions: Vec<Region> = Vec::new();
|
||||
for r in found {
|
||||
if regions.last().is_none_or(|prev| r.fence >= prev.end) {
|
||||
regions.push(r);
|
||||
}
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// The region containing byte `pos`, if any. `regions` must come from
|
||||
/// [`collect`].
|
||||
pub fn region_at(regions: &[Region], pos: usize) -> Option<&Region> {
|
||||
let i = regions.partition_point(|r| r.end <= pos);
|
||||
regions.get(i).filter(|r| r.fence <= pos)
|
||||
}
|
||||
|
||||
/// Scan one item-list scope, then its nested scopes.
|
||||
///
|
||||
/// The scope is a flat stream of units — each item's leading comments, then
|
||||
/// the item's own code — followed by the dangling comments. A region opens at
|
||||
/// the first `off` in that stream and closes at the first `on` after it;
|
||||
/// anything else, including a second `off`, is just text.
|
||||
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
|
||||
let mut open: Option<Region> = None;
|
||||
let mut scope_end = 0usize;
|
||||
for item in items {
|
||||
for c in &item.meta.leading {
|
||||
// An attribute followed by a comment puts a "leading" comment
|
||||
// *after* the item's span starts. Opening a region there would
|
||||
// emit the attribute twice, so such comments are not fences.
|
||||
if c.span.start < item.span.start {
|
||||
step(src, c, &mut open, out);
|
||||
}
|
||||
}
|
||||
// A leading comment always ends before its item's code does, so the
|
||||
// item's own end is the scope's high-water mark.
|
||||
scope_end = item.span.end as usize;
|
||||
}
|
||||
for c in dangling {
|
||||
step(src, c, &mut open, out);
|
||||
scope_end = c.span.end as usize;
|
||||
}
|
||||
if let Some(mut r) = open {
|
||||
// An unmatched `off` runs to the end of the scope. The last item's
|
||||
// span stops before the comment trailing it on the same line, and
|
||||
// `Meta.trailing` has no span to consult, so that comment has to be
|
||||
// picked up from the source or it would be dropped.
|
||||
r.end = with_trailing_comments(src, scope_end);
|
||||
out.push(r);
|
||||
}
|
||||
for item in items {
|
||||
scan_nested(src, item, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the open/closed state by one comment unit.
|
||||
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
|
||||
let start = c.span.start as usize;
|
||||
match (fence_of(&c.text), open.is_some()) {
|
||||
(Some(Fence::Off), false) => {
|
||||
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
|
||||
}
|
||||
(Some(Fence::On), true) => {
|
||||
if let Some(mut r) = open.take() {
|
||||
r.end = c.span.end as usize;
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Item scopes nested inside one item. Statement bodies are not scanned:
|
||||
/// statement-level fences are out of scope (see the feature README).
|
||||
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
||||
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for i in &g.items {
|
||||
scan_gen_block(src, &i.body, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_gen_if(src: &str, g: &GenIf, out: &mut Vec<Region>) {
|
||||
scan_gen_block(src, &g.then, out);
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => scan_gen_if(src, inner, out),
|
||||
Some(GenElse::Block(b)) => scan_gen_block(src, b, out),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `begin`…`end` is an item scope; a bodyless `if (X) item;` is
|
||||
/// not — its one item has no list for a fence to end in, and the formatter
|
||||
/// lays it out inside a `Group`. Its nested scopes are still scanned.
|
||||
fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
|
||||
if b.is_block {
|
||||
scan_scope(src, &b.items, &b.dangling, out);
|
||||
} else {
|
||||
for item in &b.items {
|
||||
scan_nested(src, item, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of the line `at` sits on, when nothing but whitespace precedes it
|
||||
/// there — otherwise `at` itself, so a fence sharing its line with another
|
||||
/// comment does not swallow it.
|
||||
fn line_start(src: &str, at: usize) -> usize {
|
||||
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
|
||||
match src.get(bol..at) {
|
||||
Some(before) if before.chars().all(char::is_whitespace) => bol,
|
||||
_ => at,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extend `end` over the comments written after it on the same line.
|
||||
fn with_trailing_comments(src: &str, end: usize) -> usize {
|
||||
let mut at = end;
|
||||
loop {
|
||||
let Some(rest) = src.get(at..) else { return at };
|
||||
let spaces = rest.len() - rest.trim_start_matches([' ', '\t']).len();
|
||||
let rest = &rest[spaces..];
|
||||
if let Some(body) = rest.strip_prefix("//") {
|
||||
// A line comment ends the line, so nothing else can follow it.
|
||||
let len = body.find('\n').unwrap_or(body.len());
|
||||
return trim_end(src, at + spaces + 2 + len);
|
||||
}
|
||||
match rest.strip_prefix("/*").and_then(|b| b.find("*/")) {
|
||||
Some(i) => at += spaces + 2 + i + 2,
|
||||
None => return at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk `end` back over spaces and tabs, so a region never ends in whitespace
|
||||
/// the comment's own span would have dropped.
|
||||
fn trim_end(src: &str, end: usize) -> usize {
|
||||
let bytes = src.as_bytes();
|
||||
let mut end = end.min(bytes.len());
|
||||
while end > 0 && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
|
||||
end -= 1;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn both_spellings_and_both_sides_are_fences() {
|
||||
assert_eq!(fence_of("// verilog_format: off"), Some(Fence::Off));
|
||||
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
|
||||
assert_eq!(fence_of("// vfmt: off"), Some(Fence::Off));
|
||||
assert_eq!(fence_of("// vfmt: on"), Some(Fence::On));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surrounding_whitespace_is_trimmed() {
|
||||
assert_eq!(fence_of("//vfmt: off"), Some(Fence::Off));
|
||||
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
|
||||
assert_eq!(fence_of("//\tvfmt: off"), Some(Fence::Off));
|
||||
assert_eq!(fence_of("// vfmt: on "), Some(Fence::On));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_else_is_an_ordinary_comment() {
|
||||
// Trailing text disqualifies a fence: an accidental switch is worse
|
||||
// than one that never fires.
|
||||
assert_eq!(fence_of("// vfmt: off (for now)"), None);
|
||||
assert_eq!(fence_of("// vfmt: off-by-one bug here"), None);
|
||||
// The match is exact, not fuzzy.
|
||||
assert_eq!(fence_of("// vfmt:off"), None);
|
||||
assert_eq!(fence_of("// vfmt : off"), None);
|
||||
assert_eq!(fence_of("// verilog_format off"), None);
|
||||
assert_eq!(fence_of("// VFMT: OFF"), None);
|
||||
assert_eq!(fence_of("// verilog_lint: waive x"), None);
|
||||
// Block comments are not fences.
|
||||
assert_eq!(fence_of("/* vfmt: off */"), None);
|
||||
assert_eq!(fence_of("/* verilog_format: off */"), None);
|
||||
assert_eq!(fence_of("// vfmt: off\n// vfmt: on"), None);
|
||||
assert_eq!(fence_of(""), None);
|
||||
assert_eq!(fence_of("// off"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_line_starts_at_its_indentation() {
|
||||
let src = "module m;\n // vfmt: off\n";
|
||||
let at = src.find("//").expect("fence");
|
||||
assert_eq!(line_start(src, at), src.find(" //").expect("indent"));
|
||||
// Not when another comment shares the line.
|
||||
let src = "module m;\n /* a */ // vfmt: off\n";
|
||||
let at = src.find("//").expect("fence");
|
||||
assert_eq!(line_start(src, at), at);
|
||||
// At the very start of the file.
|
||||
assert_eq!(line_start("// vfmt: off\n", 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_comments_extend_a_scope_end() {
|
||||
let src = "wire a; // note\nendmodule\n";
|
||||
let end = src.find(" //").expect("comment");
|
||||
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; // note");
|
||||
// Block comments, including several, and multi-line ones.
|
||||
let src = "wire a; /* x */ /* y */\n";
|
||||
let end = src.find(" /*").expect("comment");
|
||||
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; /* x */ /* y */");
|
||||
let src = "wire a; /* x\n y */\nendmodule\n";
|
||||
let end = src.find(" /*").expect("comment");
|
||||
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; /* x\n y */");
|
||||
// Code on the same line is not absorbed.
|
||||
let src = "wire a; endmodule\n";
|
||||
let end = src.find(" endmodule").expect("kw");
|
||||
assert_eq!(with_trailing_comments(src, end), end);
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@
|
||||
//! on a single line, cuddled `begin`/`end`.
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::{contains_hard_line, Printer};
|
||||
use crate::verify::{
|
||||
line_starts_inside_string, verify_convergence, verify_equivalence, VerificationError,
|
||||
};
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -72,7 +74,8 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
let fmt = Fmt { _cfg: config };
|
||||
let regions = fence::collect(source, &file);
|
||||
let fmt = Fmt { _cfg: config, src: source, regions };
|
||||
let doc = fmt.file(&file);
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print(&doc);
|
||||
@@ -86,6 +89,19 @@ fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Err
|
||||
|
||||
struct Fmt<'a> {
|
||||
_cfg: &'a Config,
|
||||
/// The text the AST was parsed from — what `// verilog_format: off`
|
||||
/// regions are spliced out of.
|
||||
src: &'a str,
|
||||
/// The fenced regions of `src`, sorted and non-overlapping.
|
||||
regions: Vec<Region>,
|
||||
}
|
||||
|
||||
/// What a comment turns into: itself, the verbatim region it opens, or
|
||||
/// nothing at all because a region already covers its bytes.
|
||||
enum Slot<'r> {
|
||||
Normal,
|
||||
Opens(&'r Region),
|
||||
Covered,
|
||||
}
|
||||
|
||||
/// One operator of a flattened binary chain, with the comments written on
|
||||
@@ -184,16 +200,57 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
// ------------------------------------------------------------------
|
||||
// Format-off fences
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What to do with one comment, given the fenced regions of the source.
|
||||
fn slot(&self, c: &Comment) -> Slot<'_> {
|
||||
match fence::region_at(&self.regions, c.span.start as usize) {
|
||||
None => Slot::Normal,
|
||||
Some(r) if r.fence == c.span.start as usize => Slot::Opens(r),
|
||||
Some(_) => Slot::Covered,
|
||||
}
|
||||
}
|
||||
|
||||
/// True if this node's code is inside a fenced region, i.e. its bytes are
|
||||
/// already being emitted verbatim and it must not be formatted.
|
||||
fn is_fenced(&self, span: TextRange) -> bool {
|
||||
fence::region_at(&self.regions, span.start as usize).is_some()
|
||||
}
|
||||
|
||||
/// A fenced region's source bytes.
|
||||
///
|
||||
/// A slice that is not on a character boundary cannot happen — every
|
||||
/// offset comes from a span or from a scan over ASCII delimiters — but if
|
||||
/// it ever did, an empty region loses tokens and `verify_equivalence`
|
||||
/// rejects the output, which is the failsafe. Better that than a panic.
|
||||
fn verbatim(&self, r: &Region) -> Doc {
|
||||
Doc::Verbatim(self.src.get(r.start..r.end).unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node, with any
|
||||
/// fenced region they open spliced in as source bytes.
|
||||
fn leading_comments(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, c) in meta.leading.iter().enumerate() {
|
||||
if i > 0 && c.blank_before {
|
||||
for c in &meta.leading {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
if !docs.is_empty() && c.blank_before {
|
||||
docs.push(Doc::BlankLine);
|
||||
}
|
||||
docs.push(self.comment(c));
|
||||
docs.push(doc);
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = self.leading_comments(meta);
|
||||
for attr in &meta.attrs {
|
||||
docs.push(self.raw_text(attr));
|
||||
docs.push(Doc::HardLine);
|
||||
@@ -324,15 +381,20 @@ impl<'a> Fmt<'a> {
|
||||
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
|
||||
}
|
||||
|
||||
/// Sequence of items/statements at one indent level, preserving single
|
||||
/// blank lines between them.
|
||||
/// Sequence of items at one indent level, preserving single blank lines
|
||||
/// between them. An item a fenced region swallowed emits nothing, and
|
||||
/// contributes no separator either.
|
||||
fn item_seq(&self, items: &[Item]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
for item in items {
|
||||
let item_docs = self.item_docs(item);
|
||||
if item_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.item(item));
|
||||
docs.extend(item_docs);
|
||||
}
|
||||
docs
|
||||
}
|
||||
@@ -351,12 +413,13 @@ impl<'a> Fmt<'a> {
|
||||
fn dangling(&self, comments: &[Comment]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for c in comments {
|
||||
if c.blank_before {
|
||||
docs.push(Doc::BlankLine);
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.comment(c));
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
docs.push(doc);
|
||||
}
|
||||
docs
|
||||
}
|
||||
@@ -367,17 +430,45 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn file(&self, f: &SourceFile) -> Doc {
|
||||
let mut docs = self.item_seq(&f.items);
|
||||
for (i, c) in f.dangling.iter().enumerate() {
|
||||
if !docs.is_empty() || i > 0 {
|
||||
for c in &f.dangling {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
if !docs.is_empty() {
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.comment(c));
|
||||
docs.push(doc);
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn item(&self, item: &Item) -> Doc {
|
||||
self.with_meta(&item.meta, self.item_kind(&item.kind))
|
||||
concat(self.item_docs(item))
|
||||
}
|
||||
|
||||
/// One item: its leading comments, then — unless a fenced region is
|
||||
/// already emitting its bytes — its attributes, code and trailing
|
||||
/// comment. Comments before the `off` fence are still emitted; comments
|
||||
/// are never dropped.
|
||||
fn item_docs(&self, item: &Item) -> Vec<Doc> {
|
||||
let mut docs = self.leading_comments(&item.meta);
|
||||
if self.is_fenced(item.span) {
|
||||
// The last comment asked for a line break before code that is not
|
||||
// coming. Whoever emits the next unit separates it itself.
|
||||
if matches!(docs.last(), Some(Doc::HardLine)) {
|
||||
docs.pop();
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
for attr in &item.meta.attrs {
|
||||
docs.push(self.raw_text(attr));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.item_kind(&item.kind));
|
||||
docs.extend(self.trailing(&item.meta));
|
||||
docs
|
||||
}
|
||||
|
||||
fn item_kind(&self, kind: &ItemKind) -> Doc {
|
||||
@@ -397,6 +488,9 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::Directive(d) => self.raw_text(d),
|
||||
// Only error-tolerant parsing builds these, and `format_source`
|
||||
// parses strictly, so this arm exists to keep the match total.
|
||||
ItemKind::Error(d) => self.raw_text(d),
|
||||
ItemKind::MacroItem(m) => self.macro_call(m),
|
||||
ItemKind::Import(paths) => text(format!("import {};", paths.join(", "))),
|
||||
ItemKind::Timeunit(t) => text(format!("{t};")),
|
||||
@@ -1466,6 +1560,9 @@ impl<'a> Fmt<'a> {
|
||||
StmtKind::Continue => text("continue;"),
|
||||
StmtKind::Disable(name) => text(format!("disable {name};")),
|
||||
StmtKind::Directive(d) => self.raw_text(d),
|
||||
// See `ItemKind::Error`: unreachable from `format_source`, present
|
||||
// so the match stays total.
|
||||
StmtKind::Error(d) => self.raw_text(d),
|
||||
StmtKind::MacroStmt(m) => self.macro_call(m),
|
||||
StmtKind::Assert { kw, cond, then, els } => {
|
||||
let mut docs = vec![text(format!("{kw} ")), self.parens(cond)];
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Formatter engine: document IR + printer + formatting rules.
|
||||
|
||||
pub mod doc;
|
||||
pub mod fence;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod verify;
|
||||
|
||||
@@ -77,6 +77,15 @@ impl Printer {
|
||||
col += s.chars().count();
|
||||
}
|
||||
}
|
||||
Doc::Verbatim(s) => {
|
||||
// Undo the indent the preceding line break wrote: these
|
||||
// bytes carry their own.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out.push_str(s);
|
||||
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -147,7 +156,7 @@ impl Printer {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Doc::HardLine | Doc::BlankLine => return true,
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => return true,
|
||||
Doc::IfBreak(s) => {
|
||||
if mode == Mode::Break {
|
||||
width -= s.chars().count() as isize;
|
||||
@@ -161,7 +170,7 @@ impl Printer {
|
||||
|
||||
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
items.iter().any(|d| match d {
|
||||
Doc::HardLine | Doc::BlankLine => true,
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
|
||||
Doc::Concat(inner) | Doc::Indent(inner) | Doc::Group(inner) => contains_hard_line(inner),
|
||||
_ => false,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
# a fenced region comes out byte-exact, weird spacing and all
|
||||
module m;
|
||||
// verilog_format: off
|
||||
wire [3:0] a = 4'h1;
|
||||
wire [31:0] bb= 32'h2;
|
||||
// verilog_format: on
|
||||
wire c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// verilog_format: off
|
||||
wire [3:0] a = 4'h1;
|
||||
wire [31:0] bb= 32'h2;
|
||||
// verilog_format: on
|
||||
wire c;
|
||||
endmodule
|
||||
====
|
||||
# the vfmt alias fences the same region
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire [3:0] a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire [3:0] a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# the two spellings are interchangeable across one region
|
||||
module m;
|
||||
// verilog_format: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// verilog_format: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# a region keeps its own indentation, first line included
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
wire b;
|
||||
// vfmt: on
|
||||
wire c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
wire b;
|
||||
// vfmt: on
|
||||
wire c;
|
||||
endmodule
|
||||
====
|
||||
# a fence at the top of the file
|
||||
// vfmt: off
|
||||
module m; endmodule
|
||||
// vfmt: on
|
||||
module n;
|
||||
wire a;
|
||||
endmodule
|
||||
----
|
||||
// vfmt: off
|
||||
module m; endmodule
|
||||
// vfmt: on
|
||||
module n;
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# an unmatched off runs to the end of the file
|
||||
module m;
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: off
|
||||
module n; wire b; endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: off
|
||||
module n; wire b; endmodule
|
||||
====
|
||||
# an unmatched off runs to the end of the module body, not past endmodule
|
||||
module m;
|
||||
wire a;
|
||||
// vfmt: off
|
||||
wire b;
|
||||
wire c;
|
||||
endmodule
|
||||
|
||||
module n;
|
||||
wire d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
// vfmt: off
|
||||
wire b;
|
||||
wire c;
|
||||
endmodule
|
||||
|
||||
module n;
|
||||
wire d;
|
||||
endmodule
|
||||
====
|
||||
# an unmatched off keeps the comment trailing its last item
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a; // note
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a; // note
|
||||
endmodule
|
||||
====
|
||||
# an unmatched off swallows the scope's dangling comments too
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// dangling one
|
||||
// dangling two
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// dangling one
|
||||
// dangling two
|
||||
endmodule
|
||||
====
|
||||
# an on written after endmodule cannot close an off inside the module
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: on
|
||||
module n;
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: on
|
||||
module n;
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# two regions in one file
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
// vfmt: off
|
||||
wire c;
|
||||
// vfmt: on
|
||||
wire d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
// vfmt: off
|
||||
wire c;
|
||||
// vfmt: on
|
||||
wire d;
|
||||
endmodule
|
||||
====
|
||||
# a fence with trailing text is not a fence
|
||||
module m;
|
||||
// vfmt: off (just for now)
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off (just for now)
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# a block comment is not a fence
|
||||
module m;
|
||||
/* vfmt: off */
|
||||
wire a;
|
||||
/* vfmt: on */
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
/* vfmt: off */
|
||||
wire a;
|
||||
/* vfmt: on */
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# a fence written after code on the same line is not a fence
|
||||
module m;
|
||||
wire z; // vfmt: off
|
||||
wire a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire z; // vfmt: off
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# an on with no open off is an ordinary comment
|
||||
module m;
|
||||
// vfmt: on
|
||||
wire a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: on
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# a second off inside an open region is just text, the first on closes
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: off
|
||||
wire b;
|
||||
// vfmt: on
|
||||
wire c;
|
||||
// vfmt: on
|
||||
wire d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: off
|
||||
wire b;
|
||||
// vfmt: on
|
||||
wire c;
|
||||
// vfmt: on
|
||||
wire d;
|
||||
endmodule
|
||||
====
|
||||
# a region of nothing but comments
|
||||
module m;
|
||||
// vfmt: off
|
||||
// +-------+
|
||||
// | ascii |
|
||||
// +-------+
|
||||
// vfmt: on
|
||||
wire a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
// +-------+
|
||||
// | ascii |
|
||||
// +-------+
|
||||
// vfmt: on
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# comments before the off fence are still formatted, and never dropped
|
||||
module m;
|
||||
wire z;
|
||||
|
||||
// doc for the table
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire z;
|
||||
|
||||
// doc for the table
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
endmodule
|
||||
====
|
||||
# valid-but-ugly code inside a region is left exactly as written
|
||||
module m;
|
||||
// vfmt: off
|
||||
always@(posedge clk)if(en)q<=d;else q <= 1'b0;
|
||||
assign y = {a,b , c} ;
|
||||
// vfmt: on
|
||||
assign z = a + b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
always@(posedge clk)if(en)q<=d;else q <= 1'b0;
|
||||
assign y = {a,b , c} ;
|
||||
// vfmt: on
|
||||
assign z = a + b;
|
||||
endmodule
|
||||
====
|
||||
# attributes and directives inside a region are source bytes like anything else
|
||||
module m;
|
||||
// vfmt: off
|
||||
(* keep *) wire a;
|
||||
`ifdef FOO
|
||||
wire b;
|
||||
`endif
|
||||
// vfmt: on
|
||||
wire c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// vfmt: off
|
||||
(* keep *) wire a;
|
||||
`ifdef FOO
|
||||
wire b;
|
||||
`endif
|
||||
// vfmt: on
|
||||
wire c;
|
||||
endmodule
|
||||
====
|
||||
# fences work in a package body
|
||||
package p;
|
||||
// vfmt: off
|
||||
localparam int A =1;
|
||||
// vfmt: on
|
||||
localparam int B =2;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
// vfmt: off
|
||||
localparam int A =1;
|
||||
// vfmt: on
|
||||
localparam int B = 2;
|
||||
endpackage
|
||||
====
|
||||
# fences work inside a generate begin..end block
|
||||
module m;
|
||||
generate
|
||||
if (X) begin : g
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
if (X) begin : g
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
wire b;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# a statement-level fence has no effect this round
|
||||
module m;
|
||||
always @(*) begin
|
||||
// vfmt: off
|
||||
x = 1;
|
||||
// vfmt: on
|
||||
y = 2;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) begin
|
||||
// vfmt: off
|
||||
x = 1;
|
||||
// vfmt: on
|
||||
y = 2;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a blank line before the off fence survives, collapsed to one
|
||||
module m;
|
||||
wire z;
|
||||
|
||||
|
||||
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire z;
|
||||
|
||||
// vfmt: off
|
||||
wire a;
|
||||
// vfmt: on
|
||||
endmodule
|
||||
====
|
||||
# a region ending the file keeps exactly one final newline
|
||||
module m;
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: off
|
||||
`define WIDTH 8
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
endmodule
|
||||
// vfmt: off
|
||||
`define WIDTH 8
|
||||
====
|
||||
@@ -0,0 +1,110 @@
|
||||
//! `// verilog_format: off` fences: the properties the `.cases` table cannot
|
||||
//! state directly — byte-exactness of the spliced range, idempotency of a
|
||||
//! second pass, and that the safety net still rejects a *corrupted* region.
|
||||
//! Spec: `docs/features/format-fences/README.md`.
|
||||
|
||||
use vlog_formatter::fence::{fence_of, Fence};
|
||||
use vlog_formatter::{format_source, verify_equivalence, Config};
|
||||
|
||||
fn fmt(src: &str) -> String {
|
||||
format_source(src, &Config::default()).expect("format")
|
||||
}
|
||||
|
||||
/// Format, then assert the three properties every fenced input must have:
|
||||
/// the region survives byte-for-byte, the output re-lexes to the input, and
|
||||
/// formatting again is a fixed point.
|
||||
fn fenced(src: &str, region: &str) -> String {
|
||||
let out = fmt(src);
|
||||
assert!(src.contains(region), "the region is not in the input:\n{region}");
|
||||
assert!(out.contains(region), "region not emitted byte-exact:\nwant\n{region}\ngot\n{out}");
|
||||
verify_equivalence(src, &out).expect("output is token-equivalent to the input");
|
||||
assert_eq!(fmt(&out), out, "second pass changed the output");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_is_emitted_byte_for_byte() {
|
||||
// Interior spacing, alignment, trailing comments and a blank line inside
|
||||
// the region all survive; the item after it is formatted normally.
|
||||
let src = "module m;\n // vfmt: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // vfmt: on\n wire c;\nendmodule\n";
|
||||
let region =
|
||||
" // vfmt: off\n wire [3:0] a = 4'h1; // lo\n\n wire [31:0] b= 32'h2;\n // vfmt: on";
|
||||
let out = fenced(src, region);
|
||||
assert!(out.ends_with(" wire c;\nendmodule\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_keeps_its_own_indentation_on_every_line() {
|
||||
// The source is indented four spaces inside a module the formatter
|
||||
// indents by two: the region's first line is not re-indented either.
|
||||
let src =
|
||||
"module m;\n // vfmt: off\n wire a;\n // vfmt: on\n wire b;\nendmodule\n";
|
||||
let out = fenced(src, " // vfmt: off\n wire a;\n // vfmt: on");
|
||||
assert!(
|
||||
out.contains("\n wire b;\n"),
|
||||
"formatting did not resume at the module indent:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmatched_off_runs_to_the_end_of_its_scope_only() {
|
||||
// It must stop at the module's last item — the comment trailing that item
|
||||
// included, since `Meta.trailing` has no span of its own to splice from —
|
||||
// and the next module must still be formatted.
|
||||
let src = "module m;\n // vfmt: off\n wire a; // note\nendmodule\n\nmodule n;\n wire b;\nendmodule\n";
|
||||
let out = fenced(src, " // vfmt: off\n wire a; // note");
|
||||
assert!(out.contains("module n;\n wire b;\n"), "the next module was not formatted:\n{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_before_the_off_fence_are_still_formatted_and_never_dropped() {
|
||||
let src = "module m;\n// doc for the table\n// vfmt: off\nwire a;\n// vfmt: on\nendmodule\n";
|
||||
let out = fenced(src, "// vfmt: off\nwire a;\n// vfmt: on");
|
||||
assert!(out.contains(" // doc for the table\n"), "leading comment lost or unindented:\n{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
|
||||
// The fence is not a licence to change bytes: a hand-built "output" that
|
||||
// reformats, drops or adds anything inside the region must fail
|
||||
// equivalence exactly as it would outside one.
|
||||
let src = "module m;\n // vfmt: off\n wire [3:0] a;\n wire b; // note\n // vfmt: on\nendmodule\n";
|
||||
let corrupted = [
|
||||
// a token dropped from inside the region
|
||||
"module m;\n // vfmt: off\n wire a;\n wire b; // note\n // vfmt: on\nendmodule\n",
|
||||
// the region's trailing comment dropped
|
||||
"module m;\n // vfmt: off\n wire [3:0] a;\n wire b;\n // vfmt: on\nendmodule\n",
|
||||
// a fence comment itself dropped
|
||||
"module m;\n wire [3:0] a;\n wire b; // note\n // vfmt: on\nendmodule\n",
|
||||
// a token added inside the region
|
||||
"module m;\n // vfmt: off\n wire [3:0] a, z;\n wire b; // note\n // vfmt: on\nendmodule\n",
|
||||
// a fence turned into an ordinary comment
|
||||
"module m;\n // vfmt: off\n wire [3:0] a;\n wire b; // note\n // vfmt: onward\nendmodule\n",
|
||||
];
|
||||
// The real formatter gets it right...
|
||||
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
|
||||
// ...and every corruption of it is caught.
|
||||
for bad in corrupted {
|
||||
assert!(
|
||||
verify_equivalence(src, bad).is_err(),
|
||||
"a corrupted fenced region was accepted:\n{bad}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_matcher_agrees_with_what_the_formatter_honours() {
|
||||
// The unit tests in `fence.rs` pin the matcher; this pins that the
|
||||
// formatter is driven by it, in both directions.
|
||||
let body = "module m;\n {}\n wire a;\nendmodule\n";
|
||||
for spelling in ["// verilog_format: off", "//vfmt: off", "//\tverilog_format: off"] {
|
||||
assert_eq!(fence_of(spelling), Some(Fence::Off));
|
||||
let out = fmt(&body.replace("{}", spelling));
|
||||
assert!(out.contains("wire a;"), "{spelling} did not fence:\n{out}");
|
||||
}
|
||||
for spelling in ["// vfmt: off now", "// vfmt:off", "/* vfmt: off */", "// VFMT: OFF"] {
|
||||
assert_eq!(fence_of(spelling), None);
|
||||
let out = fmt(&body.replace("{}", spelling));
|
||||
assert!(out.contains("wire a;"), "{spelling} fenced but should not have:\n{out}");
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,13 @@ pub enum ItemKind {
|
||||
Function(FunctionDecl),
|
||||
Task(TaskDecl),
|
||||
Defparam(Vec<(Expr, Expr)>),
|
||||
/// Source that could not be parsed as an item, kept verbatim.
|
||||
///
|
||||
/// Only error-tolerant parsing
|
||||
/// (`vlog_parser::parse_source_tolerant`) ever produces this; the
|
||||
/// strict entry point fails on the first error instead, so the formatter
|
||||
/// never sees one. See `docs/features/error-recovery/README.md`.
|
||||
Error(RawText),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -609,6 +616,11 @@ pub enum StmtKind {
|
||||
els: Option<Box<Stmt>>,
|
||||
},
|
||||
Null,
|
||||
/// Source that could not be parsed as a statement, kept verbatim.
|
||||
///
|
||||
/// The statement-level twin of [`ItemKind::Error`]: produced only by
|
||||
/// error-tolerant parsing, never seen by the formatter.
|
||||
Error(RawText),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -13,7 +13,7 @@ pub mod token;
|
||||
|
||||
pub use lexer::{tokenize, LexError};
|
||||
pub use line_index::LineIndex;
|
||||
pub use parser::{parse, ParseError};
|
||||
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
|
||||
pub use span::TextRange;
|
||||
|
||||
/// Convenience: lex and parse in one step.
|
||||
@@ -22,6 +22,34 @@ pub fn parse_source(source: &str) -> Result<ast::SourceFile, Error> {
|
||||
parse(tokens).map_err(Error::Parse)
|
||||
}
|
||||
|
||||
/// Lex and parse without ever failing: the parts that do not parse become
|
||||
/// error leaves in the tree and diagnostics in the list.
|
||||
///
|
||||
/// This is the entry point for editor-side consumers (TODO.md §6), where the
|
||||
/// buffer is mid-edit most of the time. On a file that parses cleanly the tree
|
||||
/// is identical to [`parse_source`]'s and the diagnostic list is empty — so a
|
||||
/// caller that refuses to act on a file with diagnostics (the formatter does)
|
||||
/// sees exactly the behavior it had before. See
|
||||
/// `docs/features/error-recovery/README.md`.
|
||||
pub fn parse_source_tolerant(source: &str) -> (ast::SourceFile, Vec<ParseDiagnostic>) {
|
||||
match tokenize(source) {
|
||||
Ok(tokens) => parse_tolerant(tokens, source),
|
||||
// The lexer is all-or-nothing (an unterminated string or block comment
|
||||
// has no sensible resumption point), so a lex error makes the whole
|
||||
// file one error node rather than a partial tree.
|
||||
Err(e) => {
|
||||
let offset = LineIndex::new(source).offset(e.line, e.col).unwrap_or(0);
|
||||
let diag = ParseDiagnostic {
|
||||
message: e.message,
|
||||
line: e.line,
|
||||
col: e.col,
|
||||
span: TextRange::empty(offset),
|
||||
};
|
||||
(parser::error_file(source), vec![diag])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Lex(LexError),
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
//! number of tokens per level brackets itself with [`Parser::enter`] /
|
||||
//! [`Parser::leave`], turning nesting past [`MAX_NESTING_DEPTH`] into an
|
||||
//! ordinary [`ParseError`].
|
||||
//!
|
||||
//! Error tolerance: [`parse`] stops at the first error, which is what the
|
||||
//! formatter needs. [`parse_tolerant`] shares this same grammar code but
|
||||
//! recovers instead — see `docs/features/error-recovery/README.md`.
|
||||
|
||||
use crate::ast::*;
|
||||
use crate::span::TextRange;
|
||||
@@ -32,6 +36,26 @@ impl std::fmt::Display for ParseError {
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
/// An error [`parse_tolerant`] recovered from, in the same words a
|
||||
/// [`ParseError`] would have used plus the byte range it points at.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParseDiagnostic {
|
||||
/// What went wrong, e.g. ``expected `;` (found "endmodule")``.
|
||||
pub message: String,
|
||||
/// 1-based line of the token the parser gave up on.
|
||||
pub line: u32,
|
||||
/// 1-based column (in bytes) of that token.
|
||||
pub col: u32,
|
||||
/// Byte extent of that token; empty at end of file.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ParseDiagnostic {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}:{}: {}", self.line, self.col, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
type PResult<T> = Result<T, ParseError>;
|
||||
|
||||
const TYPE_KEYWORDS: &[&str] = &[
|
||||
@@ -62,6 +86,27 @@ const GATE_KEYWORDS: &[&str] = &[
|
||||
"rtran", "tranif0", "tranif1", "rtranif0", "rtranif1",
|
||||
];
|
||||
|
||||
/// Keywords that close a construct an enclosing parse loop is waiting for.
|
||||
/// Recovery stops *before* them without consuming, so the loop that opened the
|
||||
/// construct still gets to close it — that is what keeps an error inside a
|
||||
/// generate block from eating the `endgenerate`.
|
||||
const SYNC_CLOSERS: &[&str] = &[
|
||||
"end",
|
||||
"endmodule",
|
||||
"endpackage",
|
||||
"endgenerate",
|
||||
"endfunction",
|
||||
"endtask",
|
||||
"endcase",
|
||||
"join",
|
||||
"join_any",
|
||||
"join_none",
|
||||
];
|
||||
|
||||
/// Keywords that can only *begin* a construct at file scope. Recovery stops
|
||||
/// before them too, so garbage written in front of a module cannot swallow it.
|
||||
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "package"];
|
||||
|
||||
const ASSIGN_OPS: &[&str] =
|
||||
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
|
||||
|
||||
@@ -94,7 +139,7 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
|
||||
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
|
||||
pub const MAX_CHAIN_LENGTH: u32 = 256;
|
||||
|
||||
pub struct Parser {
|
||||
pub struct Parser<'a> {
|
||||
tokens: Vec<Token>,
|
||||
pos: usize,
|
||||
pending_leading: Vec<Comment>,
|
||||
@@ -103,21 +148,69 @@ pub struct Parser {
|
||||
depth: u32,
|
||||
/// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`].
|
||||
links: u32,
|
||||
/// Recover from errors instead of returning them; see [`parse_tolerant`].
|
||||
tolerant: bool,
|
||||
/// The text the tokens were lexed from. Read only by recovery, to copy a
|
||||
/// skipped range into an error node, so strict mode passes `""`.
|
||||
source: &'a str,
|
||||
/// Errors recovered from, in source order. Always empty in strict mode.
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
/// Parse a token stream, stopping at the first error.
|
||||
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
|
||||
let mut p = Parser {
|
||||
tokens,
|
||||
pos: 0,
|
||||
pending_leading: Vec::new(),
|
||||
pending_trailing: Vec::new(),
|
||||
depth: 0,
|
||||
links: 0,
|
||||
};
|
||||
p.parse_source_file()
|
||||
Parser::new(tokens, "", false).parse_source_file()
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
/// Parse a token stream that may be broken, recording errors instead of
|
||||
/// failing.
|
||||
///
|
||||
/// The unparsable parts of the file become [`ItemKind::Error`] /
|
||||
/// [`StmtKind::Error`] leaves holding the source text they cover, so the tree
|
||||
/// still spans the whole file. `source` must be the exact text `tokens` were
|
||||
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
|
||||
/// the diagnostics are empty.
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
|
||||
let mut p = Parser::new(tokens, source, true);
|
||||
match p.parse_source_file() {
|
||||
Ok(file) => (file, p.diagnostics),
|
||||
// Unreachable in practice: every error path inside a file body is
|
||||
// recovered. Rather than assert that, fall back to one error item
|
||||
// covering the file, which is what a lex-level failure gets too.
|
||||
Err(e) => {
|
||||
let span = TextRange::new(0, source.len() as u32);
|
||||
let diag = ParseDiagnostic { message: e.message, line: e.line, col: e.col, span };
|
||||
let mut diagnostics = p.diagnostics;
|
||||
diagnostics.push(diag);
|
||||
(error_file(source), diagnostics)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `SourceFile` that is one error item covering the whole text — what a
|
||||
/// caller gets when the text cannot even be tokenized.
|
||||
pub(crate) fn error_file(source: &str) -> SourceFile {
|
||||
let span = TextRange::new(0, source.len() as u32);
|
||||
let raw = RawText { text: source.to_string(), col: 1, span };
|
||||
let item = Item { meta: Meta::default(), kind: ItemKind::Error(raw), span };
|
||||
SourceFile { items: vec![item], dangling: Vec::new(), span }
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
fn new(tokens: Vec<Token>, source: &'a str, tolerant: bool) -> Self {
|
||||
Parser {
|
||||
tokens,
|
||||
pos: 0,
|
||||
pending_leading: Vec::new(),
|
||||
pending_trailing: Vec::new(),
|
||||
depth: 0,
|
||||
links: 0,
|
||||
tolerant,
|
||||
source,
|
||||
diagnostics: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cur(&self) -> &Token {
|
||||
&self.tokens[self.pos]
|
||||
}
|
||||
@@ -174,6 +267,160 @@ impl Parser {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Error recovery
|
||||
//
|
||||
// Only ever reached when `tolerant` is set. The strategy is deliberately
|
||||
// one paragraph long: record the error, skip to a sync token, wrap the
|
||||
// skipped text in an error leaf, continue with the next item/statement.
|
||||
// Neither `depth` nor `links` is touched here — the gated frames released
|
||||
// their own levels on the way out, so recovery resumes at exactly the
|
||||
// budget the loop it happened in was running at.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
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()))
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
fn at_join_kw(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_kw("join") || t.is_kw("join_any") || t.is_kw("join_none")
|
||||
}
|
||||
|
||||
/// Loop condition for a body that ends at `end_kw`. In tolerant mode any
|
||||
/// sync stop ends it too, so an unclosed block stops where the next
|
||||
/// construct begins instead of eating the rest of the file.
|
||||
fn at_body_end(&self, end_kw: &str) -> bool {
|
||||
self.at_eof() || self.cur().is_kw(end_kw) || (self.tolerant && self.at_sync_stop())
|
||||
}
|
||||
|
||||
/// Consume a construct's closing keyword. In tolerant mode a missing one
|
||||
/// is a diagnostic and the construct is treated as closed where the parser
|
||||
/// stopped: mid-edit code has unclosed blocks all the time, and the items
|
||||
/// already parsed inside are worth more than the whole file being one
|
||||
/// error node.
|
||||
fn expect_closer(&mut self, kw: &str) -> PResult<()> {
|
||||
if self.cur().is_kw(kw) {
|
||||
self.bump();
|
||||
return Ok(());
|
||||
}
|
||||
if self.tolerant {
|
||||
self.record(format!("expected `{kw}`"));
|
||||
return Ok(());
|
||||
}
|
||||
self.error(format!("expected `{kw}`"))
|
||||
}
|
||||
|
||||
/// Record a diagnostic at the cursor without failing.
|
||||
fn record(&mut self, message: impl Into<String>) {
|
||||
let e = self.make_error(message);
|
||||
self.push_diag(e);
|
||||
}
|
||||
|
||||
/// File `err` as a diagnostic. Called while the cursor still sits on the
|
||||
/// token the error was raised at, which is where its span comes from.
|
||||
fn push_diag(&mut self, err: ParseError) {
|
||||
let span = self.cur().span;
|
||||
self.diagnostics.push(ParseDiagnostic {
|
||||
message: err.message,
|
||||
line: err.line,
|
||||
col: err.col,
|
||||
span,
|
||||
});
|
||||
}
|
||||
|
||||
/// Skip tokens up to the next sync point: a `;` (consumed — it terminated
|
||||
/// the broken construct), a sync-stop keyword (left in place for the
|
||||
/// construct it belongs to), or end of file.
|
||||
///
|
||||
/// Brackets opened while skipping are skipped as a unit, so the `;`s of a
|
||||
/// broken `for (i = 0; ...)` header do not end the skip early. A closing
|
||||
/// bracket with nothing open is skipped like any other token: recovery
|
||||
/// only ever runs in an item or statement list, and no such list sits
|
||||
/// inside brackets, so a stray `)` is garbage rather than someone else's
|
||||
/// terminator — treating it as one made every leftover `)` of a broken
|
||||
/// expression its own error node.
|
||||
fn skip_to_sync(&mut self) {
|
||||
let mut open = 0u32;
|
||||
while !self.at_eof() {
|
||||
let t = self.cur();
|
||||
if open == 0 {
|
||||
if self.at_sync_stop() {
|
||||
return;
|
||||
}
|
||||
if t.is_sym(";") {
|
||||
self.bump();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
open += 1;
|
||||
} else if open > 0 && (t.is_sym(")") || t.is_sym("]") || t.is_sym("}")) {
|
||||
open -= 1;
|
||||
}
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
|
||||
/// Record `err` and skip to a sync point, handing back the skipped source
|
||||
/// as a verbatim leaf spanning from `start` (the byte offset of the token
|
||||
/// at `start_pos`, where the failed construct began).
|
||||
fn recover(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText {
|
||||
self.push_diag(err);
|
||||
if self.pos == start_pos {
|
||||
// The failed construct consumed nothing, so skipping might not
|
||||
// either; take one token to guarantee the enclosing loop advances.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_to_sync();
|
||||
// Comments inside the skipped range are part of the raw text below.
|
||||
// Dropping the trivia copies keeps them from reattaching themselves to
|
||||
// whatever node comes next.
|
||||
let _ = self.take_dangling();
|
||||
let span = self.span_from(start);
|
||||
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// The source text `span` covers. Empty in strict mode, which never
|
||||
/// recovers and is therefore never given the source.
|
||||
fn slice(&self, span: TextRange) -> String {
|
||||
self.source.get(span.as_range()).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Parse one item; in tolerant mode turn a failure into an error leaf.
|
||||
fn item_or_recover(&mut self) -> PResult<Item> {
|
||||
let start_pos = self.pos;
|
||||
let start = self.here();
|
||||
match self.parse_item() {
|
||||
Err(e) if self.tolerant => {
|
||||
let raw = self.recover(start_pos, start, e);
|
||||
let span = raw.span;
|
||||
Ok(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span })
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse one statement; in tolerant mode turn a failure into an error leaf.
|
||||
fn stmt_or_recover(&mut self) -> PResult<Stmt> {
|
||||
let start_pos = self.pos;
|
||||
let start = self.here();
|
||||
match self.parse_stmt() {
|
||||
Err(e) if self.tolerant => {
|
||||
let raw = self.recover(start_pos, start, e);
|
||||
let span = raw.span;
|
||||
Ok(Stmt { meta: Meta::default(), kind: StmtKind::Error(raw), span })
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Spans
|
||||
//
|
||||
@@ -211,13 +458,18 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn error<T>(&self, message: impl Into<String>) -> PResult<T> {
|
||||
Err(self.make_error(message))
|
||||
}
|
||||
|
||||
/// The error the parser would report at the cursor right now.
|
||||
fn make_error(&self, message: impl Into<String>) -> ParseError {
|
||||
let t = self.cur();
|
||||
let shown = if t.kind == TokenKind::Eof { "<eof>" } else { t.text.as_str() };
|
||||
Err(ParseError {
|
||||
ParseError {
|
||||
line: t.line,
|
||||
col: t.col,
|
||||
message: format!("{} (found {:?})", message.into(), shown),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_sym(&mut self, sym: &str) -> PResult<Token> {
|
||||
@@ -442,7 +694,7 @@ impl Parser {
|
||||
fn parse_source_file(&mut self) -> PResult<SourceFile> {
|
||||
let mut items = Vec::new();
|
||||
while !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
// The cursor is on the EOF token, whose empty span sits at the end of
|
||||
@@ -543,11 +795,11 @@ impl Parser {
|
||||
"generate" => {
|
||||
self.bump();
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endgenerate") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endgenerate") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endgenerate")?;
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
@@ -623,11 +875,11 @@ impl Parser {
|
||||
let name = self.expect_ident()?;
|
||||
self.expect_sym(";")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endpackage") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endpackage") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endpackage")?;
|
||||
self.expect_closer("endpackage")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(ItemKind::Package { kw, name, items, dangling, end_label })
|
||||
}
|
||||
@@ -685,11 +937,11 @@ impl Parser {
|
||||
let (ports, port_dangling) = self.parse_port_list()?;
|
||||
self.expect_sym(";")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endmodule") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endmodule") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endmodule")?;
|
||||
self.expect_closer("endmodule")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(Module {
|
||||
kw,
|
||||
@@ -1369,7 +1621,7 @@ impl Parser {
|
||||
let expr = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endcase") && !self.at_eof() {
|
||||
while !self.at_body_end("endcase") {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let labels = if self.eat_kw("default") {
|
||||
@@ -1387,7 +1639,7 @@ impl Parser {
|
||||
items.push(GenCaseItem { meta, labels, body, span });
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endcase")?;
|
||||
self.expect_closer("endcase")?;
|
||||
Ok(GenCase { expr, items, dangling })
|
||||
}
|
||||
|
||||
@@ -1397,11 +1649,11 @@ impl Parser {
|
||||
self.bump();
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("end") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("end") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
self.expect_closer("end")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(GenBlock {
|
||||
label,
|
||||
@@ -1412,7 +1664,7 @@ impl Parser {
|
||||
span: self.span_from(start),
|
||||
})
|
||||
} else {
|
||||
let item = self.parse_item()?;
|
||||
let item = self.item_or_recover()?;
|
||||
let span = item.span;
|
||||
Ok(GenBlock {
|
||||
label: None,
|
||||
@@ -1512,11 +1764,11 @@ impl Parser {
|
||||
end_kw: &str,
|
||||
) -> PResult<(Vec<Stmt>, Vec<Comment>, Option<String>)> {
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_kw(end_kw) && !self.at_eof() {
|
||||
stmts.push(self.parse_stmt()?);
|
||||
while !self.at_body_end(end_kw) {
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw(end_kw)?;
|
||||
self.expect_closer(end_kw)?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok((stmts, dangling, end_label))
|
||||
}
|
||||
@@ -1593,11 +1845,11 @@ impl Parser {
|
||||
self.bump();
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_kw("end") && !self.at_eof() {
|
||||
stmts.push(self.parse_stmt()?);
|
||||
while !self.at_body_end("end") {
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
self.expect_closer("end")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::Block { label, stmts, dangling, end_label })
|
||||
}
|
||||
@@ -1606,14 +1858,18 @@ impl Parser {
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut stmts = Vec::new();
|
||||
while !self.at_eof()
|
||||
&& !(self.cur().is_kw("join")
|
||||
|| self.cur().is_kw("join_any")
|
||||
|| self.cur().is_kw("join_none"))
|
||||
&& !self.at_join_kw()
|
||||
&& !(self.tolerant && self.at_sync_stop())
|
||||
{
|
||||
stmts.push(self.parse_stmt()?);
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
let join_kw = self.bump().text;
|
||||
let join_kw = if self.tolerant && !self.at_join_kw() {
|
||||
self.record("expected `join`");
|
||||
"join".to_string()
|
||||
} else {
|
||||
self.bump().text
|
||||
};
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label })
|
||||
}
|
||||
@@ -1836,7 +2092,7 @@ impl Parser {
|
||||
self.expect_sym(")")?;
|
||||
// `case (x) inside` is not supported; plain case kinds only.
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endcase") && !self.at_eof() {
|
||||
while !self.at_body_end("endcase") {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let labels = if self.eat_kw("default") {
|
||||
@@ -1848,7 +2104,7 @@ impl Parser {
|
||||
self.expect_sym(":")?;
|
||||
labels
|
||||
};
|
||||
let stmt = self.parse_stmt()?;
|
||||
let stmt = self.stmt_or_recover()?;
|
||||
let span = self.span_from(start);
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
@@ -1856,7 +2112,7 @@ impl Parser {
|
||||
items.push(CaseItem { meta, labels, stmt, span });
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endcase")?;
|
||||
self.expect_closer("endcase")?;
|
||||
Ok(StmtKind::Case { qualifier, kw, expr, items, dangling })
|
||||
}
|
||||
|
||||
@@ -2818,4 +3074,35 @@ mod tests {
|
||||
assert_eq!(comments.before.len(), 1, "one comment before the operator");
|
||||
assert_eq!(comments.after.len(), 1, "one comment after the operator");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Error recovery
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// White-box version of the handshake in
|
||||
/// `docs/features/recursion-limit/README.md`: recovery neither leaks nor
|
||||
/// resets the two budgets, so both counters are back at zero once a file
|
||||
/// full of recovered errors has been parsed.
|
||||
#[test]
|
||||
fn both_budgets_are_balanced_after_recovering() {
|
||||
let src = "module m;\n wire a\n assign x = ((1 +;\n initial begin\n y = ;\n end\n bad ) ) ;\nendmodule\n@#!\nmodule n;\n wire b\nendmodule\n";
|
||||
let mut p = Parser::new(tokenize(src).expect("lex error"), src, true);
|
||||
p.parse_source_file().expect("tolerant parsing never fails");
|
||||
assert!(!p.diagnostics.is_empty(), "the source is broken on purpose");
|
||||
assert_eq!(p.depth, 0, "nesting budget left open after recovery");
|
||||
assert_eq!(p.links, 0, "chain budget left open after recovery");
|
||||
}
|
||||
|
||||
/// The strict entry point keeps its contract: it fails at the *first*
|
||||
/// error, with the same message tolerant mode files as its first
|
||||
/// diagnostic.
|
||||
#[test]
|
||||
fn strict_parsing_still_stops_at_the_first_error() {
|
||||
let src = "module m;\n wire a\n wire b;\n wire c\nendmodule\n";
|
||||
let err = parse(tokenize(src).expect("lex error")).expect_err("strict must refuse");
|
||||
let (_, diags) = crate::parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "tolerant mode reports both");
|
||||
assert_eq!(err.message, diags[0].message);
|
||||
assert_eq!((err.line, err.col), (diags[0].line, diags[0].col));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
//! Error-tolerant parsing: `parse_source_tolerant` never fails, agrees with
|
||||
//! the strict parser on every file that parses, and keeps the rest of a broken
|
||||
//! file addressable. See `docs/features/error-recovery/README.md`.
|
||||
//!
|
||||
//! The four guarantees this file pins:
|
||||
//!
|
||||
//! 1. on a valid file the tolerant tree is *the same tree* and the diagnostics
|
||||
//! are empty (`tolerant_parse_equals_strict_parse_on_valid_sources`);
|
||||
//! 2. every diagnostic points inside the file, and every error node's text is
|
||||
//! its own source slice (`diagnostics_and_error_nodes_stay_inside_the_file`;
|
||||
//! the span *nesting* half lives in `spans.rs`, which reuses its exhaustive
|
||||
//! walker on recovered trees);
|
||||
//! 3. recovery does not reset the depth/chain budgets — a file full of
|
||||
//! recovered-from deep expressions cannot accumulate
|
||||
//! (`recovery_does_not_leak_the_nesting_budget`);
|
||||
//! 4. tolerant parsing never panics on arbitrary input, smoke-tested over
|
||||
//! every byte prefix of every fixture (`truncating_a_file_anywhere_...`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Sources
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn workspace_file(rel: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(rel)
|
||||
}
|
||||
|
||||
/// Every `.sv`/`.v` fixture the formatter tests against.
|
||||
fn fixtures() -> Vec<(String, String)> {
|
||||
let dir = workspace_file("vlog_formatter/tests/fixtures");
|
||||
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
let mut out = Vec::new();
|
||||
for entry in entries {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if !matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("v")) {
|
||||
continue;
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
|
||||
out.push((path.display().to_string(), text));
|
||||
}
|
||||
assert!(out.len() >= 4, "expected the formatter fixtures next door, found {}", out.len());
|
||||
out
|
||||
}
|
||||
|
||||
/// Every input *and* every expected output in `tests/cases/*.cases`. The file
|
||||
/// format is `====`-separated cases, `#` header lines, input, `----`, expected
|
||||
/// (`docs/features/case-tables/README.md`); both halves are Verilog, so both
|
||||
/// are useful sources here.
|
||||
fn case_table_sources() -> Vec<(String, String)> {
|
||||
let dir = workspace_file("vlog_formatter/tests/cases");
|
||||
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
let mut out = Vec::new();
|
||||
for entry in entries {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("cases") {
|
||||
continue;
|
||||
}
|
||||
let name = path.display().to_string();
|
||||
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
|
||||
let mut block: Vec<&str> = Vec::new();
|
||||
for line in text.lines().chain(std::iter::once("====")) {
|
||||
if line.trim_end() != "====" {
|
||||
block.push(line);
|
||||
continue;
|
||||
}
|
||||
let body: Vec<&str> = block
|
||||
.iter()
|
||||
.skip_while(|l| l.starts_with('#') || l.trim().is_empty())
|
||||
.copied()
|
||||
.collect();
|
||||
if let Some(sep) = body.iter().position(|l| l.trim_end() == "----") {
|
||||
out.push((name.clone(), join(&body[..sep])));
|
||||
out.push((name.clone(), join(&body[sep + 1..])));
|
||||
}
|
||||
block.clear();
|
||||
}
|
||||
}
|
||||
assert!(out.len() > 100, "expected the formatter case tables, found {}", out.len());
|
||||
out
|
||||
}
|
||||
|
||||
fn join(lines: &[&str]) -> String {
|
||||
let mut s = lines.join("\n");
|
||||
if !s.is_empty() {
|
||||
s.push('\n');
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Mid-edit shapes, named. Each is a snapshot of a buffer someone is typing in.
|
||||
const BROKEN: &[(&str, &str)] = &[
|
||||
("missing semicolon", "module m;\n wire a\n wire b;\nendmodule\n"),
|
||||
("unclosed begin", "module m;\n initial begin\n x = 1;\nendmodule\n"),
|
||||
("unclosed module", "module m;\n wire a;\n"),
|
||||
("half-typed declaration", "module m;\n wire [7:\nendmodule\n"),
|
||||
("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"),
|
||||
("all garbage", "!!! ???\n"),
|
||||
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
||||
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
||||
("empty file", ""),
|
||||
];
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn module_named<'a>(file: &'a SourceFile, name: &str) -> &'a Module {
|
||||
for item in &file.items {
|
||||
if let ItemKind::Module(m) = &item.kind {
|
||||
if m.name == name {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("no module {name:?} in {:?}", file.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
fn kind_name(item: &Item) -> String {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => format!("module {}", m.name),
|
||||
ItemKind::Error(r) => format!("error {:?}", r.text),
|
||||
other => format!("{:?}", std::mem::discriminant(other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every error node in the tree, outermost first, as (span, text) pairs.
|
||||
fn error_nodes(file: &SourceFile) -> Vec<(vlog_parser::TextRange, String)> {
|
||||
let mut out = Vec::new();
|
||||
for item in &file.items {
|
||||
walk_item(item, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
match &item.kind {
|
||||
ItemKind::Error(r) => out.push((r.span, r.text.clone())),
|
||||
ItemKind::Module(m) => m.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
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) => {
|
||||
g.items.iter().flat_map(|i| i.body.items.iter()).for_each(|i| walk_item(i, out))
|
||||
}
|
||||
ItemKind::Initial(s) | ItemKind::Final(s) | ItemKind::Always { stmt: s, .. } => {
|
||||
walk_stmt(s, out)
|
||||
}
|
||||
ItemKind::Function(f) => f.stmts.iter().for_each(|s| walk_stmt(s, out)),
|
||||
ItemKind::Task(t) => t.stmts.iter().for_each(|s| walk_stmt(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_gen_if(g: &GenIf, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
g.then.items.iter().for_each(|i| walk_item(i, out));
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => walk_gen_if(inner, out),
|
||||
Some(GenElse::Block(b)) => b.items.iter().for_each(|i| walk_item(i, out)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_stmt(stmt: &Stmt, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Error(r) => out.push((r.span, r.text.clone())),
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
stmts.iter().for_each(|s| walk_stmt(s, out))
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
walk_stmt(then, out);
|
||||
els.iter().for_each(|s| walk_stmt(s, out));
|
||||
}
|
||||
StmtKind::Case { items, .. } => items.iter().for_each(|i| walk_stmt(&i.stmt, out)),
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => walk_stmt(body, out),
|
||||
StmtKind::Timing { stmt, .. } | StmtKind::Wait { stmt, .. } => {
|
||||
stmt.iter().for_each(|s| walk_stmt(s, out))
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
then.iter().chain(els.iter()).for_each(|s| walk_stmt(s, out))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_diagnostics_fit(src: &str, diags: &[ParseDiagnostic]) {
|
||||
for d in diags {
|
||||
assert!(
|
||||
d.span.end as usize <= src.len(),
|
||||
"diagnostic {d} span {:?} runs past the file ({} bytes)",
|
||||
d.span,
|
||||
src.len()
|
||||
);
|
||||
assert!(d.span.start <= d.span.end, "inverted span in {d}");
|
||||
assert!(d.line >= 1 && d.col >= 1, "diagnostic without a position: {d}");
|
||||
assert!(src.is_char_boundary(d.span.start as usize), "span start splits a character: {d}");
|
||||
assert!(src.is_char_boundary(d.span.end as usize), "span end splits a character: {d}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 1: a valid file parses to the very same tree
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn tolerant_parse_equals_strict_parse_on_valid_sources() {
|
||||
let mut sources = fixtures();
|
||||
sources.extend(case_table_sources());
|
||||
let mut valid = 0;
|
||||
let mut invalid = 0;
|
||||
for (name, src) in &sources {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
match parse_source(src) {
|
||||
Ok(strict) => {
|
||||
assert!(diags.is_empty(), "{name}: valid source got diagnostics: {diags:?}");
|
||||
assert_eq!(
|
||||
format!("{strict:?}"),
|
||||
format!("{file:?}"),
|
||||
"{name}: tolerant tree differs from the strict one"
|
||||
);
|
||||
valid += 1;
|
||||
}
|
||||
Err(_) => {
|
||||
// The `.cases` tables carry a few `#SKIP` cases of syntax the
|
||||
// parser does not support yet; those must report, not agree.
|
||||
assert!(
|
||||
!diags.is_empty(),
|
||||
"{name}: strict parse failed but tolerant found nothing"
|
||||
);
|
||||
assert_diagnostics_fit(src, &diags);
|
||||
invalid += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(valid > 200, "test would be vacuous: only {valid} valid sources");
|
||||
println!("{valid} valid sources agreed with the strict parser, {invalid} reported errors");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 2: diagnostics and error nodes stay inside the file
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn diagnostics_and_error_nodes_stay_inside_the_file() {
|
||||
for (name, src) in BROKEN {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(
|
||||
file.span.as_range(),
|
||||
0..src.len(),
|
||||
"{name}: the file node must span the whole text"
|
||||
);
|
||||
if src.is_empty() {
|
||||
assert!(diags.is_empty(), "{name}: an empty file is not an error");
|
||||
continue;
|
||||
}
|
||||
assert!(!diags.is_empty(), "{name}: expected at least one diagnostic");
|
||||
assert_diagnostics_fit(src, &diags);
|
||||
for (span, text) in error_nodes(&file) {
|
||||
assert!(
|
||||
span.end as usize <= src.len(),
|
||||
"{name}: error node {span:?} runs past the end"
|
||||
);
|
||||
assert_eq!(
|
||||
text,
|
||||
&src[span.as_range()],
|
||||
"{name}: an error node's text must be its own source slice"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diagnostics_span_is_the_token_its_line_col_names() {
|
||||
// The span and the line:col are two views of the same token, so an editor
|
||||
// that highlights the span and a terminal that prints the position agree.
|
||||
for (name, src) in BROKEN {
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
let index = vlog_parser::LineIndex::new(src);
|
||||
for d in &diags {
|
||||
let Some(offset) = index.offset(d.line, d.col) else {
|
||||
panic!("{name}: diagnostic position out of range: {d}");
|
||||
};
|
||||
assert_eq!(offset, d.span.start, "{name}: {d} span {:?} is elsewhere", d.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The mid-edit shapes, one assertion set each
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_missing_semicolon_is_recovered_at_the_next_one() {
|
||||
let src = "module m;\n wire a\n wire b;\n wire c;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert!(diags[0].message.contains("expected `;`"), "{}", diags[0]);
|
||||
let m = module_named(&file, "m");
|
||||
// The broken declaration and the one that follows it land in the error
|
||||
// node — the sync token is the next `;`, not the next line. `wire c;`
|
||||
// parses normally, which is the point: the file did not become garbage.
|
||||
assert_eq!(m.items.len(), 2);
|
||||
assert!(matches!(&m.items[0].kind, ItemKind::Error(r) if r.text == "wire a\n wire b;"));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_begin_keeps_the_statements_inside_it() {
|
||||
let src = "module m;\n initial begin\n x = 1;\n y = 2;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert!(diags[0].message.contains("expected `end`"), "{}", diags[0]);
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("{:?}", kind_name(&m.items[0])) };
|
||||
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("not a block") };
|
||||
assert_eq!(stmts.len(), 2, "both assignments survive the missing `end`");
|
||||
// The `endmodule` was left for the module to close with.
|
||||
assert!(error_nodes(&file).is_empty(), "nothing was skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_module_keeps_its_items() {
|
||||
let src = "module m;\n wire a;\n wire b;\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert!(diags[0].message.contains("expected `endmodule`"), "{}", diags[0]);
|
||||
assert_eq!(module_named(&file, "m").items.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_typed_declaration_is_one_error_node() {
|
||||
let src = "module m;\n wire [7:\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
assert!(matches!(&m.items[0].kind, ItemKind::Error(r) if r.text == "wire [7:"));
|
||||
// Recovery stopped *before* `endmodule`, so the module still closed.
|
||||
assert!(m.end_label.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_typed_instantiation_is_one_error_node() {
|
||||
let src = "module m;\n sub u0 (.a(\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
let m = module_named(&file, "m");
|
||||
// The unclosed `(` swallows what follows it up to the sync point: a
|
||||
// bracket the skip did not open ends it, otherwise the `;`.
|
||||
assert!(matches!(&m.items[0].kind, ItemKind::Error(_)), "{}", kind_name(&m.items[0]));
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_between_two_modules_leaves_both_intact() {
|
||||
for garbage in ["@#!", "foo bar baz", "???", "wire", "end", "* ) ]"] {
|
||||
let src = format!(
|
||||
"module a;\n wire x;\nendmodule\n{garbage}\nmodule b;\n wire w;\n wire v;\nendmodule\n"
|
||||
);
|
||||
let (file, diags) = parse_source_tolerant(&src);
|
||||
assert!(!diags.is_empty(), "{garbage:?}: expected a diagnostic");
|
||||
assert_diagnostics_fit(&src, &diags);
|
||||
assert_eq!(module_named(&file, "a").items.len(), 1, "{garbage:?}: module a lost items");
|
||||
assert_eq!(module_named(&file, "b").items.len(), 2, "{garbage:?}: module b lost items");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
||||
let src = "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "the generate region and the item after it both survive");
|
||||
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let ItemKind::GenIf(g) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
||||
assert!(matches!(&g.then.items[0].kind, ItemKind::Error(r) if r.text == "wire ;"));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_only_garbage_is_one_error_item() {
|
||||
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(file.items.len(), 1, "{src:?}");
|
||||
assert_eq!(diags.len(), 1, "{src:?}");
|
||||
let ItemKind::Error(r) = &file.items[0].kind else { panic!("{src:?}: not an error item") };
|
||||
assert_eq!(r.text, src.trim_end(), "{src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lex_error_makes_the_whole_file_one_error_item() {
|
||||
// The lexer is all-or-nothing, so there is no partial tree to offer.
|
||||
for src in ["module m;\n initial $display(\"abc);\nendmodule\n", "module m;\n/* nope\n"] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{src:?}");
|
||||
assert_diagnostics_fit(src, &diags);
|
||||
assert_eq!(file.items.len(), 1, "{src:?}");
|
||||
let ItemKind::Error(r) = &file.items[0].kind else { panic!("{src:?}: not an error item") };
|
||||
assert_eq!(r.text, src, "{src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_inside_a_function_or_task_body_keeps_the_rest() {
|
||||
let src = "module m;\n function int f;\n q = ;\n return 1;\n endfunction\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2);
|
||||
let ItemKind::Function(f) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(f.stmts.len(), 2, "the error statement and the `return` after it");
|
||||
assert!(matches!(&f.stmts[0].kind, StmtKind::Error(_)));
|
||||
assert!(matches!(&f.stmts[1].kind, StmtKind::Return(_)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 3: recovery does not touch the depth / chain budgets
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Both budgets are released by the gated frames themselves on the way out of
|
||||
/// an error, so recovery must neither reset them nor let them accumulate. 100
|
||||
/// broken deep expressions in a row is the shape that shows either mistake:
|
||||
/// leaking half the depth of each would trip `nesting too deep` well before
|
||||
/// the hundredth.
|
||||
#[test]
|
||||
fn recovery_does_not_leak_the_nesting_budget() {
|
||||
let depth = 25;
|
||||
let one = format!(" assign x = {}1 + {};\n", "(".repeat(depth), ")".repeat(depth));
|
||||
let src = format!("module m;\n{}endmodule\n", one.repeat(100));
|
||||
let (file, diags) = parse_source_tolerant(&src);
|
||||
assert_eq!(diags.len(), 100, "one diagnostic per broken expression");
|
||||
for d in &diags {
|
||||
assert!(!d.message.contains("too deep"), "budget accumulated across recoveries: {d}");
|
||||
assert!(!d.message.contains("too long"), "chain budget accumulated: {d}");
|
||||
}
|
||||
// All 100 recovered as items of the module, and the module still closed.
|
||||
assert_eq!(module_named(&file, "m").items.len(), 100);
|
||||
assert_eq!(error_nodes(&file).len(), 100);
|
||||
}
|
||||
|
||||
/// The complement: the limits still fire in tolerant mode, they are reported
|
||||
/// as an ordinary diagnostic, and the file keeps parsing afterwards.
|
||||
#[test]
|
||||
fn the_depth_limit_still_fires_and_is_recovered_from() {
|
||||
// Deep input costs stack; the shipped binary parses on the main thread,
|
||||
// test threads get 2 MiB. Same trick the parser's own boundary tests use.
|
||||
let src = format!(
|
||||
"module m;\n assign x = {}1{};\n wire ok;\nendmodule\n",
|
||||
"(".repeat(400),
|
||||
")".repeat(400)
|
||||
);
|
||||
let (file, diags) = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.spawn(move || {
|
||||
let (f, d) = parse_source_tolerant(&src);
|
||||
(format!("{:?}", f.items.iter().map(kind_name).collect::<Vec<_>>()), d)
|
||||
})
|
||||
.expect("spawn parser thread")
|
||||
.join()
|
||||
.expect("parser thread crashed");
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert!(diags[0].message.contains("nesting too deep"), "{}", diags[0]);
|
||||
assert!(file.contains("module m"), "{file}");
|
||||
}
|
||||
|
||||
/// The other direction of the same handshake: recovery must not *reset* the
|
||||
/// budget either. A broken statement 55 blocks deep, followed by 20 more
|
||||
/// blocks, is over the limit — unless recovery zeroed the counter, in which
|
||||
/// case the inner 20 would sail through.
|
||||
#[test]
|
||||
fn recovery_does_not_reset_the_nesting_budget() {
|
||||
let outer = 55;
|
||||
let inner = 20;
|
||||
let src = format!(
|
||||
"module m;\ninitial\n{}x = ;\n{}y = 1;\n{}{}\nendmodule\n",
|
||||
"begin\n".repeat(outer),
|
||||
"begin\n".repeat(inner),
|
||||
"end\n".repeat(inner),
|
||||
"end\n".repeat(outer),
|
||||
);
|
||||
let diags = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.spawn(move || parse_source_tolerant(&src).1)
|
||||
.expect("spawn parser thread")
|
||||
.join()
|
||||
.expect("parser thread crashed");
|
||||
assert!(
|
||||
diags.iter().any(|d| d.message.contains("nesting too deep")),
|
||||
"the depth counter was reset by recovery: {diags:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 4: no input panics, no input hangs
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Mid-edit code is truncated code: every prefix of a real file is a buffer
|
||||
/// someone had on screen at some point. Every byte position is tried, which
|
||||
/// includes every token boundary; the assertions are the invariants that must
|
||||
/// hold for *any* input, so this doubles as a fuzz smoke test.
|
||||
#[test]
|
||||
fn truncating_a_file_anywhere_never_panics() {
|
||||
let mut checked = 0usize;
|
||||
for (name, src) in fixtures() {
|
||||
for cut in 0..=src.len() {
|
||||
if !src.is_char_boundary(cut) {
|
||||
continue;
|
||||
}
|
||||
let prefix = &src[..cut];
|
||||
let (file, diags) = parse_source_tolerant(prefix);
|
||||
assert_eq!(
|
||||
file.span.as_range(),
|
||||
0..prefix.len(),
|
||||
"{name} cut at {cut}: file span must cover the prefix"
|
||||
);
|
||||
assert_diagnostics_fit(prefix, &diags);
|
||||
for (span, text) in error_nodes(&file) {
|
||||
assert_eq!(text, &prefix[span.as_range()], "{name} cut at {cut}");
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 4000, "expected thousands of prefixes, got {checked}");
|
||||
println!("{checked} byte prefixes of the fixtures parsed");
|
||||
}
|
||||
|
||||
/// Token-boundary truncation of the small case-table sources: same idea,
|
||||
/// different (much wider) set of constructs.
|
||||
#[test]
|
||||
fn truncating_a_case_table_source_never_panics() {
|
||||
let mut checked = 0usize;
|
||||
for (name, src) in case_table_sources() {
|
||||
let Ok(tokens) = vlog_parser::tokenize(&src) else { continue };
|
||||
let cuts = tokens.iter().map(|t| t.span.end as usize).chain(std::iter::once(src.len()));
|
||||
for cut in cuts {
|
||||
if !src.is_char_boundary(cut) {
|
||||
continue;
|
||||
}
|
||||
let (file, diags) = parse_source_tolerant(&src[..cut]);
|
||||
assert_eq!(file.span.as_range(), 0..cut, "{name} cut at {cut}");
|
||||
assert_diagnostics_fit(&src[..cut], &diags);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 1000, "expected thousands of prefixes, got {checked}");
|
||||
println!("{checked} token-boundary prefixes of the case tables parsed");
|
||||
}
|
||||
|
||||
/// Deleting one byte anywhere is the other half of "mid-edit": a stray
|
||||
/// backspace. Same invariants, and in particular no hang.
|
||||
#[test]
|
||||
fn deleting_any_single_character_never_panics() {
|
||||
for (name, src) in fixtures() {
|
||||
for cut in 0..src.len() {
|
||||
if !src.is_char_boundary(cut) {
|
||||
continue;
|
||||
}
|
||||
let mut broken = src.clone();
|
||||
let _ = broken.remove(cut);
|
||||
let (file, diags) = parse_source_tolerant(&broken);
|
||||
assert_eq!(file.span.as_range(), 0..broken.len(), "{name} minus byte {cut}");
|
||||
assert_diagnostics_fit(&broken, &diags);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,33 @@ fn every_node_span_nests_inside_its_parent() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The nesting invariant has to survive error recovery too: an error node is
|
||||
/// an ordinary leaf, so the tree a broken file produces must nest exactly like
|
||||
/// a good one's. Uses the same exhaustive walker as the test above, which is
|
||||
/// the point — a new node shape cannot skip it.
|
||||
#[test]
|
||||
fn recovered_error_nodes_nest_inside_their_parent() {
|
||||
let broken = [
|
||||
"module m;\n wire a\n wire b;\nendmodule\n",
|
||||
"module m;\n initial begin\n x = 1;\nendmodule\n",
|
||||
"module m;\n wire [7:\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\nendmodule\n",
|
||||
"module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n",
|
||||
"module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n",
|
||||
"module m;\n function int f;\n if (a) ; else\n endfunction\nendmodule\n",
|
||||
"module m;\n always @(*) case (x)\n 1: y = ;\n default: y = 0;\n endcase\nendmodule\n",
|
||||
"package p;\n localparam A = ;\n localparam B = 2;\nendpackage\n",
|
||||
"!!! ???\n",
|
||||
];
|
||||
for src in broken {
|
||||
let (file, diags) = vlog_parser::parse_source_tolerant(src);
|
||||
assert!(!diags.is_empty(), "expected diagnostics for {src:?}");
|
||||
for item in &file.items {
|
||||
check_item(src, item, file.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_inside(src: &str, what: &str, inner: TextRange, outer: TextRange) {
|
||||
assert!(
|
||||
outer.start <= inner.start && inner.end <= outer.end,
|
||||
@@ -432,6 +459,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
}
|
||||
}
|
||||
ItemKind::Import(_) | ItemKind::Timeunit(_) | ItemKind::Genvar(_) => {}
|
||||
// Leaves; only error-tolerant parsing produces the last one, which
|
||||
// `tests/error_recovery.rs` checks the spans of.
|
||||
ItemKind::Error(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,7 +566,11 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
|
||||
check_stmt(src, s, here);
|
||||
}
|
||||
}
|
||||
StmtKind::Break | StmtKind::Continue | StmtKind::Disable(_) | StmtKind::Null => {}
|
||||
StmtKind::Break
|
||||
| StmtKind::Continue
|
||||
| StmtKind::Disable(_)
|
||||
| StmtKind::Null
|
||||
| StmtKind::Error(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
# error-recovery
|
||||
|
||||
## Goal
|
||||
|
||||
A formatter may refuse broken input; a language server may not — an editor
|
||||
buffer is mid-edit most of the time, and "no symbols, no highlighting, no
|
||||
diagnostics until the file parses" is exactly the experience TODO.md §6 exists
|
||||
to avoid. This feature adds a second entry point to `vlog_parser`,
|
||||
`parse_source_tolerant(src) -> (SourceFile, Vec<ParseDiagnostic>)`, that never
|
||||
fails: where the grammar gives up it records a diagnostic, skips to a sync
|
||||
token, wraps the skipped text in an `ItemKind::Error` / `StmtKind::Error` leaf
|
||||
and carries on. The strict `parse_source` keeps its exact behavior — the two
|
||||
entry points share the grammar code, not a copy of it, so there is no second
|
||||
parser to keep in sync. On a file that parses cleanly the tolerant tree is
|
||||
*the same tree* and the diagnostic list is empty, which is what lets the
|
||||
formatter keep its "zero errors or nothing" contract unchanged.
|
||||
|
||||
## The recovery strategy
|
||||
|
||||
Deliberately one paragraph long, because a recovery strategy nobody can
|
||||
predict is worse than a crude one everybody can:
|
||||
|
||||
1. **Recovery happens only in item and statement *lists*.** Those are the
|
||||
places a parse can resume from: file scope, module and package bodies,
|
||||
generate regions and generate blocks, `begin`/`end` and `fork`/`join`
|
||||
bodies, function and task bodies, and a case item's statement. An error
|
||||
deeper inside a construct (a for-header, a port list, a case label) is not
|
||||
caught where it happens — it propagates out to the nearest enclosing list,
|
||||
and that whole item or statement becomes one error node. Nothing else in
|
||||
the grammar knows recovery exists.
|
||||
2. **Record, then skip.** The diagnostic is the `ParseError` the strict parser
|
||||
would have returned — same message, same line:col — plus the byte span of
|
||||
the token the parser gave up on.
|
||||
3. **Skip to a sync token.** From the failure point, skip forward until one
|
||||
of:
|
||||
- **`;`** — consumed; it terminated the broken construct.
|
||||
- a **sync-stop keyword** — *not* consumed, because the construct it closes
|
||||
or opens is somebody else's to parse (see the table below).
|
||||
- **end of file**.
|
||||
Brackets opened while skipping are skipped as a unit, so the `;`s inside a
|
||||
broken `for (i = 0; ...)` header do not end the skip early.
|
||||
4. **Wrap.** The text from where the failed construct started through the
|
||||
sync point becomes an `ItemKind::Error(RawText)` or
|
||||
`StmtKind::Error(RawText)` — a verbatim AST leaf exactly like `MacroCall`
|
||||
and `Directive` already are, carrying `text`, `col` and `span`.
|
||||
5. **Always advance.** If the failed construct consumed no tokens at all, the
|
||||
skip takes one anyway, so an enclosing loop can never spin.
|
||||
|
||||
### The sync tokens, and why each one
|
||||
|
||||
| token | consumed? | why |
|
||||
|---|---|---|
|
||||
| `;` | yes | The statement/declaration terminator: the one token that reliably ends a construct in this grammar, and the only one worth *eating* — the broken text ended there. |
|
||||
| `end`, `endmodule`, `endpackage`, `endgenerate`, `endfunction`, `endtask`, `endcase`, `join`, `join_any`, `join_none` | no | Each closes a construct whose parse loop is still on the stack. Consuming one would leave that construct unclosed and cascade the damage outward — this is exactly what "an error inside a generate block must not eat the `endgenerate`" means. `endcase` and the `join`s are in the set for the same reason the ones the task named are, and are cheap to add. |
|
||||
| `module`, `macromodule`, `package` | no | These can only *begin* a construct at file scope. Without them, garbage written between two modules skips forward looking for a `;` and swallows the second module's header. With them, garbage between two modules costs exactly one error node. |
|
||||
| end of file | — | Nothing left to sync to. |
|
||||
| a closing `)`/`]`/`}` **with a matching open in the skipped range** | yes | Part of the garbage being skipped. |
|
||||
| a closing `)`/`]`/`}` **with nothing open** | yes | Also skipped. Recovery only ever runs in an item or statement list, and no such list sits inside brackets, so a stray `)` belongs to the broken expression, not to a caller. Treating it as a stop point was tried first and made every leftover `)` of `assign x = (((1 + )));` its own error node — 26 diagnostics for one typo. |
|
||||
|
||||
### Unclosed constructs
|
||||
|
||||
The sync-token rules alone would turn a file whose `endmodule` is not typed
|
||||
yet into one file-sized error node — the single most common mid-edit state,
|
||||
and the one where an LSP most needs the tree. So two small companions:
|
||||
|
||||
- In tolerant mode a body loop also ends at any sync stop, not just at its own
|
||||
closing keyword. An unclosed `begin` therefore ends where the next construct
|
||||
begins instead of eating the rest of the file.
|
||||
- `expect_closer` (used for every `end*`/`join` keyword) records
|
||||
``expected `end` `` as a diagnostic instead of failing, and treats the
|
||||
construct as closed where the parser stopped.
|
||||
|
||||
The result: `module m; initial begin x = 1; endmodule` yields one diagnostic
|
||||
(missing `end`), a module with its `initial` block, and the block with its
|
||||
statement — no error node at all.
|
||||
|
||||
### A file that is all garbage
|
||||
|
||||
…becomes one error item covering it. So does a file the *lexer* rejects (see
|
||||
Assumptions), which is the only case where the tolerant tree carries no
|
||||
structure at all.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Recovery is a parse-level mechanism; the lexer stays all-or-nothing.** An
|
||||
unterminated string or block comment has no sensible resumption point
|
||||
(everything after it is inside the string), so `parse_source_tolerant` turns
|
||||
a `LexError` into one diagnostic plus one file-wide error item rather than
|
||||
guessing. Making the lexer tolerant is a separate, larger decision;
|
||||
truncated files hit this path often enough that it is worth revisiting if
|
||||
the LSP finds it too coarse.
|
||||
- **A missing `;` costs the construct after it.** The sync point is the next
|
||||
`;`, not the next line, so `wire a` (no semicolon) followed by `wire b;`
|
||||
produces one error node covering both. Line-based heuristics ("resync at a
|
||||
token that starts a line") would do better on this one shape and worse on
|
||||
wrapped constructs; the boring rule is the one that is predictable.
|
||||
- **A broken construct can produce more than one diagnostic.** A half-typed
|
||||
`for (i = 0; i < ; i = i + 1)` fails inside the header, resyncs at the `;`
|
||||
*inside* the header, and reports again on the remains. Every extra
|
||||
diagnostic is at a real position and the file still parses to the end; no
|
||||
attempt is made to suppress cascades.
|
||||
- **Comments attached to a construct that failed to parse are dropped from the
|
||||
tolerant tree.** They were harvested into the failed node's `Meta` before
|
||||
the error, and comments *inside* the skipped range survive only as bytes of
|
||||
the error node's raw text. This does not weaken CLAUDE.md invariant #3:
|
||||
that invariant is about what the *formatter* emits, and the formatter never
|
||||
parses tolerantly (see Handshakes). An LSP consuming a broken buffer can
|
||||
still reach every comment through the token stream.
|
||||
- **Every successful item/statement parse consumes at least one token.** The
|
||||
termination argument rests on it (with the always-advance rule covering the
|
||||
failure side). It is true of every arm in the grammar today; a future arm
|
||||
that could succeed on zero tokens would need the loops to guard against it.
|
||||
- **`source` must be the exact text the tokens were lexed from.**
|
||||
`parse_tolerant(tokens, source)` copies spans out of it; a mismatched string
|
||||
would put wrong text in the error nodes. `parse_source_tolerant(src)` is the
|
||||
entry point that cannot get this wrong, and is what callers should use.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Promised to `vlog_formatter` — the formatter must not format a file with
|
||||
diagnostics, and this round did not change how it formats anything:**
|
||||
|
||||
- `format_source` still calls `vlog_parser::parse_source`, i.e. the strict
|
||||
parser, which still fails on the **first** error and makes the CLI leave the
|
||||
file untouched. Error nodes cannot appear in a tree the formatter builds.
|
||||
- **Four lines were added to `format.rs` anyway, and they are the one thing
|
||||
this feature could not do inside its own crate**: adding a variant to
|
||||
`ItemKind`/`StmtKind` makes the formatter's exhaustive `match`es fail to
|
||||
compile, so each got one arm (`ItemKind::Error(d) => self.raw_text(d)`, and
|
||||
the statement twin) plus a comment saying it is unreachable from
|
||||
`format_source`. Verbatim pass-through was chosen over emitting nothing so
|
||||
that, if a future entry point ever did hand the formatter such a tree,
|
||||
`verify.rs`'s token-equivalence check would see the tokens rather than
|
||||
silently lose them. No behavior change: the full `.cases`, fixture,
|
||||
snapshot and idempotency suite is green with zero churn.
|
||||
- **`verify.rs` is untouched.** No normalization was added, broadened or
|
||||
weakened, so CLAUDE.md hard invariant #4 does not apply to this round.
|
||||
- When the LSP lands, its contract with the formatter is: *format only when
|
||||
the diagnostic list is empty*; otherwise publish the diagnostics and serve
|
||||
the partial tree for everything else (symbols, highlighting, hover).
|
||||
|
||||
**Consumed from `docs/features/recursion-limit/README.md` (the handshake that
|
||||
was written for this feature):** recovery **must not reset `depth` or
|
||||
`links`**. It does not touch either. It cannot need to: both are released by
|
||||
the gated frames themselves on every path out, including error paths
|
||||
(`leave()` after the inner call, `self.links = outer_links` after it), so by
|
||||
the time an error reaches the list loop that recovers, both counters are back
|
||||
at exactly that loop's level. Recovery resumes there. Two tests pin it — one
|
||||
white-box (both counters are 0 after a tolerant parse of a broken file), one
|
||||
black-box in each direction: 100 broken 25-deep expressions in a row produce
|
||||
100 diagnostics and never a `nesting too deep` (no leak), and a broken
|
||||
statement 55 blocks deep followed by 20 more blocks *does* produce one (no
|
||||
reset). Both were mutation-tested by injecting `self.depth = 0` and
|
||||
`self.depth += 1` into `recover`; each mutation fails a test.
|
||||
|
||||
**Consumed from `docs/features/spans/README.md`:** error nodes are ordinary
|
||||
AST leaves under the existing span convention — span = code extent, comments
|
||||
excluded, so a child's span nests inside its parent's. `tests/spans.rs`'s
|
||||
exhaustive nesting walker now runs over recovered trees too
|
||||
(`recovered_error_nodes_nest_inside_their_parent`), which is deliberate reuse:
|
||||
a new node shape cannot quietly skip the invariant. An error node's `text` is
|
||||
asserted to be its own source slice, so `source[span] == text` holds for the
|
||||
new leaf as it does for `RawText` elsewhere.
|
||||
|
||||
**Requested of nobody.** No other module needs a change.
|
||||
|
||||
## API
|
||||
|
||||
```rust
|
||||
// vlog_parser
|
||||
pub fn parse_source_tolerant(source: &str) -> (ast::SourceFile, Vec<ParseDiagnostic>);
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>);
|
||||
|
||||
pub struct ParseDiagnostic {
|
||||
pub message: String, // exactly what ParseError would have said
|
||||
pub line: u32, // 1-based, as on ParseError
|
||||
pub col: u32, // 1-based, in bytes
|
||||
pub span: TextRange, // extent of the token the parser gave up on
|
||||
}
|
||||
```
|
||||
|
||||
`ParseDiagnostic` displays as `line:col: message`, like `ParseError`. Its
|
||||
`span` and its `line:col` are two views of *the same token* — asserted, so a
|
||||
terminal that prints the position and an editor that highlights the range
|
||||
agree. The extent that was *skipped* is not on the diagnostic; it is the error
|
||||
node's span in the tree, which is where a consumer that wants it should look.
|
||||
|
||||
`parse(tokens)` and `parse_source(source)` are unchanged, including their
|
||||
signatures.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `parse_tolerant` / `parse_source_tolerant`; `ParseDiagnostic` with
|
||||
message, line, col and span.
|
||||
- [x] `ItemKind::Error(RawText)` / `StmtKind::Error(RawText)` leaves carrying
|
||||
the skipped text and its span.
|
||||
- [x] Sync-token set documented above; skipping balances brackets.
|
||||
- [x] Recovery at all nine item/statement list sites; nothing else in the
|
||||
grammar changed shape.
|
||||
- [x] Unclosed constructs: tolerant body-loop exit + `expect_closer`.
|
||||
- [x] Lex errors → one diagnostic + one file-wide error item.
|
||||
- [x] Guarantee (a): tolerant == strict on 500 valid sources (fixtures + every
|
||||
`.cases` input *and* expected output), asserted on the `Debug` shape of
|
||||
the whole tree, with zero diagnostics.
|
||||
- [x] Guarantee (b): diagnostics inside the file, positions consistent with
|
||||
spans, error-node text == its source slice, error nodes nest (in
|
||||
`tests/spans.rs`, via the existing exhaustive walker).
|
||||
- [x] Guarantee (c): budgets neither leak nor reset; mutation-tested.
|
||||
- [x] Guarantee (d): 5299 byte-prefix truncations of the fixtures, ~11k
|
||||
token-boundary truncations of the case-table sources (the exact count
|
||||
grows with the case table; QA re-measured 11570), and every
|
||||
single-character deletion of every fixture — no panic, no hang, all
|
||||
invariants hold on every one.
|
||||
- [x] Mid-edit shapes tested by name: missing `;`, unclosed `begin`, unclosed
|
||||
`module`, `wire [7:`, `sub u0 (.a(`, garbage between two modules (six
|
||||
kinds), error inside a generate block, error inside a function body,
|
||||
all-garbage file, stray `endmodule`, lex error, empty file.
|
||||
- [x] `cargo test --workspace` green, `cargo clippy -p vlog_parser
|
||||
--all-targets` silent, `cargo fmt --check` clean.
|
||||
- [x] TODO.md §6 error-tolerant checkbox.
|
||||
- [ ] **Not done, deliberately:** a tolerant *lexer*. See Assumptions.
|
||||
- [ ] **Not done:** cascade suppression (a "don't report twice within N
|
||||
tokens" rule). Wait for the LSP to show whether the cascades are
|
||||
actually noisy in practice.
|
||||
- [ ] **Not done:** recovery inside headers and lists (port lists, parameter
|
||||
lists, for-headers). Those need per-construct resync points, and the
|
||||
first consumer should say whether the coarse-grained answer is enough.
|
||||
Note (QA finding, lead-confirmed): today a broken *header* doesn't just
|
||||
go unrecovered — it distorts the surrounding tree (the module body
|
||||
re-parses as file-scope items and the orphaned `endmodule` becomes a
|
||||
second error item, 2 diagnostics for one typo). The LSP consumer
|
||||
should expect that shape until header recovery lands.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read CLAUDE.md, README.md, TODO.md §6, `docs/features/spans/README.md` and
|
||||
the recursion-limit Handshakes before touching code. Baseline:
|
||||
`cargo test --workspace` **161 passed**, clippy silent, fmt clean.
|
||||
- **Chose "recover in list loops only".** The alternative — recovery points
|
||||
inside every construct — multiplies the number of places that can invent a
|
||||
resync rule, and each one is a new way for the two entry points to diverge.
|
||||
One `item_or_recover` / `stmt_or_recover` pair, called from the nine loops
|
||||
that build a `Vec<Item>`/`Vec<Stmt>`, keeps the grammar code shared
|
||||
literally rather than by convention: every other function is untouched and
|
||||
cannot tell which mode it is running in.
|
||||
- **`tolerant` is a flag on `Parser`, not a second parser.** `parse` and
|
||||
`parse_tolerant` differ by that flag and by the `source` slice recovery
|
||||
copies error-node text from. Strict mode passes `""` because it never
|
||||
recovers, which is stated at the field.
|
||||
- **Two changes to the strict path's *shape*, none to its behavior**: body
|
||||
loop conditions moved into `at_body_end(kw)` (identical when `tolerant` is
|
||||
false) and `expect_kw("end…")` became `expect_closer("end…")` (identical
|
||||
error, identical message, when `tolerant` is false). The formatter's whole
|
||||
suite, including snapshots and `.cases`, is green with zero churn, and a
|
||||
unit test asserts strict parsing still stops at the *first* error with the
|
||||
same message tolerant mode files first.
|
||||
- **The stray-closing-bracket rule was wrong on the first try, and the tests
|
||||
caught it.** `)` with nothing open originally *stopped* the skip, on the
|
||||
theory that it belonged to an enclosing construct. It does not — recovery
|
||||
never runs inside brackets — and the price was one error node per leftover
|
||||
`)`: the 100-broken-expressions budget test reported 2600 diagnostics
|
||||
instead of 100, and the depth-limit test 32 instead of 1. Skipping them
|
||||
fixed both and is what the table above now documents.
|
||||
- **Unclosed constructs got two companions on purpose.** With sync tokens
|
||||
alone, `module m; wire a;` (no `endmodule` yet) is one file-sized error node
|
||||
— i.e. the tolerant parser would be useless in the state an editor is in
|
||||
most often. The tolerant body-loop exit plus `expect_closer` cost about
|
||||
fifteen lines and turn that case into "one diagnostic, whole tree intact".
|
||||
- **Comments attached to a failed construct are dropped from the tree** — they
|
||||
went into the failed node's `Meta` before the error was raised, and pulling
|
||||
them back out would mean restructuring where `take_meta` is called. Wrote it
|
||||
down in Assumptions instead of hiding it; it is sound only because the
|
||||
formatter never parses tolerantly, which is the handshake above.
|
||||
- **Reused `tests/spans.rs`'s exhaustive nesting walker** for the recovered
|
||||
trees rather than writing a second one. It is compiler-checked exhaustive,
|
||||
so the new leaves had to be handled there anyway; running it on broken
|
||||
sources costs ten lines and makes the nesting guarantee total.
|
||||
- **Mutation-tested the budget claim rather than asserting it from the code**:
|
||||
`self.depth = 0` in `recover` fails both budget tests, `self.depth += 1`
|
||||
fails the leak test. Reverted; `grep MUTATION` is 0.
|
||||
- **Probed behavior with a throwaway `examples/probe.rs`** (mid-edit shapes,
|
||||
then every byte prefix of every fixture) before writing any assertions, so
|
||||
the tests encode measured behavior rather than hoped-for behavior. The
|
||||
example was deleted; it is not part of the diff.
|
||||
- Did not touch `verify.rs`, `tools/`, `corpus/`, or `crates/vfmt`. Did not
|
||||
run `git commit`/`git push`.
|
||||
- **Concurrency note:** another agent's format-off-fence work
|
||||
(`crates/vlog_formatter/src/fence.rs`, `doc.rs`, `format.rs`, `printer.rs`,
|
||||
`docs/features/format-fences/`) is live in the same working tree. My only
|
||||
edit inside that crate is the four lines described in Handshakes, made with
|
||||
exact-string edits so their in-progress work was not disturbed; their diff
|
||||
in `format.rs` is untouched around them. One clippy warning currently comes
|
||||
from their `fence.rs:58` (`map_or` → `is_none_or`) — theirs to fix, left
|
||||
alone; `cargo clippy -p vlog_parser --all-targets` is silent.
|
||||
|
||||
**Results:** `cargo test --workspace` **188 passed, 0 failed** (up from 161:
|
||||
+2 `vlog_parser` unit tests, +19 in the new `tests/error_recovery.rs`, +1 in
|
||||
`tests/spans.rs`; the rest is the concurrent fence work). `cargo clippy -p
|
||||
vlog_parser --all-targets` silent. `cargo fmt --all --check` clean. Files
|
||||
touched: `crates/vlog_parser/src/{parser,ast,lib}.rs`,
|
||||
`crates/vlog_parser/tests/error_recovery.rs` (new),
|
||||
`crates/vlog_parser/tests/spans.rs` (one test + two match arms),
|
||||
`crates/vlog_formatter/src/format.rs` (four lines, see Handshakes), `TODO.md`
|
||||
(§6 checkbox), this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
Read CLAUDE.md, this README, the diffs in `crates/vlog_parser/src/{lib,ast,parser}.rs`,
|
||||
`crates/vlog_parser/tests/{error_recovery.rs,spans.rs}`, and the four added
|
||||
`format.rs` match arms before testing. Scope: `-p vlog_parser`; did not touch
|
||||
the concurrent format-fences work. Verdict: **no BLOCKING findings.** All
|
||||
claims verified, two LOW-severity documentation/behavior notes below.
|
||||
|
||||
**Tool results (exact):**
|
||||
- `cargo test -p vlog_parser`: unit 49 passed, `error_recovery.rs` 19 passed,
|
||||
`spans.rs` 12 passed — 80/80, 0 failed.
|
||||
- `cargo clippy -p vlog_parser --all-targets`: silent, 0 warnings.
|
||||
- `cargo fmt --check -p vlog_parser`: clean.
|
||||
- `cargo test --workspace`: green, 194 passed total (up from the dev's
|
||||
logged 188 — the delta is the concurrent format-fences suite, confirmed by
|
||||
reading its test file names, not this feature).
|
||||
- `cargo test -p vlog_formatter`: 55/55 green (8+1+4+6+2+32+0 doctests) — the
|
||||
strict-path/snapshot/`.cases`/idempotency suite has zero churn from this
|
||||
feature, confirming the Handshakes claim.
|
||||
|
||||
**Claim 1 (parse/parse_source unchanged, one Parser + tolerant flag):** PASS.
|
||||
Traced the code: `parse`/`parse_source` build `Parser::new(tokens, "", false)`;
|
||||
every recovery call site (`item_or_recover`/`stmt_or_recover`) only diverges
|
||||
from the strict `Err` propagation when `self.tolerant` is true (`Err(e) if
|
||||
self.tolerant => …`, `other => other`), so strict mode is byte-identical to
|
||||
before. `strict_parsing_still_stops_at_the_first_error` (parser.rs) and
|
||||
`format_source`'s green suite both confirm no observable change.
|
||||
|
||||
**Claim 2 (sync tokens, bracket balancing, stray closers, unclosed
|
||||
constructs):** PASS on every sub-claim, confirmed both by the dev's own
|
||||
tests and independently in a scratch harness
|
||||
(`/private/tmp/…/scratchpad/qa_probe`, deleted nothing in-repo):
|
||||
- `module`/`endmodule`/`endgenerate`/`join*` etc. correctly left unconsumed
|
||||
even when the literal text "module" appears inside a *string* or a
|
||||
*comment* inside a broken construct — the lexer tags those as
|
||||
`String`/`Comment` tokens, not `Keyword`, so `at_sync_stop` never
|
||||
misfires on them. Verified with three adversarial sources (`"module
|
||||
fake"` in a string, `// … module …` in a line comment, `/* module … */`
|
||||
in a block comment) — each produced exactly 1 diagnostic, no false stop.
|
||||
- Stray closing brackets do not cascade: 50 consecutive stray `)` between
|
||||
two modules collapsed into **one** error node / one diagnostic, not 50 —
|
||||
matches the work log's account of the fix.
|
||||
- Unclosed constructs: `module m; initial begin x=1; endmodule` shape
|
||||
(dev's own `an_unclosed_begin_keeps_the_statements_inside_it`) gives
|
||||
exactly 1 diagnostic (`expected \`end\``), both statements intact, zero
|
||||
error nodes. Confirmed.
|
||||
- Bracket-balanced skipping confirmed at 10 levels of nested `generate`/`if`
|
||||
with a broken `wire ;` at the bottom: 1 diagnostic, the error node sits at
|
||||
the correct innermost level, and the outer 10 levels of structure plus the
|
||||
module's trailing sibling item are all intact (probe5/probe2 output).
|
||||
|
||||
**Claim 3a (tolerant == strict on ≥500 valid sources):** PASS. Dev's test
|
||||
reports 550 valid sources (fixtures + `.cases` inputs/outputs), all
|
||||
Debug-equal, all zero-diagnostic. Independently re-verified with my own
|
||||
extractor (not reusing `tests/error_recovery.rs`'s helper) over 30
|
||||
pseudo-randomly sampled `.cases` inputs: 30/30 consistent (Debug-equal tree,
|
||||
empty diagnostics).
|
||||
|
||||
**Claim 3b (spans, char-boundary safety, LineIndex agreement, nesting):**
|
||||
PASS. Independently re-checked char-boundary-safety and
|
||||
`LineIndex::offset` agreement on a case the dev's `BROKEN` list doesn't
|
||||
include — a BOM-prefixed file (`\u{FEFF}module m; …`), both well-formed and
|
||||
broken — no panic, diagnostic span is in-file and char-boundary-safe, and
|
||||
`LineIndex::offset(line, col) == span.start` held. `spans.rs`'s exhaustive
|
||||
walker running over `recovered_error_nodes_nest_inside_their_parent`
|
||||
confirmed as claimed.
|
||||
|
||||
**Claim 3c (depth/links neither leak nor reset):** PASS, and independently
|
||||
stress-tested beyond the dev's fixed-shape tests: 50 valid expression chains
|
||||
each at `MAX_CHAIN_LENGTH - 1` (255 links), each interleaved with a broken
|
||||
statement forcing a recovery in between — 50 diagnostics (one per broken
|
||||
statement), **zero** `chain too long` / `nesting too deep` anywhere (no
|
||||
leak across the 50 recoveries), and all 100 items survived as siblings of
|
||||
the module. Complement: one expression at 306 links (over the 256 limit)
|
||||
between two good statements produced **exactly one** diagnostic
|
||||
(`expression chain too long (limit 256)`), recovered as a single clean
|
||||
error node, with both the preceding and following good statements intact
|
||||
in the tree — the "restore discipline" claim holds in both directions.
|
||||
|
||||
**Claim 3d (no panic, extended):** PASS. Re-ran the dev's approach and then
|
||||
extended it: independently re-implemented the `.cases`-file input extractor
|
||||
(not reusing the dev's) and byte-truncated (not just token-boundary) every
|
||||
`.cases` **input** section at every char-boundary offset — 21,988 cuts,
|
||||
well under the 3-minute time-box (66 ms), zero panics, all spans in-file and
|
||||
char-boundary-safe. A second independent pass did token-boundary truncation
|
||||
(5,510 cuts) with the same result. Also fuzzed: `;;;;` alone (2 diagnostics,
|
||||
each swallowing two `;`s per the always-advance rule — expected, not a
|
||||
bug), a 1 MB file of only `;` (500,000 diagnostics/items, 344 ms release
|
||||
build, no hang), an unterminated string at EOF and an unterminated block
|
||||
comment (both correctly hit the lex-error path: 1 diagnostic, 1 file-wide
|
||||
error item), and a BOM'd file (no panic; see note below). None panicked.
|
||||
|
||||
**Minor discrepancy in claim 3d's exact number:** the README's Status/TODO
|
||||
line says "10756 token-boundary truncations of the case-table sources";
|
||||
re-running the *exact same* dev test today (`cargo test -p vlog_parser
|
||||
--test error_recovery -- --nocapture truncating_a_case_table_source_never_panics`)
|
||||
prints **11570**. The byte-prefix number (5299) still matches exactly. The
|
||||
drift is because the case-table corpus has grown since that number was
|
||||
written (concurrent `.cases` files added by other in-flight feature work in
|
||||
this same tree), not a functional problem — but a number stated this
|
||||
precisely will keep silently rotting as the corpus grows. Suggest wording
|
||||
it approximately (or dropping the exact count) rather than re-chasing it
|
||||
every time a `.cases` file is added.
|
||||
|
||||
**Claim 4 (lex errors are all-or-nothing):** PASS. Confirmed via dev tests
|
||||
plus independently on an unterminated string, an unterminated block
|
||||
comment, and a BOM'd file — each produces exactly one diagnostic and one
|
||||
file-wide `ItemKind::Error` covering the whole source, never a partial tree.
|
||||
|
||||
**Claim 5 (tool results, unreachable format.rs arms):** PASS. Tool results
|
||||
above. Confirmed the two added `format.rs` arms
|
||||
(`ItemKind::Error(d) => self.raw_text(d)` at line 493,
|
||||
`StmtKind::Error(d) => self.raw_text(d)` at line 1565) are exact-string
|
||||
minimal (one line of code each, plus a comment) and genuinely unreachable
|
||||
from `format_source`: `format_once` calls `vlog_parser::parse_source`,
|
||||
which is strict (`tolerant: false`), and `ItemKind::Error`/`StmtKind::Error`
|
||||
are constructed *only* inside `item_or_recover`/`stmt_or_recover`'s
|
||||
`Err(e) if self.tolerant` arm — a path strict parsing never takes. `git
|
||||
diff --stat crates/vlog_formatter/src/verify.rs` is empty, confirming
|
||||
"`verify.rs` is untouched" (CLAUDE.md invariant #4 does not apply to this
|
||||
round, as claimed).
|
||||
|
||||
**Finding — LOW, non-blocking (header/list recovery produces a garbage
|
||||
tree, not a clean single failure):** the README's Status/TODO already
|
||||
records header/port-list/for-header recovery as **not done**, and asked me
|
||||
to check which of the two documented possibilities ("clean single failure"
|
||||
vs. "garbage tree") actually happens. Answer: **garbage tree.** For
|
||||
`module m #(parameter W = , parameter X = 4) (input a); wire ok;
|
||||
endmodule`, the tree is *not* one error item — it's three top-level items:
|
||||
one error item covering the header through its closing `;`, then `wire ok;`
|
||||
re-parsed as an ordinary **top-level** `DataDecl` item (not inside any
|
||||
module — semantically wrong shape for the tree), then a second, spurious
|
||||
error item covering the orphaned `endmodule` keyword. That's 2 diagnostics
|
||||
for one typo, and a module body statement now appears to live at file
|
||||
scope. This doesn't break any stated guarantee (the module's body content
|
||||
is still `src[span]`-correct in whichever node it ends up in, and nothing
|
||||
panics), and it's explicitly flagged as a follow-up decision for "the first
|
||||
consumer" in the TODO — but "not covered" undersells it: it's not just that
|
||||
the header itself isn't recovered, the *tree shape after it* is
|
||||
misleading. Recommend the Assumptions section say this explicitly (a header
|
||||
failure produces extra, oddly-placed items/diagnostics, not just "one
|
||||
failure covering the header") so a future LSP author isn't surprised.
|
||||
Reproduction: see probe5 sources above; any of the four listed there
|
||||
reproduces it.
|
||||
|
||||
**Finding — LOW, out of scope for this feature (BOM lex-error message is
|
||||
mojibake, pre-existing):** a BOM-prefixed file (`\u{FEFF}module m; …`)
|
||||
correctly takes the lex-error path (1 diagnostic, 1 file-wide error item,
|
||||
no panic, span char-boundary-safe and in-file — all of this feature's
|
||||
guarantees hold). But the message itself, `"unexpected character 'ï'"`, is
|
||||
mojibake: it looks like the lexer is decoding a single byte of the BOM's
|
||||
UTF-8 encoding rather than the codepoint. `crates/vlog_parser/src/lexer.rs`
|
||||
is untouched by this diff (`git diff --stat` confirms), so this is
|
||||
pre-existing and out of this feature's scope — flagging for whoever next
|
||||
touches `lexer.rs`, since BOM'd files are a common artifact from
|
||||
Windows/VS Code and will reach the LSP path this feature exists to serve.
|
||||
|
||||
**CLAUDE.md compliance:** public items documented (`ParseDiagnostic` and its
|
||||
fields, `parse_tolerant`, `parse_source_tolerant`, `ItemKind::Error`,
|
||||
`StmtKind::Error` all carry doc comments). No `unwrap()`/`expect()`/`panic!`
|
||||
in library code paths — the three hits from `grep` are inside
|
||||
`#[cfg(test)] mod tests`, which CLAUDE.md permits. README has all required
|
||||
sections, current and honest (TODO.md §6 checkbox matches what's actually
|
||||
shipped, non-goals — tolerant lexer, cascade suppression, header/list
|
||||
recovery — are recorded). Did not edit the Review section.
|
||||
|
||||
**Not independently reproduced:** the mutation-testing claim in the
|
||||
Handshakes section (`self.depth = 0` / `self.depth += 1` injected into
|
||||
`recover`, each failing a test) — took it on the dev's word since
|
||||
mutating shipped code to re-verify a already-passing regression class
|
||||
was judged lower value than the adversarial probing above; the black-box
|
||||
budget tests (3c) independently exercise the same invariant from the
|
||||
outside and passed.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with
|
||||
format-fences (the two features interlock in `format.rs` via the new
|
||||
`Error` variants' match arms, so separate commits would not compile).**
|
||||
|
||||
The LSP's parser is now real: never fails, positioned diagnostics,
|
||||
Error leaves that obey the span nesting invariant, and — the part that
|
||||
took discipline — the strict path provably untouched (shared grammar
|
||||
code with a flag, not a fork; byte-identical behavior traced by QA).
|
||||
The evidence standard here was the best yet: truncation fuzz at byte
|
||||
and token granularity (27k+ cuts, zero panics), budget guarantees
|
||||
mutation-tested in both directions, and the stray-closer cascade bug
|
||||
caught by the dev's own tests before QA ever saw it.
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **Sync-token set**: consuming `;` but not the closers/openers is the
|
||||
right asymmetry, and treating `module`/`package` as recovery
|
||||
openers is what keeps garbage from swallowing the next module.
|
||||
Bracket-balanced skipping (the `;`-inside-broken-for case) is the
|
||||
subtle rule; it's tested.
|
||||
2. **Lex errors stay all-or-nothing** — honest scoping; a tolerant
|
||||
lexer is its own feature and the Assumption says so.
|
||||
3. **The 4 exhaustive-match arms in format.rs** were structurally
|
||||
unavoidable, exact-string minimal, and QA traced their
|
||||
unreachability from `format_source`. Accepted as the one
|
||||
cross-scope touch.
|
||||
4. QA's low findings both addressed at review: the truncation count is
|
||||
now stated approximately (it grows with the case table), and the
|
||||
Assumptions now say plainly that a broken *header* distorts the
|
||||
surrounding tree shape (2 diagnostics, body re-parsed at file
|
||||
scope) — the LSP consumer must expect that until header recovery
|
||||
lands. Cascade suppression and header recovery remain deliberate
|
||||
non-goals awaiting a real consumer.
|
||||
|
||||
The BOM mojibake message QA noticed in passing is a lexer
|
||||
message-quality nit; it can ride with the `@(* )` lexer item already
|
||||
on TODO §1.
|
||||
@@ -0,0 +1,566 @@
|
||||
# format-fences
|
||||
|
||||
## Goal
|
||||
|
||||
Let an author switch the formatter off for a stretch of code with
|
||||
`// verilog_format: off` … `// verilog_format: on` (Verible's spelling, plus a
|
||||
short `// vfmt: off` / `// vfmt: on` alias) and get those bytes back exactly
|
||||
as they were written. Hand-aligned lookup tables, generated blocks, and
|
||||
column-aligned instance connections are the cases every RTL codebase has;
|
||||
without an escape hatch they are the reason a formatter never gets adopted.
|
||||
The region is emitted as a raw slice of the original source — the AST inside
|
||||
it is never consulted — so "verbatim" is true by construction rather than by
|
||||
careful re-printing. This is the first consumer of the byte spans landed by
|
||||
`docs/features/spans/README.md`.
|
||||
|
||||
## Fence grammar
|
||||
|
||||
A fence is a **line comment** whose text, after stripping the leading `//` and
|
||||
trimming whitespace on both sides, is *exactly* one of:
|
||||
|
||||
```
|
||||
verilog_format: off vfmt: off
|
||||
verilog_format: on vfmt: on
|
||||
```
|
||||
|
||||
Consequences, all deliberate and all tested:
|
||||
|
||||
- `//verilog_format: off` (no space) and `// vfmt: on ` are fences —
|
||||
the text is trimmed. `// verilog_format:off` is **not** (no space after the
|
||||
colon; the match is exact, not fuzzy).
|
||||
- **A fence with trailing text is not a fence.** `// vfmt: off (for now)`
|
||||
formats as an ordinary comment. Rationale: the alternative — prefix
|
||||
matching — silently turns `// vfmt: off-by-one bug here` into a formatting
|
||||
switch, and a fence that fires by accident is worse than one that does not
|
||||
fire at all. If the author wants a note, it goes on its own line.
|
||||
- **Block comments are not fences.** `/* verilog_format: off */` is an
|
||||
ordinary comment. Restricting fences to `//` keeps a fence a whole-line
|
||||
thing and keeps the region boundaries at line granularity.
|
||||
- **A fence must be a leading comment**, i.e. it must start a line (nothing
|
||||
but whitespace, or another comment, before it on that line). A comment on
|
||||
the same line as preceding *code* is attached to that code as *trailing*
|
||||
trivia, and `Meta.trailing` is an `Option<String>` with no span — there is
|
||||
nothing to splice from. So `wire a; // vfmt: off` is an ordinary comment.
|
||||
See Handshakes for the parser change that would lift this.
|
||||
- The alias and the long form are interchangeable: an `off` in either
|
||||
spelling is closed by an `on` in either spelling.
|
||||
|
||||
## Semantics
|
||||
|
||||
Fences select whole **items** (module items, package items, top-level items),
|
||||
Verible-style. Think of an item list as a flat stream of *units*: each item's
|
||||
leading comments, then the item's own code (its `(* … *)` attributes and
|
||||
trailing comment included), and finally the scope's dangling comments.
|
||||
|
||||
- A region **opens** at the first `off` fence in that stream and **closes**
|
||||
at the first `on` fence after it. The emitted byte range runs from the
|
||||
first byte of the `off` fence's line through the last byte of the `on`
|
||||
fence — the fence comments themselves are part of the region.
|
||||
- Everything in between — items, their comments, their attributes — is
|
||||
skipped by the formatter and comes out of the source slice instead.
|
||||
- **Indentation is preserved, including on the region's first line.** The
|
||||
region starts at the *start of the line* the `off` fence sits on (when only
|
||||
whitespace precedes it there), and the printer emits the slice at column 0,
|
||||
so every line of the region is byte-identical to the input. Normal
|
||||
formatting, at the enclosing indent level, resumes on the line after the
|
||||
region.
|
||||
- **A second `off` inside an open region is a no-op**, as is an `on` with no
|
||||
open `off`; both are just bytes inside the region, or an ordinary comment.
|
||||
Fences do not nest and do not count.
|
||||
- **An unmatched `off` runs to the end of its scope** — the last byte of the
|
||||
containing item list, which is the end of the last item (its same-line
|
||||
trailing comment included) or of the last dangling comment, whichever comes
|
||||
last. At file scope that is the last byte of content in the file. It does
|
||||
**not** leak into the enclosing scope: an `off` inside a module body is
|
||||
closed by the module's `endmodule` at the latest, and an `on` written after
|
||||
`endmodule` belongs to the file scope and cannot close it.
|
||||
- **Fences never cross a scope boundary**, which is what keeps a region
|
||||
aligned with item boundaries: a region can never end in the middle of an
|
||||
item, so the formatter never has to print half of one.
|
||||
|
||||
### Out of scope this round: statement-level fences
|
||||
|
||||
A fence inside an item body — between two statements in an `always` block,
|
||||
between two case items, inside a port list — **has no effect**. It is
|
||||
formatted as an ordinary comment. Only `Item` lists are fenceable:
|
||||
|
||||
| fenceable scope | |
|
||||
|---|---|
|
||||
| file | `SourceFile.items` + `dangling` |
|
||||
| package body | `ItemKind::Package` |
|
||||
| module body | `Module.items` + `dangling` |
|
||||
| `generate` region | `ItemKind::GenerateRegion` |
|
||||
| generate `begin`…`end` | `GenBlock` with `is_block` |
|
||||
|
||||
Not fenceable: statement lists (`begin`/`end`, `fork`, function/task bodies),
|
||||
case-item lists, port/parameter/connection lists, and the single-item body of
|
||||
a bodyless `if (X) item;` in a generate (there is no list for a fence to end
|
||||
in, and the formatter lays that item out inside a `Group`).
|
||||
|
||||
The interaction worth knowing: an `off` at item level whose matching `on` was
|
||||
written inside a *statement* is an unmatched `off`, so it runs to the end of
|
||||
the item list rather than stopping at the `on`. That errs toward *more*
|
||||
verbatim text, never toward reformatting something the author fenced off.
|
||||
|
||||
## Splice mechanics
|
||||
|
||||
`fence::collect(src, &file)` walks the item scopes once, before any
|
||||
formatting, and returns a sorted, non-overlapping `Vec<Region>`:
|
||||
|
||||
```rust
|
||||
struct Region { fence: usize, start: usize, end: usize }
|
||||
// ^ the `off` comment's own first byte (identity)
|
||||
// ^ first byte emitted (start of that line)
|
||||
// ^ one past the last byte emitted
|
||||
```
|
||||
|
||||
Regions found inside an already-fenced range are dropped: the items holding
|
||||
them are never formatted, so their fences never run. Because a region is
|
||||
`[fence, end)` in a scope's own unit order and scopes nest, dropping any
|
||||
region whose `fence` falls before the previous region's `end` leaves a list
|
||||
that is sorted by both ends — so lookup is a `partition_point`.
|
||||
|
||||
During formatting, `Fmt` carries the source text and that list, and asks one
|
||||
question per unit:
|
||||
|
||||
| unit | test | result |
|
||||
|---|---|---|
|
||||
| a comment | it *is* a region's `off` fence | emit `Doc::Verbatim(src[start..end])` |
|
||||
| a comment | it starts inside a region | emit nothing |
|
||||
| an item's code | `item.span.start` is inside a region | emit nothing |
|
||||
|
||||
`Doc::Verbatim` is a new printer instruction: it strips the indentation the
|
||||
preceding line break just wrote and copies its string through untouched,
|
||||
newlines and all. That is the whole of "emit the original bytes".
|
||||
|
||||
An item whose code is skipped but whose leading comments are not (a `doc`
|
||||
comment above the `off` fence) still emits those comments — comments are
|
||||
never dropped. An item that emits nothing at all contributes no separator
|
||||
either, so no stray blank lines appear where the region swallowed items.
|
||||
|
||||
### Boundary / join decisions
|
||||
|
||||
- **Before the region**: the usual item separator, blank-line-aware, driven
|
||||
by the `off` fence comment's own `blank_before` flag (which is also the
|
||||
item's, since a `Meta`'s `blank_before` is its first leading comment's).
|
||||
A blank line before `// vfmt: off` survives; two or more collapse to one,
|
||||
as everywhere else.
|
||||
- **First line of the region**: byte-exact, because the region starts at the
|
||||
line start, not at the `//`. The exception is a fence preceded on its own
|
||||
line by *another comment* (`/* a */ // vfmt: off`): there the region starts
|
||||
at the `//`, and the other comment is formatted onto the line above. Still
|
||||
idempotent — on the next pass the fence does start its line.
|
||||
- **Inside the region**: nothing is touched, trailing whitespace on interior
|
||||
lines included. `Doc::Verbatim` copies bytes; the printer's
|
||||
trailing-space trimming only ever fires on line breaks *it* emits.
|
||||
- **After the region**: a `HardLine` at the enclosing indent, so the next
|
||||
item starts correctly indented on a fresh line. The blank line between the
|
||||
`on` fence and the next item is dropped, which is exactly what already
|
||||
happens between an item's last leading comment and the item itself.
|
||||
- **Region ends at end of file**: the `format_once` tail normalization
|
||||
(strip trailing blank space, add one `\n`) applies as usual, so the file
|
||||
still ends in exactly one newline.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Fence comments arrive as `Meta.leading` comments with correct spans.**
|
||||
Guaranteed by the lexer's attachment phase (a comment not on the same line
|
||||
as a preceding token becomes leading trivia) and by `docs/features/spans`.
|
||||
- **A node's span is its code extent, attributes included, comments
|
||||
excluded** — the `spans` convention. Both halves are load-bearing: the
|
||||
attribute half is why splicing an item reproduces its `(* keep *)`, and the
|
||||
comment half is why an item's leading comments can be emitted while its
|
||||
code is skipped.
|
||||
- **The formatter is only reachable through `format_source(&str)`**, so the
|
||||
source text spliced from is always the exact text the spans were lexed
|
||||
from. There is no AST-taking entry point that could pair a tree with a
|
||||
different string.
|
||||
- **A leading comment precedes its item's span.** One case can violate it —
|
||||
an attribute followed by a comment (`(* x *)` newline `// c` newline
|
||||
`wire a;`), where `Meta.leading` holds a comment positioned *after*
|
||||
`item.span.start`. Fence detection skips such comments outright rather than
|
||||
building a region that would double-emit the attribute.
|
||||
- **Slicing is char-boundary safe** because every offset comes from a span or
|
||||
from a scan over ASCII delimiters. The slice is still taken with `get()`:
|
||||
if it were ever `None` the region comes out empty, `verify_equivalence`
|
||||
rejects the output, and the file is left untouched — a failsafe, not a
|
||||
panic.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:**
|
||||
|
||||
- `Comment.span` / `Comment.text` / `Comment.blank_before` — the fence
|
||||
matcher and the region boundaries.
|
||||
- `Item.span` (code extent, attributes in, comments out) — region membership
|
||||
for an item's code.
|
||||
- The item-scope shapes: `SourceFile{items,dangling}`, `Module`,
|
||||
`ItemKind::Package`, `ItemKind::GenerateRegion`, `GenBlock`, `GenIf`,
|
||||
`GenFor`, `GenCase`.
|
||||
|
||||
Nothing in `crates/vlog_parser` was changed, and nothing new is required of
|
||||
it for this feature to work as documented.
|
||||
|
||||
**Requested of `vlog_parser` (optional, not blocking):** a span on
|
||||
`Meta.trailing`. Today it is an `Option<String>`, which is why a fence
|
||||
written after code on the same line (`wire a; // vfmt: off`) cannot be
|
||||
honoured — there is no offset to start the region at. If trailing comments
|
||||
ever grow spans (they already exist on `Token.trailing`; `Meta` drops them
|
||||
during harvest), this feature can accept same-line fences by starting the
|
||||
region at the *following* line. Until then the limitation is documented
|
||||
above. This is a request, not a change: no parser file was touched.
|
||||
|
||||
**Promised to `vlog_formatter` callers:** none of the public API changed.
|
||||
`format_source` has the same signature and the same contract.
|
||||
|
||||
**`verify.rs` is untouched.** No normalization was added, broadened or
|
||||
weakened, so CLAUDE.md hard invariant #4 does not apply to this round, and
|
||||
none was needed: a fenced region is *source bytes*, so it re-lexes to exactly
|
||||
the tokens and comments it came from, and the units it replaces are exactly
|
||||
the ones whose bytes it contains. Equivalence therefore holds by
|
||||
construction, and the check runs unchanged as the backstop that catches any
|
||||
mistake in that reasoning (an off-by-one region end would drop or duplicate a
|
||||
token and be rejected).
|
||||
|
||||
**Recursion budget (`docs/features/recursion-limit/README.md`):** unaffected.
|
||||
`fence::collect` recurses only through nested *item* scopes, which is a
|
||||
subset of the AST depth the parser already bounds at 320 layers, and it
|
||||
builds no new tree. `Doc::Verbatim` is a leaf.
|
||||
|
||||
**`Doc` gained one variant.** `Doc::Verbatim(String)` — source bytes at
|
||||
column 0, newlines included. It is treated as containing a hard line
|
||||
(`contains_hard_line`, `Printer::fits`), so it can never be measured for a
|
||||
flat layout. The one contract it relies on: it is only ever emitted right
|
||||
after a line break or at the very start of the output, which is where the
|
||||
"strip the indentation just written" step is correct. Both current emitters
|
||||
(`Fmt::leading_comments`, `Fmt::dangling`) satisfy that.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `fence.rs`: `fence_of(&str) -> Option<Fence>` exact matcher, with unit
|
||||
tests for every accept/reject spelling.
|
||||
- [x] `fence.rs`: `collect(src, &SourceFile) -> Vec<Region>` over the five
|
||||
fenceable scope shapes, nested-region drop, unmatched-to-end-of-scope.
|
||||
- [x] `Doc::Verbatim` + printer support (`print`, `fits`,
|
||||
`contains_hard_line`).
|
||||
- [x] `format.rs`: `Fmt { src, regions }`, fence-aware `leading_comments` /
|
||||
`dangling` / `item_seq` / `item_docs`; separators suppressed for units
|
||||
the region swallowed.
|
||||
- [x] `tests/cases/fences.cases` — 25 table cases (each also asserts
|
||||
idempotency and, through `format_source`, equivalence).
|
||||
- [x] `tests/fences.rs` — 6 tests: byte-exactness, own-indentation,
|
||||
unmatched-off scoping, comment preservation, matcher/formatter
|
||||
agreement, and five hand-built corrupted-region pairs the safety net
|
||||
must reject.
|
||||
- [x] README.md Style section mentions fences.
|
||||
- [x] TODO.md §2 fences item checked.
|
||||
- [ ] **Not done, deliberately:** statement-level fences (documented above).
|
||||
- [ ] **Not done:** same-line (`trailing`-trivia) fences — blocked on a
|
||||
parser change, see Handshakes.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, `README.md`, TODO.md §2/§5, and the Handshakes of
|
||||
`spans` and `recursion-limit` first. Baseline before touching anything:
|
||||
`cargo test --workspace` **161 passed** (`vlog_formatter` 42), clippy
|
||||
silent, fmt clean.
|
||||
- **Chose "region = raw source slice" over "re-print the AST unchanged"**
|
||||
without much deliberation — it is the only version where verbatim is a
|
||||
fact rather than a claim, and it is what makes the safety net green by
|
||||
construction instead of by argument.
|
||||
- **Chose exact-match fence text over prefix matching.** A prefix match makes
|
||||
`// vfmt: off-by-one` a formatting switch. Exact match's failure mode is a
|
||||
fence that does not fire, which the author sees immediately in the diff.
|
||||
- **Fences are leading comments only, and only line comments.** The leading
|
||||
restriction is forced: `Meta.trailing` is an `Option<String>` and carries no
|
||||
span, so there is no byte offset to start a region at, and `vlog_parser` is
|
||||
owned by another agent this round. Recorded as a Handshake request rather
|
||||
than worked around. The line-comment restriction is a choice: it keeps a
|
||||
fence a whole-line thing.
|
||||
- **Region starts at the line start, not at the `//`.** First version sliced
|
||||
from `comment.span.start`, which left the region's first line re-indented by
|
||||
the printer while every other line kept its source indentation — visibly
|
||||
asymmetric on a mis-indented fence. Extending the start to the beginning of
|
||||
the line (only when nothing but whitespace precedes) makes the whole region
|
||||
byte-exact, and needed a new `Doc::Verbatim` so the printer would stop
|
||||
prepending its own indent.
|
||||
- **`Doc::Verbatim` rather than reusing `Doc::Text`.** `Text` is documented as
|
||||
newline-free and the printer counts its width; a variant states the "bytes,
|
||||
column 0, forces a break" contract instead of leaving it implicit. One
|
||||
existing caller (`raw_text` on a string that crosses a line) still abuses
|
||||
`Text` — left alone, out of scope.
|
||||
- **Unmatched `off` needed a trailing-comment scan.** The scope end is the
|
||||
last item's `span.end`, and an item's same-line trailing comment sits
|
||||
*after* it with no span of its own. Without the scan, `wire a; // note`
|
||||
inside an unmatched region dropped `// note` — hard invariant #3. Found by
|
||||
reasoning about `Meta.trailing`'s missing span before writing the test, then
|
||||
pinned by `unmatched_off_keeps_a_trailing_comment` and a `.cases` entry.
|
||||
The matched case needs no scan: the `on` fence is later in the stream, so
|
||||
the trailing comment is inside the range already.
|
||||
- **Separator suppression was the second bug of construction.** An item whose
|
||||
code is swallowed still emitted the `HardLine` its last leading comment
|
||||
asked for, and then `item_seq` added the next item's separator on top —
|
||||
a blank line after every region. `item_docs` now drops that dangling
|
||||
`HardLine` when the code is skipped, and `item_seq`/`dangling`/`file`
|
||||
separate on "did this unit emit anything" instead of on the index. With no
|
||||
fences present the two formulations are identical, which is why the
|
||||
existing suite shows zero churn.
|
||||
- **Guarded the attribute-then-comment ordering case** (`(* x *)` on one line,
|
||||
a comment on the next, then the item): `Meta.leading` can hold a comment
|
||||
positioned after `item.span.start`, and a region opened there would emit the
|
||||
attribute both inside the slice and again as formatted output. Fence
|
||||
detection skips any leading comment that starts at or after its item's span.
|
||||
- **Stress-tested against the corpus rather than trusting the unit tests.**
|
||||
Injected an `off`/`on` pair at 1 868 random line positions across the 468
|
||||
corpus files that parse, and compared the result against the same runs with
|
||||
the fence text replaced by an ordinary comment of identical width:
|
||||
- **0 new verification failures.** 112 of the 1 868 plain-comment runs fail
|
||||
equivalence — a *pre-existing* bug class (a comment injected into a port
|
||||
list or an expression gets moved or dropped; the safety net catches it and
|
||||
the file is left untouched). The fenced runs fail on 94 of the same
|
||||
trials and on **no others**; 18 are avoided precisely because the region
|
||||
went verbatim.
|
||||
- **Byte-exactness at corpus scale.** Restricting the injection so both
|
||||
fences land at the same nesting level gives 294 honoured regions, of which
|
||||
287 are reproduced byte-for-byte. The other 7 are all the documented
|
||||
cross-scope case (the `on` landed in a different scope, so the `off` ran
|
||||
to the end of its own): each preserves a verbatim *prefix* that stops
|
||||
exactly at its scope's last item.
|
||||
- **Two pre-existing bugs found in passing, both left alone** (out of scope,
|
||||
reported to the lead): the comment-injection failures above, and a
|
||||
double-blank-line bug — two leading comments separated by a blank line come
|
||||
out separated by *two* blank lines, because `Fmt::leading` emits a
|
||||
`HardLine` after each comment and then a `BlankLine` before the next.
|
||||
Reproduced on the pre-change binary; not touched here because fixing it
|
||||
churns snapshots.
|
||||
- Did not touch `crates/vlog_parser`, `crates/vfmt`, `verify.rs`, or
|
||||
`tools/`. Did not run `git commit`/`git push`.
|
||||
|
||||
**Results:** `cargo test -p vlog_formatter` **53 passed** (was 42: +5 matcher
|
||||
unit tests in `fence.rs`, +6 in `tests/fences.rs`), plus **25 new
|
||||
`.cases` entries** inside `case_tables`. No existing test changed and no
|
||||
snapshot or `.cases` churn — the fence-aware separator logic is
|
||||
byte-identical to the old index-based one when no fence is present, which is
|
||||
what the untouched suite demonstrates. `cargo test --workspace` **194 passed,
|
||||
0 failed** (that number also carries the concurrent error-tolerant-parsing
|
||||
agent's new `vlog_parser` tests). `cargo clippy --workspace --all-targets`
|
||||
silent (0 warnings). `cargo fmt --all --check` clean. Corpus:
|
||||
`tools/corpus_check.sh corpus` (read-only) — 820 files, 2 ok-unchanged, 466
|
||||
would-reformat, 352 parse-error, **0 verification errors, 0 crashes**, TSV md5
|
||||
`3fab114f4f00626b254259e9dafe0ed7`, **byte-identical** to the `spans`
|
||||
baseline. No `.sv`/`.v` corpus file contains a fence comment (`grep -rl` over
|
||||
all 820: 0 hits; the only two `verilog_format` matches in the tree are a CI
|
||||
YAML comment and a Verible build script), so the feature is inert there, as
|
||||
expected. Corpus repos `git status --porcelain` clean apart from the
|
||||
pre-existing untracked `.vfmt-corpus-rev` stamps.
|
||||
|
||||
Files touched: `crates/vlog_formatter/src/fence.rs` (new),
|
||||
`crates/vlog_formatter/src/{lib,doc,printer,format}.rs`,
|
||||
`crates/vlog_formatter/tests/fences.rs` (new),
|
||||
`crates/vlog_formatter/tests/cases/fences.cases` (new), `README.md` (Style
|
||||
section), `TODO.md` (§2 checkbox), this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
Scope: `crates/vlog_formatter` only (a concurrent QA agent owns
|
||||
`vlog_parser`/error-recovery this round; untouched here). No commit/push.
|
||||
All work done via a scratch cargo project pointing at this crate by path
|
||||
(`/private/tmp/.../scratchpad/qa_probe`) plus a disposable `git worktree` at
|
||||
`HEAD` (901a78c, pre-fence) for baseline comparisons — both removed after
|
||||
use, working tree left exactly as found (`git status --short` before/after
|
||||
identical).
|
||||
|
||||
**Tool results.**
|
||||
- `cargo test -p vlog_formatter`: **53 passed, 0 failed** (8 lib unit tests
|
||||
— 5 in `fence.rs` + 3 pre-existing in `printer.rs` — 1+4+6+2+32 across
|
||||
`cases.rs`/`deep_nesting.rs`/`fences.rs`/`fixtures.rs`/`verification.rs`).
|
||||
Matches the claimed 42→53.
|
||||
- `cargo test --workspace`: **194 passed, 0 failed** (40+21 in `vfmt`, 53 in
|
||||
`vlog_formatter`, 49+19+12 in `vlog_parser` — the last three carry the
|
||||
concurrent error-recovery agent's work, not this feature's).
|
||||
- `cargo clippy -p vlog_formatter --all-targets`: 0 warnings.
|
||||
`cargo clippy --workspace --all-targets`: 0 warnings. Confirmed the
|
||||
earlier-flagged `fence.rs:58` nit is gone: it reads
|
||||
`regions.last().is_none_or(|prev| ...)`, not `.map_or(true, ...)`.
|
||||
- `cargo fmt --check` (workspace): clean, no output.
|
||||
- `verify.rs` untouched: `git diff --quiet -- crates/vlog_formatter/src/verify.rs`
|
||||
exits 0. `tests/verification.rs` likewise unchanged (`git diff --quiet`),
|
||||
and its 32 tests still pass unmodified.
|
||||
- `git status --short`: only `README.md`, `TODO.md`,
|
||||
`crates/vlog_formatter/src/{doc,format,lib,printer}.rs` modified in this
|
||||
feature's footprint, plus the four new files
|
||||
(`fence.rs`, `tests/fences.rs`, `tests/cases/fences.cases`,
|
||||
`docs/features/format-fences/README.md`) — matches the work log's "files
|
||||
touched" list exactly. `crates/vlog_parser/**` changes present are the
|
||||
concurrent feature's, not this one's.
|
||||
- `tools/corpus_check.sh corpus`: 820 files, **0 verification errors, 0
|
||||
crashes**, TSV md5 `3fab114f4f00626b254259e9dafe0ed7` — **matches** the
|
||||
claimed baseline exactly (byte-identical results file). `grep -rl` for
|
||||
`verilog_format|vfmt:` across all `.sv/.v/.svh/.vh` in `corpus/`: **0
|
||||
hits**, confirming the feature is inert on the corpus as claimed.
|
||||
|
||||
**Claim 1 (fence grammar) — PASS.** Direct `fence_of()` probes:
|
||||
`// vfmt: off ` (single trailing space) *is* a fence — correctly so, the
|
||||
grammar trims surrounding whitespace and only disqualifies non-whitespace
|
||||
trailing text; my first pass at this check used the wrong expectation and
|
||||
was self-corrected. `// VFMT: off` (case), `// vfmt: off` (inner double
|
||||
space), `// verilog_format:off` (no space after colon) are all correctly
|
||||
rejected — matches the documented grammar exactly, no drift between prose
|
||||
and code. Block comments and same-line trailing comments confirmed inert
|
||||
via both the `.cases` table and my own probes.
|
||||
|
||||
**Claim 2 (semantics) — PASS.** All items verified, including two not
|
||||
explicitly in the `.cases` table: (a) a region nested inside another
|
||||
region — outer `off`/`on` wrapping a module that has its own inner
|
||||
`off`/`on` pair — is correctly collapsed to one region (`fence::collect`'s
|
||||
dedup), the inner fence pair is inert text, output byte-exact,
|
||||
second-pass idempotent. (b) unmatched-`off` correctly stops at
|
||||
`endmodule`/`end` and never leaks into the next scope, confirmed at file,
|
||||
module and generate-block granularity.
|
||||
|
||||
**Claim 3 (splice mechanics) — PASS.** Adversarial idempotency probes (24
|
||||
targeted cases: fence at file start/end with and without trailing
|
||||
newline, zero items between off/on, off right after `module m;` + on
|
||||
right before `endmodule`, two adjacent regions, matched region whose last
|
||||
item has a same-line trailing comment, interior tabs/trailing spaces,
|
||||
multi-line macro + attribute inside a region, 1/2/3 blank lines in three
|
||||
different positions around the fences, generate-block-final region
|
||||
matched and unmatched, CRLF file variants including a fence sharing its
|
||||
line with a block comment, a crammed one-line port/connection list inside
|
||||
a region, and a 200-column line inside a region) — **all byte-exact and
|
||||
idempotent, zero failures.** Region-content protection confirmed: the
|
||||
200-col line and the crammed port list both survive verbatim, and
|
||||
formatting resumes at the correct indent immediately after (`assign z = a
|
||||
+ b;` at 2-space indent right after a verbatim block that was written at
|
||||
column 0). CRLF interior bytes (`\r\n`) survive inside `Doc::Verbatim`
|
||||
slices exactly; the formatter's own emitted lines around them use `\n` as
|
||||
usual — pre-existing, general behavior, not fence-specific, and internally
|
||||
consistent (idempotent).
|
||||
|
||||
Reviewed `printer.rs`'s `Doc::Verbatim` indent-stripping
|
||||
(`while out.ends_with(' ') { out.pop(); }`) for a tabs-vs-spaces gap: the
|
||||
printer's own indentation is generated exclusively via
|
||||
`" ".repeat(...)`-style space writes (confirmed by reading `print()`), so
|
||||
there is no path where the "indentation just written" contains a tab —
|
||||
the space-only strip is correct as written, not a latent bug.
|
||||
|
||||
**Claim 4 (matcher) — PASS**, see Claim 1; the `tests/fences.rs`
|
||||
`the_matcher_agrees_with_what_the_formatter_honours` test already pins the
|
||||
matcher-vs-formatter agreement in both directions and I independently
|
||||
reproduced every spelling in the task list against `fence_of` directly.
|
||||
|
||||
**Claim 5 (interaction with error-recovery arms) — PASS, and
|
||||
strengthened.** The README's Handshakes section reasons that
|
||||
`fence::collect` never sees `ItemKind::Error` in production because
|
||||
`format_source` only calls the strict `parse_source`. I went further and
|
||||
called `fence::collect` directly against a `parse_source_tolerant(...)`
|
||||
tree containing an `ItemKind::Error` node (adjacent to, and also
|
||||
overlapping the leading comments of, a fenced region) — no panic, and
|
||||
`ItemKind::Error` is correctly ignored by `scan_nested`'s catch-all arm in
|
||||
both configurations tried. This is dead code in today's product but is
|
||||
now empirically confirmed safe, not just reasoned about.
|
||||
|
||||
**Claim: 1868-injection stress (evidence review, not reproduced at that
|
||||
scale) — directionally confirmed.** I ran an independent ~200-trial
|
||||
random injection harness against the same `corpus/` (118 trials usable
|
||||
after skipping the 82 that don't parse, consistent with the corpus's
|
||||
~43% parse rate). Initial naive comparison (fence pair vs. a *single*
|
||||
plain padding comment) showed 1 "new" fence failure, but that comparison
|
||||
was unfair — the fence variant inserts two lines (off+on), the plain
|
||||
variant only one. Re-run with a fair **paired** control (plain padding
|
||||
comments at the *same two* line positions): **0 new verification failures
|
||||
attributable to fencing**, and the fence variant additionally *avoided* 2
|
||||
failures the plain-pair control hit (regions the fence sent verbatim that
|
||||
a plain comment injected at the same spot would have corrupted) — this
|
||||
directly corroborates the dev's own "0 new verification failures" /
|
||||
"18 avoided precisely because the region went verbatim" claim, on an
|
||||
independent sample. I did not attempt to reproduce the dev's exact
|
||||
1868/294/287/7 figures (no harness script was checked in to rerun
|
||||
verbatim); treat those as the dev's own measurement, independently
|
||||
corroborated in direction and magnitude but not bit-for-bit.
|
||||
|
||||
**Claim 7 (pre-existing bugs) — PASS, both reproduced on the pre-change
|
||||
binary.** Using a disposable `git worktree` at `HEAD` (901a78c, before any
|
||||
of this feature's changes):
|
||||
- **Double-blank between leading comments**: `module m;\n // first\n\n //
|
||||
second\n wire a;\nendmodule\n` reproduces the extra blank line
|
||||
(`// first` then *two* blank lines then `// second`) identically on the
|
||||
baseline binary. Confirmed pre-existing, not introduced.
|
||||
- **Comment in a list dropped → refused**: reproduced the exact corpus
|
||||
hit (`corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_mubi16_dec.sv`,
|
||||
padding comment inserted before line 16) on both the baseline worktree
|
||||
and the current tree — byte-identical error message
|
||||
(`token stream diverges at index 18: input has comment ... output has
|
||||
symbol "#"`) on both. Confirmed pre-existing. Note for context (not a
|
||||
correction of the dev's claim): this bug class is the same one already
|
||||
tracked as open "refusals" in `docs/features/corpus-bugs/README.md`
|
||||
("Comments inside a replication, inside a compactly-printed bracket
|
||||
expression, ... remain refusals" — this feature's finding is another
|
||||
instance of that same, already-known category, not a new one).
|
||||
|
||||
**Durability of the two open items — PASS with a minor, non-blocking
|
||||
suggestion.** Both are recorded in this README's Work log, which is a
|
||||
required, checked-in section per `CLAUDE.md`'s document-based-development
|
||||
rules, so they are not silently lost by the letter of that requirement.
|
||||
They are *not* mirrored as `TODO.md` §1 entries the way other QA-found
|
||||
bugs in this repo are (e.g. the `@(* )` lexer bug, tagged "(bug-fix QA
|
||||
find)"). Since `TODO.md` is described as the project's "curated backlog"
|
||||
and is where a future agent would look first, I'd suggest the lead add
|
||||
one line each there for discoverability — informational only, not
|
||||
blocking.
|
||||
|
||||
**Claude.md compliance — PASS.** No `unwrap()`/`expect()`/`panic!` outside
|
||||
`#[cfg(test)]` in `fence.rs` or the `format.rs` diff (checked by grep on
|
||||
the diff and the file). All new `pub` items in `fence.rs` carry one-line
|
||||
doc comments. No `unsafe`. `README.md`/`TODO.md` checkbox changes are
|
||||
accurate to what shipped (statement-level and same-line fences correctly
|
||||
left unchecked with a documented reason).
|
||||
|
||||
**Overall: no BLOCKING findings.** No byte change inside any fenced
|
||||
region across two passes in any probe, no behavior change with zero
|
||||
fences present beyond what the existing untouched test suite already
|
||||
covers (byte-for-byte zero churn). The one apparent anomaly during
|
||||
testing (the "1 new fence failure" in the naive injection comparison) was
|
||||
a flaw in my own harness's methodology, not the feature — resolved with a
|
||||
fair control, see above.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with
|
||||
error-recovery (entangled in `format.rs` via the `Error` match arms).**
|
||||
|
||||
The user-facing rule this feature had to get right — *bytes inside a
|
||||
fence are sacred* — survived 24 adversarial join probes and ~2000
|
||||
combined corpus injections (dev's 1868 + QA's paired-control 118) with
|
||||
zero region byte changes and zero new verification failures. Points
|
||||
reviewed and accepted:
|
||||
|
||||
1. **Exact-match fence grammar** (trailing text disqualifies, no-space
|
||||
`vfmt:off` disqualifies): strict grammars over lenient ones is the
|
||||
config-discovery lesson applied again — a fence that half-matches
|
||||
silently doing nothing would be the worst outcome, and the current
|
||||
rule makes it at least predictable. Verible-compatible spelling plus
|
||||
the short alias is the right pair.
|
||||
2. **Item-level scope, statement level deferred** — the honest scope
|
||||
line, documented and tested (an off-fence inside an item body is
|
||||
inert). Same-line trailing fences are inert for a structural reason
|
||||
(Meta.trailing has no span) — the Handshake filed on vlog_parser is
|
||||
the right escalation instead of a hack. That handshake lands
|
||||
naturally with the comments round.
|
||||
3. **Doc::Verbatim as a first-class hard-line element** rather than
|
||||
string surgery in the printer: right layer, and "with no fences the
|
||||
output is byte-identical" held (corpus md5 exact).
|
||||
4. Two construction-time bugs (dropped trailing comment on unmatched
|
||||
off, stray separator from swallowed items) caught and fixed by the
|
||||
dev's own tests — the invariant-test-first habit is now visibly the
|
||||
house style.
|
||||
|
||||
QA's suggestion adopted at review: the two pre-existing bugs this
|
||||
feature surfaced (comment-in-list refusal, quantified at 112/1868
|
||||
trials; the double-blank leading-comment nit) are now TODO.md items
|
||||
queued for a dedicated comments round — they were too big to ride
|
||||
along here, and the refusal path means neither can corrupt.
|
||||
Reference in new issue
Block a user