Add directives-in-instances and shared-fence-filter (round 15)

directives-in-instances: `ifdef/`else/`elsif/`endif/`define/`include
now parse between elements of instantiation #() override lists and
connection lists (param_directives on Instantiation, conn_directives
on Instance -- an all-in-arm list is Connections::Ordered(vec![]),
so the vector cannot live inside it; commas stored on Connection and
OrderedConn, never derived). All six named corpus targets format and
converge; no corpus file is blocked on a compiler directive any more
(backtick parse errors 6 -> 0); corpus 476/820 formattable (58.0%),
clean-file external resolution 94.0%. One bug found en route and
fixed: directive_entry overwrote before_sep, dropping a comment
(net-caught; pinned by directives_in_lists.cases:780, sabotage-
verified).

shared-fence-filter: one definition of "which bytes are fenced" --
protected_regions/is_protected in vlog_formatter::fence (the CLI's
scan MOVED in, not copied; grep finds one owner). The CLI filter is
byte-identical (isolated-diff worktrees, 8 shapes, 48 CLI tests
diff-empty); the server's quickfix and fixAll paths now drop fixes
touching protected bytes -- off means hands-off in the editor too.
Sabotage: removing the scan union fails six tests across three
crates. Lead fix: the good-tree test now genuinely pins the collect
path (QA found it only exercised the scan).

(The stale corpus-check-results.tsv two QAs flagged turned out to be
an untracked ignored working file, not a committed one -- deleted
from disk after this commit; it regenerates on every corpus run.)

589 workspace tests. Dev: 2 Opus agents; QA: 2 Sonnet agents;
reviews in docs/features/{directives-in-instances,
shared-fence-filter}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 12:09:51 -07:00
1 parent 6e6aacb392
commit 692496fb89
16 files changed
+2285 -146

No files matched your search

+16 -10
View File
@@ -251,13 +251,17 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
multi-line argument list keeps its own line structure, re-indented); a
trailing `;` is reproduced only if the source wrote one
- `` `ifdef``/`` `ifndef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
`` `include`` and macro invocations written **between the elements** of a
module header's port list, its parameter port list or an enum member list.
The condition is not evaluated: both arms' elements are entries of the one
list, exactly as at item position. The directive must be the last thing on
its line, and the comma placement the source wrote is reproduced — including
a comma written *inside* an `` `ifdef`` arm. See
`docs/features/directives-in-lists/README.md`
`` `undef``, `` `include`` and macro invocations written **between the
elements** of a module header's port list, its parameter port list, an enum
member list, an instantiation's `#( ... )` parameter overrides or an
instance's `( ... )` connection list. The condition is not evaluated: both
arms' elements are entries of the one list, exactly as at item position. The
directive must be the last thing on its line, and the comma placement the
source wrote is reproduced — including a comma written *inside* an
`` `ifdef`` arm. A list may be nothing *but* a directive
(``sub #(`include "config.vh") u (...)``). See
`docs/features/directives-in-lists/README.md` and
`docs/features/directives-in-instances/README.md`
Not yet supported (parse errors). Roadmap ordered by measured impact on
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
@@ -280,9 +284,11 @@ corpus baseline this ordering comes from:
format — its next blocker is `restrict property`, item 7 below). The
real payoff was the workspace index: `picorv32`, `picorv32_axi` and
`picorv32_wb` now index (521 → 530 modules), taking cross-file external
resolution from 87.0% to 93.6% on cleanly-parsed files. Still missing: the
same construct inside an *instantiation's* parameter-override or connection
list (6 files)
resolution from 87.0% to 93.6% on cleanly-parsed files. The instantiation
half followed in `docs/features/directives-in-instances/README.md`: the
same construct inside an *instantiation's* `#( ... )` overrides or an
instance's `( ... )` connections, which unblocked the remaining 6 files.
**No corpus file is blocked on a compiler directive any more**
7. DPI, concurrent assertions (`assert property`), non-simple casts
8. Interfaces/modports, `case ... inside`, streaming operators, specify
blocks, `let`/`checker`, sequences — rare in the corpus RTL
+10 -2
View File
@@ -340,8 +340,16 @@ later:
`picorv32_axi` and `picorv32_wb` index at all — 521 → 530 modules,
8044 → 9174 exported members, external candidates answered 87.0 % → 93.6 %
on cleanly-parsed files (unresolved-external rate 2.6 % → 1.3 % of all
references). Still unindexed for the same reason: modules whose
*instantiation* lists hold a directive.
references). The instantiation half followed in
`docs/features/directives-in-instances/README.md` (directives in an
instantiation's `#( ... )` overrides and an instance's `( ... )`
connections); after it **no corpus file is blocked on a compiler directive
at all**, so nothing is left unindexed for this reason. The *index* counts
above did not move (530 modules, 9174 exported members, 502 defines — the
six files it unblocked have headers that already parsed, so their modules
were already indexed); what moved is 6 more files that now format, and with
them external candidates answered 93.6 % → **94.0 %** on cleanly-parsed
files (unresolved-external rate 1.3 % → **1.2 %**).
- [x] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over
stdio via `tower-lsp` or `lsp-server`. Order of capabilities:
1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`),
+35 -72
View File
@@ -125,15 +125,12 @@ fn run_rules(
/// rewrote those same bytes would make the fence a promise only half of vfmt
/// keeps. The violation is still **reported** — a finding is information, and
/// silencing it is what waivers are for — it just loses its automatic fix.
///
/// Which bytes count as fenced is [`fence::protected_regions`]' answer, not
/// one of this file's own: the language server asks the same question about
/// the same buffers, and two answers to it would drift.
fn fixable_outside_fences(text: &str, violations: &[Violation]) -> Vec<Violation> {
// Two sources, unioned. `fence::collect` is the formatter's own answer and
// the authority wherever the tree is good; the line scan is a backstop for
// the files only the linter sees, where error recovery can swallow the
// structure a fence hangs on and `collect` then reports no region at all.
// Erring toward more protection only ever declines a fix.
let (parsed, _) = vlog_parser::parse_source_tolerant(text);
let mut regions = fence::collect(text, &parsed);
regions.extend(scanned_fence_regions(text));
let regions = fence::protected_regions(text);
if regions.is_empty() {
return violations.to_vec();
}
@@ -144,56 +141,11 @@ fn fixable_outside_fences(text: &str, violations: &[Violation]) -> Vec<Violation
.collect()
}
/// Fenced regions found by reading lines, without a parse.
///
/// A fence is by definition a line comment alone on its line whose text
/// matches exactly, so [`fence::fence_of`] — the formatter's own grammar — is
/// all this needs. Pairing is deliberately cruder than the formatter's: an
/// `off` runs to the next `on` or to the end of the file, with no notion of
/// the enclosing scope. It can therefore protect a little more than the
/// formatter would emit verbatim (and would be fooled by a fence spelled
/// inside a block comment), which is the harmless direction: the only
/// consequence is a fix vfmt declines to apply.
fn scanned_fence_regions(text: &str) -> Vec<Region> {
let index = LineIndex::new(text);
let mut regions = Vec::new();
let mut open: Option<usize> = None;
for line in 1..=index.line_count() {
let Some(range) = index.line_range(line) else { continue };
let Some(spelling) = text.get(range.as_range()).and_then(|l| fence::fence_of(l.trim()))
else {
continue;
};
match (spelling, open) {
(fence::Fence::Off, None) => open = Some(range.start as usize),
(fence::Fence::On, Some(start)) => {
regions.push(Region { fence: start, start, end: range.end as usize });
open = None;
}
// A second `off`, or an `on` with nothing open, is just text.
_ => {}
}
}
if let Some(start) = open {
regions.push(Region { fence: start, start, end: text.len() });
}
regions
}
/// True when any edit of `fix` overlaps a fenced region.
///
/// The protected range is the whole `start..end` the formatter would emit
/// verbatim, indentation of the fence line included — not just what
/// `region_at` calls "inside" — because that is exactly the set of bytes the
/// formatter promises to leave alone.
fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
fix.edits.iter().any(|(range, _)| {
let start = range.start as usize;
// An insertion has an empty range; treat it as covering the byte it
// would land in front of, so nothing can be spliced into a region.
let end = (range.end as usize).max(start + 1);
regions.iter().any(|region| start < region.end && region.start < end)
})
fix.edits
.iter()
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
}
/// Applies fixes until the file stops changing. Returns what is left over,
@@ -436,30 +388,41 @@ mod tests {
assert_eq!(fixable_outside_fences(text, &violations).len(), 1);
}
#[test]
fn the_line_scan_backstops_a_file_that_does_not_parse() {
// Error recovery can swallow the structure `fence::collect` hangs a
// region on; the scan still finds it.
let text = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
let regions = scanned_fence_regions(text);
assert_eq!(regions.len(), 1, "{regions:?}");
let tab = text.find("\ta = 1").unwrap_or(0);
assert!(regions[0].start <= tab && tab < regions[0].end);
/// One `no-tabs`-shaped violation over the tab at `at`.
fn tab_violation(at: usize) -> Vec<LintViolation> {
let at = at as u32;
vec![LintViolation::new("no-tabs", "tab", TextRange::new(at, at + 1))
.with_fix(edit_at(at, at + 1))]
}
#[test]
fn an_unclosed_fence_scan_runs_to_the_end_of_the_file() {
fn the_line_scan_backstops_a_file_that_does_not_parse() {
// Error recovery can swallow the structure `fence::collect` hangs a
// region on; the union's scan half still finds it. Owned by
// `fence::protected_regions` now — this is the CLI end of it.
let text = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
let tab = text.find("\ta = 1").unwrap_or(0);
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
}
#[test]
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
let text = "module m;\n// vfmt: off\n\ta = 1;\nendmodule\n";
let regions = scanned_fence_regions(text);
assert_eq!(regions.len(), 1);
assert_eq!(regions[0].end, text.len());
let tab = text.find("\ta = 1").unwrap_or(0);
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
}
#[test]
fn an_ordinary_comment_is_not_a_fence() {
assert!(scanned_fence_regions("// vfmt: off-by-one\n\ta = 1;\n").is_empty());
assert!(scanned_fence_regions("// just a note\n\ta = 1;\n").is_empty());
assert!(scanned_fence_regions("// vfmt: on\n\ta = 1;\n").is_empty(), "a stray `on`");
for text in [
"module m;\n// vfmt: off-by-one\n\ta = 1;\nendmodule\n",
"module m;\n// just a note\n\ta = 1;\nendmodule\n",
// A stray `on` opens nothing.
"module m;\n// vfmt: on\n\ta = 1;\nendmodule\n",
] {
let tab = text.find("\ta = 1").unwrap_or(0);
assert_eq!(fixable_outside_fences(text, &tab_violation(tab)).len(), 1, "{text:?}");
}
}
#[test]
+48
View File
@@ -300,6 +300,54 @@ mod tests {
assert!(actions_of(&ws).is_empty(), "converged");
}
/// A tab inside a fence and a tab outside one, both `no-tabs` findings.
const FENCED: &str = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
#[test]
fn a_violation_inside_a_fence_gets_a_diagnostic_but_no_quick_fix() {
let ws = workspace(FENCED);
let doc = ws.document(&uri()).expect("open");
// The finding is published — `off` silences the fix, not the report.
let fenced_line = 2;
let published = crate::lint::diagnostics(doc);
assert!(
published.iter().any(|d| d.range.start.line == fenced_line),
"the fenced tab is still reported: {published:#?}"
);
// ...but the cursor on it offers no lightbulb.
let at = Range {
start: Position { line: fenced_line, character: 0 },
end: Position { line: fenced_line, character: 0 },
};
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
// The unfenced tab one line further down still has one.
let at = Range {
start: Position { line: 4, character: 0 },
end: Position { line: 4, character: 0 },
};
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
}
#[test]
fn fix_all_edits_the_unfenced_violations_only() {
let ws = workspace(FENCED);
let actions = actions_of(&ws);
let all = actions
.iter()
.find(|a| a.kind == Some(CodeActionKind::new(FIX_ALL)))
.expect("a fixAll action");
let output = applied(FENCED, all);
assert_eq!(
output, "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n wire b;\nendmodule\n",
"the fenced line is byte-identical, the free one is fixed"
);
// And the fenced bytes really are the input's own, tab included.
let fenced = FENCED.find("\twire a;").expect("fenced line");
assert!(output.contains("\twire a;"), "{output:?}");
assert_eq!(&output[..fenced], &FENCED[..fenced]);
}
#[test]
fn a_clean_buffer_offers_nothing() {
let text = "module m;\n wire a;\nendmodule\n";
+65 -2
View File
@@ -7,6 +7,7 @@
//! `docs/features/server-lint/README.md`.
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{default_rules, lint, run, LintContext, Violation};
use crate::convert::Positions;
@@ -24,14 +25,38 @@ pub fn violations(doc: &Document) -> Vec<Violation> {
run(&doc.text, doc.path.clone(), &default_rules())
}
/// The same findings, with their fixes built for `tab_width`.
/// The findings a code action may offer a fix for, with their fixes built for
/// `tab_width`.
///
/// The code-action path passes the indent width of the `vfmt.toml` governing
/// the buffer, so a quick fix that replaces a tab writes exactly what `vfmt`
/// would have written there.
///
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
/// region is dropped here, so the editor keeps the same promise `vfmt check
/// --fix` does: **reported, never auto-fixed**. The diagnostic still reaches
/// the user — [`violations`] is the publishing path and is not filtered — it
/// just has no lightbulb. Which bytes count as fenced is
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
/// `docs/features/shared-fence-filter/README.md`.
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
let ctx = LintContext::new(&doc.text, doc.path.clone()).with_tab_width(tab_width);
lint(&ctx, &default_rules())
let found = lint(&ctx, &default_rules());
// One tolerant parse per code-action request, on top of the one
// `LintContext` just did. The diagnostics path — the per-keystroke one —
// pays neither, because it never reads a fix.
let regions = fence::protected_regions(&doc.text);
found.into_iter().filter(|violation| !fix_touches_fence(violation, &regions)).collect()
}
/// True when a violation carries a fix any edit of which lands in a fenced
/// region. A fix is all-or-nothing, so one edit inside blocks the whole fix.
fn fix_touches_fence(violation: &Violation, regions: &[Region]) -> bool {
violation.fix.as_ref().is_some_and(|fix| {
fix.edits
.iter()
.any(|(span, _)| fence::is_protected(regions, span.start as usize, span.end as usize))
})
}
/// One LSP diagnostic per lint violation.
@@ -130,6 +155,44 @@ mod tests {
assert!(diags.iter().any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))));
}
#[test]
fn a_violation_inside_a_fence_is_reported_but_not_fixable() {
// `off` means hands-off for the editor too: the warning is published,
// the fix is withheld.
let text = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
let offered = fixable(doc, 2);
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
let free = text.find("\twire b").expect("the unfenced tab") as u32;
assert_eq!(offered[0].span.start, free);
}
#[test]
fn a_fence_holds_even_when_the_file_does_not_parse() {
// Error recovery can swallow the item structure `fence::collect` hangs
// a region on — the buffers the server sees mid-keystroke are exactly
// that population, and the shared filter's scan half covers them.
let text = "module m;\n@@@ junk;\n// vfmt: off\n\twire a;\n// vfmt: on\nendmodule\n";
let (ws, uri) = doc_of(text);
let doc = ws.document(&uri).expect("open");
assert!(
diagnostics(doc)
.iter()
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
"still reported"
);
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
}
#[test]
fn an_unfenced_file_offers_every_fix() {
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
}
#[test]
fn a_fix_expands_a_tab_to_the_width_it_is_given() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
+95
View File
@@ -250,6 +250,101 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A fenced tab and an unfenced one, in a file whose name matches its module.
/// One pass converges here (no two fixes want the same bytes), which is what
/// makes the server's single-pass `fixAll` comparable to the CLI's loop.
const FENCED: &str = "module fenced;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
/// The `vfmt` CLI binary, built beside this crate's own.
///
/// Cargo names no env var for another package's binary, so it is found by
/// path. `cargo test --workspace` — the gate this test belongs to — always
/// builds it; `cargo test -p vfmt_server` alone may not, and the test says so
/// and passes rather than failing for a reason that is not about the server.
fn vfmt_binary() -> Option<PathBuf> {
let path = Path::new(env!("CARGO_BIN_EXE_vfmt-server")).with_file_name("vfmt");
path.is_file().then_some(path)
}
#[test]
fn fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence() {
let Some(vfmt) = vfmt_binary() else {
eprintln!("skipped: the `vfmt` binary is not built next to `vfmt-server`");
return;
};
let dir = temp_dir("fence");
let file = dir.join("fenced.sv");
std::fs::write(&file, FENCED).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(FENCED).expect("json")
)),
// Fix-on-save, then a cursor sitting on the fenced tab.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":5,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.vfmt"]}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":2,"character":0}},"end":{{"line":2,"character":1}}}},"context":{{"diagnostics":[]}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
// Both tabs are still reported: `off` withholds the fix, not the finding.
let published = messages
.iter()
.find(|m| m["method"] == "textDocument/publishDiagnostics")
.expect("diagnostics");
let diagnostics = published["params"]["diagnostics"].as_array().expect("an array");
assert_eq!(diagnostics.len(), 2, "one per tab, fenced included: {diagnostics:#?}");
// No quick fix on the fenced line.
let at_fence = messages.iter().find(|m| m["id"] == 3).expect("code action response");
let at_fence = at_fence["result"].as_array().expect("an array");
assert!(
!at_fence.iter().any(|a| a["kind"] == "quickfix"),
"no lightbulb inside a fence: {at_fence:#?}"
);
// And `fixAll` writes exactly what `vfmt check --fix` writes.
let fix_all = messages.iter().find(|m| m["id"] == 2).expect("fixAll response");
let fix_all = fix_all["result"].as_array().expect("an array");
assert_eq!(fix_all.len(), 1, "only what was asked for: {fix_all:#?}");
let edits = fix_all[0]["edit"]["changes"][uri.as_str()].as_array().expect("edits");
assert_eq!(edits.len(), 1, "one whole-document edit");
let fixed = edits[0]["newText"].as_str().expect("newText").to_string();
let cli = dir.join("cli.sv");
std::fs::write(&cli, FENCED).expect("write");
let status = Command::new(&vfmt)
.arg("check")
.arg("--fix")
.arg(&cli)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("the vfmt binary runs");
// Two findings remain (the fenced tab is reported and unfixed), so the
// CLI exits 1 — the documented "reported, never auto-fixed" contract.
assert_eq!(status.code(), Some(1), "violations remain, and that is correct");
let cli_output = std::fs::read_to_string(&cli).expect("read back");
assert_eq!(fixed, cli_output, "the two front ends agree byte for byte");
assert!(cli_output.contains("\twire a;"), "the fenced tab survived: {cli_output:?}");
assert!(cli_output.contains(" wire b;"), "the free tab was fixed: {cli_output:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A buffer that is broken *and* still has a resolvable reference: error
/// recovery is what makes both true at once, and the LSP depends on it.
const SOURCE: &str = "module top;\n wire a;\n assign a = 1;\n wire ;\nendmodule\n";
+148
View File
@@ -4,9 +4,16 @@
//! 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`.
//!
//! [`protected_regions`] and [`is_protected`] are the same answer for the
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
//! `vfmt check --fix` and the language server's quick fixes. They live here so
//! there is one definition of "what is fenced": see
//! `docs/features/shared-fence-filter/README.md`.
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
/// Which side of a fence a comment spells.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -69,6 +76,76 @@ pub fn region_at(regions: &[Region], pos: usize) -> Option<&Region> {
regions.get(i).filter(|r| r.fence <= pos)
}
/// Every byte range in `src` that no tool may edit automatically.
///
/// `off` means hands-off across all of vfmt, not just the layout engine, so
/// the CLI's `--fix` and the server's quick fixes both ask this question here
/// rather than each answering it themselves. The answer is deliberately
/// wider than [`collect`]'s: it is the union of
///
/// 1. `collect` over a tolerant parse — the formatter's own item-scoped
/// answer, authoritative wherever the tree is good, and
/// 2. a line scan, the backstop for the broken files only the linter and the
/// server see, where error recovery can swallow the item structure a
/// region hangs on and `collect` then reports no region at all.
///
/// The regions may overlap and are not sorted; [`is_protected`] is the only
/// thing that reads them, and protecting a little more than the formatter
/// emits verbatim only ever declines an edit, which is the harmless
/// direction.
pub fn protected_regions(src: &str) -> Vec<Region> {
let (parsed, _) = vlog_parser::parse_source_tolerant(src);
let mut regions = collect(src, &parsed);
regions.extend(scanned_regions(src));
regions
}
/// Whether the byte range `start..end` overlaps any protected region.
///
/// An empty range is an insertion; it covers the byte it would land in front
/// of, so nothing can be spliced into a region. The protected extent is the
/// whole [`Region::start`]`..`[`Region::end`] the formatter emits verbatim,
/// the fence line's own indentation included — not just what [`region_at`]
/// calls "inside".
pub fn is_protected(regions: &[Region], start: usize, end: usize) -> bool {
let end = end.max(start + 1);
regions.iter().any(|region| start < region.end && region.start < end)
}
/// Fenced regions found by reading lines, without a parse.
///
/// A fence is by definition a line comment alone on its line whose text
/// matches exactly, so [`fence_of`] — the formatter's own grammar — is all
/// this needs. Pairing is cruder than [`collect`]'s: an `off` runs to the next
/// `on` or to the end of the file, with no notion of the enclosing scope. It
/// can therefore protect a little more than the formatter emits verbatim, and
/// would be fooled by a fence spelled inside a block comment; both err toward
/// declining an edit.
fn scanned_regions(src: &str) -> Vec<Region> {
let index = LineIndex::new(src);
let mut regions = Vec::new();
let mut open: Option<usize> = None;
for line in 1..=index.line_count() {
let Some(range) = index.line_range(line) else { continue };
let Some(spelling) = src.get(range.as_range()).and_then(|l| fence_of(l.trim())) else {
continue;
};
match (spelling, open) {
(Fence::Off, None) => open = Some(range.start as usize),
(Fence::On, Some(start)) => {
regions.push(Region { fence: start, start, end: range.end as usize });
open = None;
}
// A second `off`, or an `on` with nothing open, is just text.
_ => {}
}
}
if let Some(start) = open {
regions.push(Region { fence: start, start, end: src.len() });
}
regions
}
/// Scan one item-list scope, then its nested scopes.
///
/// The scope is a flat stream of units — each item's leading comments, then
@@ -276,4 +353,75 @@ mod tests {
let end = src.find(" endmodule").expect("kw");
assert_eq!(with_trailing_comments(src, end), end);
}
/// A region covering bytes 10..20, as `collect` would report one.
fn ten_to_twenty() -> Vec<Region> {
vec![Region { fence: 10, start: 10, end: 20 }]
}
#[test]
fn protection_is_decided_exactly_at_the_region_boundaries() {
let regions = ten_to_twenty();
// First byte inside, last byte inside, and the whole span.
assert!(is_protected(&regions, 10, 11), "first byte inside");
assert!(is_protected(&regions, 19, 20), "last byte inside");
assert!(is_protected(&regions, 10, 20), "the whole region");
// Adjacent on both ends, touching nothing inside.
assert!(!is_protected(&regions, 9, 10), "ends where the region starts");
assert!(!is_protected(&regions, 20, 21), "starts where the region ends");
// Straddling either edge is still a hit.
assert!(is_protected(&regions, 9, 11), "straddles the start");
assert!(is_protected(&regions, 19, 21), "straddles the end");
// An insertion (empty range) inside must not be spliced in either,
// while one at the far edge is outside.
assert!(is_protected(&regions, 15, 15), "insertion inside");
assert!(is_protected(&regions, 10, 10), "insertion at the first byte");
assert!(!is_protected(&regions, 20, 20), "insertion just past the end");
// Nothing is protected without a region.
assert!(!is_protected(&[], 10, 11));
}
#[test]
fn a_fence_in_a_good_tree_protects_its_whole_region() {
// The fenced content must be a valid module item, or this test only
// exercises the scan half it claims not to test (QA find): `\ta = 1;`
// bare at item position does not parse, and `collect` then hangs no
// region on the tree. `wire` declarations parse cleanly.
let src = "module m;\n// vfmt: off\n\twire a;\n// vfmt: on\n\twire b;\nendmodule\n";
let (parsed, diagnostics) = vlog_parser::parse_source_tolerant(src);
assert!(diagnostics.is_empty(), "the tree must be clean for this test to mean anything");
assert!(!collect(src, &parsed).is_empty(), "the TREE path must find the region");
let regions = protected_regions(src);
let fenced = src.find("\twire a").expect("fenced tab");
let free = src.find("\twire b").expect("free tab");
assert!(is_protected(&regions, fenced, fenced + 1), "{regions:?}");
assert!(!is_protected(&regions, free, free + 1), "{regions:?}");
}
#[test]
fn the_line_scan_backstops_a_file_that_does_not_parse() {
// Error recovery can swallow the structure `collect` hangs a region
// on; the scan still finds it.
let src = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
let (parsed, _) = vlog_parser::parse_source_tolerant(src);
assert!(collect(src, &parsed).is_empty(), "the premise: no tree region here");
let tab = src.find("\ta = 1").expect("tab");
assert!(is_protected(&protected_regions(src), tab, tab + 1));
}
#[test]
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
let src = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\nendmodule\n";
let regions = scanned_regions(src);
assert_eq!(regions.len(), 1);
assert_eq!(regions[0].end, src.len());
}
#[test]
fn an_ordinary_comment_protects_nothing() {
assert!(scanned_regions("// vfmt: off-by-one\n\ta = 1;\n").is_empty());
assert!(scanned_regions("// just a note\n\ta = 1;\n").is_empty());
assert!(scanned_regions("// vfmt: on\n\ta = 1;\n").is_empty(), "a stray `on`");
assert!(protected_regions("module m;\n\ta = 1;\nendmodule\n").is_empty());
}
}
+38 -27
View File
@@ -427,6 +427,8 @@ impl<'a> Fmt<'a> {
let has_before_sep = !item.before_sep.is_empty();
// A directive swallows the rest of its line, so its comma — and
// any comment written before that comma — must start a new one.
// (A comment itself may share the line: the lexer stops the
// directive's capture before a `//` or `/*`.)
let ends_line = self.inline_comments(&item.before_sep, &mut inner) || item.directive;
if item.comma.unwrap_or(i < last) {
if ends_line {
@@ -491,12 +493,16 @@ impl<'a> Fmt<'a> {
///
/// Its trailing comment goes in `before_sep` rather than `trailing`
/// because that is where the source put it — between the directive and
/// the comma that may follow it.
/// the comma that may follow it. `Parser::take_before_sep` already moves a
/// trailing comment into `before_sep` in source order, so at most one of
/// the two is ever populated and appending keeps the source's order.
fn directive_entry(&self, d: &ListDirective) -> ListItem {
let mut before_sep = d.meta.before_sep.clone();
before_sep.extend(d.meta.trailing.clone());
ListItem {
leading: d.meta.leading.clone(),
doc: self.raw_text(&d.raw),
before_sep: d.meta.trailing.clone().into_iter().collect(),
before_sep,
trailing: None,
comma: Some(d.comma),
directive: true,
@@ -1151,10 +1157,14 @@ impl<'a> Fmt<'a> {
// An empty `#()` was written by hand and is reprinted as `#()`; a
// missing one stays missing.
if let Some(params) = &inst.params {
let items: Vec<ListItem> =
params.iter().map(|c| ListItem::from_meta(&c.meta, self.connection(c))).collect();
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited("(", items, ")", false));
docs.push(self.delimited("(", items, ")", broken));
on_fresh_line = false;
}
if let [only] = &inst.instances[..] {
@@ -1211,31 +1221,32 @@ impl<'a> Fmt<'a> {
if !self.bracket_comments(&instance.conn_comments, &mut docs, false) {
docs.push(text(" "));
}
docs.push(self.connections(&instance.conns));
docs.push(self.connections(&instance.conns, &instance.conn_directives));
concat(docs)
}
fn connections(&self, conns: &Connections) -> Doc {
match conns {
Connections::Named(list) => {
let items: Vec<ListItem> =
list.iter().map(|c| ListItem::from_meta(&c.meta, self.connection(c))).collect();
self.delimited("(", items, ")", false)
}
Connections::Ordered(list) => {
let items: Vec<ListItem> = list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d)
})
.collect();
self.delimited("(", items, ")", false)
}
}
/// A connection list, with the `` `ifdef``-style directives written between
/// its entries merged back into source order. A list holding one is laid
/// out broken: a directive runs to end of line, so nothing may share it.
fn connections(&self, conns: &Connections, directives: &[ListDirective]) -> Doc {
let items: Vec<ListItem> = match conns {
Connections::Named(list) => list
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.collect(),
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
.collect(),
};
let items = self.list_entries(items, directives);
self.delimited("(", items, ")", !directives.is_empty())
}
fn connection(&self, c: &Connection) -> Doc {
@@ -364,3 +364,491 @@ module m #(
input b
);
endmodule
====
# `ifdef around the first connection of an instantiation
module m;
sub u (
`ifdef X
.a(x),
`endif
.b(y)
);
endmodule
----
module m;
sub u (
`ifdef X
.a(x),
`endif
.b(y)
);
endmodule
====
# `ifdef around a connection in the middle of the list
module m;
sub u (
.a(x),
`ifdef X
.b(y),
`endif
.c(z)
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
.b(y),
`endif
.c(z)
);
endmodule
====
# `ifdef around the trailing connections: the comma before it stays put
module m;
sub u (
.a(x),
`ifdef X
.b(y),
.c(z)
`endif
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
.b(y),
.c(z)
`endif
);
endmodule
====
# `ifdef in a parameter override list
module m;
sub #(
`ifdef X
.P(1),
`endif
.Q(2)
) u (.a(x));
endmodule
----
module m;
sub #(
`ifdef X
.P(1),
`endif
.Q(2)
) u (.a(x));
endmodule
====
# `else arm in a connection list: neither arm writes a trailing comma
module m;
sub u (
`ifdef X
.a(x)
`else
.a(y)
`endif
);
endmodule
----
module m;
sub u (
`ifdef X
.a(x)
`else
.a(y)
`endif
);
endmodule
====
# `elsif chain between connections
module m;
sub u (
.a(x),
`ifdef X
.b(1),
`elsif Y
.b(2),
`else
.b(3),
`endif
.c(z)
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
.b(1),
`elsif Y
.b(2),
`else
.b(3),
`endif
.c(z)
);
endmodule
====
# nested `ifdef in a parameter override list (picorv32/testbench.v)
module m;
sub #(
`ifndef SYNTH_TEST
`ifdef SP_TEST
.ENABLE_REGS_DUALPORT(0),
`endif
.ENABLE_MUL(1)
`endif
) u (.a(x));
endmodule
----
module m;
sub #(
`ifndef SYNTH_TEST
`ifdef SP_TEST
.ENABLE_REGS_DUALPORT(0),
`endif
.ENABLE_MUL(1)
`endif
) u (.a(x));
endmodule
====
# the comma written after the directive, not before it
module m;
sub u (
.a(x)
`ifdef X
,
.b(y)
`endif
);
endmodule
----
module m;
sub u (
.a(x)
`ifdef X
,
.b(y)
`endif
);
endmodule
====
# a connection list that is entirely one `ifdef arm
module m;
sub u (
`ifdef X
.a(x),
.b(y)
`endif
);
endmodule
----
module m;
sub u (
`ifdef X
.a(x),
.b(y)
`endif
);
endmodule
====
# a parameter override list that is nothing but an `include (torture/testbench.v)
module m;
sub #(
`include "config.vh"
) u (.a(x));
endmodule
----
module m;
sub #(
`include "config.vh"
) u (.a(x));
endmodule
====
# `.*` alongside a directive
module m;
sub u (
.a(x),
`ifdef X
.b(y),
`endif
.*
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
.b(y),
`endif
.*
);
endmodule
====
# `define, a macro invocation and `undef between connections (spec_instance.sv)
module m;
sub u (
.a(x),
`define X(n) .n(pre_n),
`X_EACH
`undef X
.b(y)
);
endmodule
----
module m;
sub u (
.a(x),
`define X(n) .n(pre_n),
`X_EACH
`undef X
.b(y)
);
endmodule
====
# a directive standing after the last connection
module m;
sub u (
.a(x),
.b(y)
`ifdef X
`endif
);
endmodule
----
module m;
sub u (
.a(x),
.b(y)
`ifdef X
`endif
);
endmodule
====
# a connection list holding only directives and no connection at all
module m;
sub u (
`ifdef X
`endif
);
endmodule
----
module m;
sub u (
`ifdef X
`endif
);
endmodule
====
# `ifdef between positional connections
module m;
sub u (
x,
`ifdef X
y,
`endif
z
);
endmodule
----
module m;
sub u (
x,
`ifdef X
y,
`endif
z
);
endmodule
====
# `ifdef before the first positional connection
module m;
sub u (
`ifdef X
x,
`endif
y
);
endmodule
----
module m;
sub u (
`ifdef X
x,
`endif
y
);
endmodule
====
# two adjacent directives between connections
module m;
sub u (
.a(x),
`ifdef X
`define LOCAL 1
.b(y),
`endif
.c(z)
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
`define LOCAL 1
.b(y),
`endif
.c(z)
);
endmodule
====
# a `define with a line continuation inside a parameter override list
module m;
sub #(
`define WIDE(x) \
((x) * 2)
.P(1)
) u (.a(x));
endmodule
----
module m;
sub #(
`define WIDE(x) \
((x) * 2)
.P(1)
) u (.a(x));
endmodule
====
# directives in both lists of one instantiation
module m;
sub #(
`ifdef X
.P(1),
`endif
.Q(2)
) u (
`ifdef Y
.a(x),
`endif
.b(y)
);
endmodule
----
module m;
sub #(
`ifdef X
.P(1),
`endif
.Q(2)
) u (
`ifdef Y
.a(x),
`endif
.b(y)
);
endmodule
====
# a comment trailing a connection inside an `ifdef arm
module m;
sub u (
.a(x),
`ifdef X
.b(y), // why
`endif
.c(z)
);
endmodule
----
module m;
sub u (
.a(x),
`ifdef X
.b(y), // why
`endif
.c(z)
);
endmodule
====
# a comment written before the `)` of a directive-only override list
module m;
sub #(
`include "config.vh"
// nothing else
) u (.a(x));
endmodule
----
module m;
sub #(
`include "config.vh" // nothing else
) u (.a(x));
endmodule
====
# `ifdef in the connection list of one of several instances
module m;
sub u0 (.a(x)), u1 (
`ifdef X
.a(y),
`endif
.b(z)
);
endmodule
----
module m;
sub u0 (.a(x)),
u1 (
`ifdef X
.a(y),
`endif
.b(z)
);
endmodule
====
# an `ifdef arm holding the only connection, with more after the `endif
module m;
sub u (
`ifdef X
.a(x),
`endif
`ifdef Y
.b(y),
`endif
.c(z)
);
endmodule
----
module m;
sub u (
`ifdef X
.a(x),
`endif
`ifdef Y
.b(y),
`endif
.c(z)
);
endmodule
====
# `include between two connections
module m;
sub u (
.a(x),
`include "more.svh"
.b(y)
);
endmodule
----
module m;
sub u (
.a(x),
`include "more.svh"
.b(y)
);
endmodule
@@ -600,3 +600,82 @@ fn a_list_directive_may_still_be_reindented() {
let output = "module m (\n input a,\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
verify_equivalence(input, output).expect("only indentation changed");
}
// ---------------------------------------------------------------------------
// ... and between an instantiation's parameter overrides and connections
// (docs/features/directives-in-instances)
//
// Also no normalization: `verify.rs` is byte-identical to the commit before
// this feature, so hard invariant #4 does not bind here either. One test per
// corruption the two new parse loops could plausibly produce.
// ---------------------------------------------------------------------------
#[test]
fn a_comma_swallowed_into_a_connection_list_directive_is_rejected() {
// The same end-of-line hazard as in a header's lists: printing a
// directive's comma on its own line is what keeps the two separate tokens.
let input =
"module m;\n sub u (\n .a(x)\n`ifdef X\n ,\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x)\n `ifdef X,\n .b(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_moved_across_a_connection_list_directive_is_rejected() {
// Deriving a connection's comma from its index rather than from the source
// hops it to the other side of the `ifdef.
let input =
"module m;\n sub u (\n .a(x)\n`ifdef X\n ,\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x),\n `ifdef X\n .b(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_invented_between_two_connection_ifdef_arms_is_rejected() {
// Neither arm writes a comma; a list that commas every entry but the last
// would add one after the first `.a(x)`.
let input =
"module m;\n sub u (\n`ifdef X\n .a(x)\n`else\n .a(y)\n`endif\n );\nendmodule\n";
let output = "module m;\n sub u (\n `ifdef X\n .a(x),\n `else\n .a(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_parameter_override_directive_is_rejected() {
// The `torture/testbench.v` shape: the `include is the *only* thing in the
// override list, so losing it would silently empty the `#()`.
let input = "module m;\n sub #(\n`include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
let output = "module m;\n sub #() u (.a(x));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_connection_list_directive_printed_out_of_order_is_rejected() {
// `before` is what interleaves the directives with the connections; an
// off-by-one there emits the `endif before the connection it wrapped.
let input = "module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n";
let output = "module m;\n sub u (\n .a(x),\n `ifdef X\n `endif\n .b(y),\n .c(z)\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_before_a_directive_only_override_lists_paren_is_rejected() {
// The comment written after the list's one directive and before its `)`
// has no element to ride on; hard invariant #3 says it must still survive.
let input =
"module m;\n sub #(\n`include \"config.vh\"\n // nothing else\n ) u (.a(x));\nendmodule\n";
let output = "module m;\n sub #(\n `include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn an_instantiation_list_directive_may_still_be_reindented() {
// The other direction: re-indenting the directive to the list's level is
// what the formatter legitimately does, and must stay accepted.
let input = "module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x),\n `ifdef X\n .b(y)\n `endif\n );\nendmodule\n";
verify_equivalence(input, output).expect("only indentation changed");
}
+19 -4
View File
@@ -81,10 +81,10 @@ pub struct RawText {
}
/// A compiler directive written *between* the elements of a port,
/// parameter-port or enum-member list (`` `ifdef``/`` `else``/`` `elsif``/
/// `` `endif``, `` `define``, `` `include``) — or a standalone macro
/// invocation standing in the same place, which is passed through the same
/// way.
/// parameter-port, enum-member, parameter-override or instance-connection
/// list (`` `ifdef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
/// `` `undef``, `` `include``) — or a standalone macro invocation standing in
/// the same place, which is passed through the same way.
///
/// It is kept in a vector *beside* the elements rather than folded into one
/// enum with them: the element vectors are read by `vlog_semantic` and
@@ -498,6 +498,10 @@ pub struct Instantiation {
/// at all. An empty `Some` is a written-but-empty `#()`, which must be
/// printed back: dropping it would lose two tokens.
pub params: Option<Vec<Connection>>,
/// Directives written between the parameter overrides, in source order.
/// They live here rather than inside `params` because a `#( ... )` whose
/// whole body is one `` `include`` has no override to hang them on.
pub param_directives: Vec<ListDirective>,
pub instances: Vec<Instance>,
}
@@ -512,6 +516,11 @@ pub struct Instance {
/// `(` opening its connection list.
pub conn_comments: Vec<Comment>,
pub conns: Connections,
/// Directives written between the connections, in source order. They live
/// here rather than inside [`Connections`] because a list whose every
/// element sits in an `` `ifdef`` arm is still an empty
/// [`Connections::Ordered`].
pub conn_directives: Vec<ListDirective>,
/// Code extent of the instance, its connection list included.
pub span: TextRange,
}
@@ -526,6 +535,9 @@ pub enum Connections {
pub struct OrderedConn {
pub meta: Meta,
pub expr: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the connection; empty for an omitted one.
pub span: TextRange,
}
@@ -545,6 +557,9 @@ pub struct Connection {
/// (`.data_i (x /* verilator lint_off */)`). Printed back inside the
/// parens: after them they would sit in the enclosing list instead.
pub close_comments: Vec<Comment>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the connection.
pub span: TextRange,
}
+213 -27
View File
@@ -1557,30 +1557,43 @@ impl<'a> Parser<'a> {
let module_span = self.span_from(module_start);
let param_comments = self.take_before_open("#");
let mut params = None;
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
if last.meta.trailing.is_none() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
// Same two break conditions as a header's lists (see
// `Parser::parse_module`): no comma and no directive ends
// the list, and after a directive only the closing bracket
// does — an `` `ifdef`` arm may end without a comma and
// still be followed by an `` `else`` arm.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
// Comments before the `)` of the override list belong inside it.
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
params = Some(list);
}
@@ -1592,7 +1605,8 @@ impl<'a> Parser<'a> {
let dims = self.parse_dims()?;
let conn_comments = self.take_before_open("(");
self.expect_sym("(")?;
let conns = self.parse_connections()?;
let mut conn_directives = Vec::new();
let conns = self.parse_connections(&mut conn_directives)?;
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
@@ -1600,16 +1614,57 @@ impl<'a> Parser<'a> {
if more {
meta.trailing = self.take_trailing();
}
instances.push(Instance { meta, name, name_span, dims, conn_comments, conns, span });
instances.push(Instance {
meta,
name,
name_span,
dims,
conn_comments,
conns,
conn_directives,
span,
});
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(Instantiation { module, module_span, param_comments, params, instances })
Ok(Instantiation {
module,
module_span,
param_comments,
params,
param_directives,
instances,
})
}
fn parse_connections(&mut self) -> PResult<Connections> {
/// Move the comments written before a list's closing bracket onto the last
/// entry *in source order*, which is a trailing directive when the list has
/// one and the last element otherwise.
///
/// Without the directive case they would print before it, having moved
/// backwards across a token; with an element-less list (`` #(`include
/// "config.vh") ``) the directive is the only place they can go at all.
fn take_last_entry_before_close(
&mut self,
last_element: Option<&mut Meta>,
directives: &mut [ListDirective],
elements: usize,
) {
if let Some(d) = directives.last_mut().filter(|d| d.before == elements) {
self.take_before_sep(&mut d.meta, ")");
} else if let Some(meta) = last_element {
self.take_before_sep(meta, ")");
}
}
/// The connections of one instance. `directives` collects the
/// `` `ifdef``-style lines written between them; the harvest must run
/// before the `.`-peek below, or a directive standing before the first
/// connection would be read as a positional expression.
fn parse_connections(&mut self, directives: &mut Vec<ListDirective>) -> PResult<Connections> {
self.take_list_directives(directives, 0);
if self.cur().is_sym(")") {
return Ok(Connections::Ordered(Vec::new()));
}
@@ -1620,20 +1675,22 @@ impl<'a> Parser<'a> {
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
let comma = self.eat_sym(",");
if let Some(last) = conns.last_mut() {
if last.meta.trailing.is_none() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
// Comments before the closing `)` belong to the last conn: after
// Comments before the closing `)` belong to the last entry: after
// it they would sit outside the connection list entirely.
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Named(conns))
} else {
let mut conns = Vec::new();
@@ -1650,18 +1707,18 @@ impl<'a> Parser<'a> {
let span = self.span_from(start);
let mut meta = meta;
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
let comma = self.eat_sym(",");
if comma {
meta.trailing = self.take_trailing();
}
conns.push(OrderedConn { meta, expr, span });
if !more {
conns.push(OrderedConn { meta, expr, comma, span });
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Ordered(conns))
}
}
@@ -1681,6 +1738,7 @@ impl<'a> Parser<'a> {
name_span: star,
expr: None,
close_comments: Vec::new(),
comma: false,
span,
});
}
@@ -1709,7 +1767,7 @@ impl<'a> Parser<'a> {
};
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection { meta, name, name_span, expr, close_comments, span })
Ok(Connection { meta, name, name_span, expr, close_comments, comma: false, span })
} else {
let e = self.parse_expr_or_type()?;
let span = self.span_from(start);
@@ -1720,6 +1778,7 @@ impl<'a> Parser<'a> {
name_span: TextRange::empty(span.start),
expr: Some(e),
close_comments: Vec::new(),
comma: false,
span,
})
}
@@ -3556,6 +3615,133 @@ mod tests {
assert!(parse(tokenize(src).expect("lex error")).is_err());
}
fn instantiation_of(file: &SourceFile) -> &Instantiation {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(i) = &m.items[0].kind else {
panic!("expected an instantiation")
};
i
}
#[test]
fn a_directive_between_connections_records_its_place_and_the_commas() {
let src =
"module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.len(), 3);
assert_eq!(
conns.iter().map(|c| c.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &inst.instances[0].conn_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second connection");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2);
assert!(d.iter().all(|d| !d.comma));
assert!(inst.param_directives.is_empty(), "the override list holds none");
}
#[test]
fn a_directive_between_parameter_overrides_lands_on_the_instantiation() {
// The `picorv32/testbench.v` shape: nested `ifdef, the outer one
// wrapping the whole override list.
let src = "module m;\n sub #(\n`ifndef S\n`ifdef T\n .P(0),\n`endif\n .Q(1)\n`endif\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let params = inst.params.as_ref().expect("an override list");
assert_eq!(params.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["P", "Q"]);
assert_eq!(params.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
let d = &inst.param_directives;
assert_eq!(d.iter().map(|d| d.before).collect::<Vec<_>>(), vec![0, 0, 1, 2]);
assert_eq!(d[0].raw.text, "`ifndef S");
assert_eq!(d[3].raw.text, "`endif");
}
#[test]
fn an_override_list_may_be_nothing_but_a_directive() {
// `picorv32/scripts/torture/testbench.v`: the whole `#( ... )` is one
// `include, so there is no element to hang the directive on.
let src = "module m;\n sub #(\n`include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.params.as_ref().expect("a written `#()`").is_empty());
assert_eq!(inst.param_directives.len(), 1);
assert_eq!(inst.param_directives[0].raw.text, "`include \"config.vh\"");
assert_eq!(inst.param_directives[0].before, 0);
}
#[test]
fn a_connection_list_may_be_nothing_but_a_directive() {
let src = "module m;\n sub u (\n`ifdef X\n`endif\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("an element-less list has no `.` to make it named")
};
assert!(conns.is_empty());
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn a_directive_before_the_first_connection_does_not_hide_the_dot() {
// The harvest must run before the `.`-peek that chooses named over
// ordered connections, or the backtick is read as a positional value.
let src =
"module m;\n sub u (\n`ifdef X\n .a(x),\n`endif\n .b(y)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.len(), 2);
assert_eq!(inst.instances[0].conn_directives[0].before, 0);
}
#[test]
fn a_directive_between_positional_connections_is_harvested_too() {
let src =
"module m;\n sub u (\n x,\n`ifdef X\n y,\n`endif\n z\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("expected ordered connections")
};
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, true, false]);
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn an_instantiation_with_no_directive_keeps_empty_directive_vectors() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing instantiation byte-for-byte alike.
let src = "module m;\n sub #(.P(1)) u (.a(x), .b(y));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.param_directives.is_empty());
assert!(inst.instances[0].conn_directives.is_empty());
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
}
#[test]
fn a_directive_inside_a_connection_is_still_a_parse_error() {
// A directive runs to end of line, so it can only stand *between*
// connections. One written inside a connection's parens is out of
// scope by design; this pins that it is refused rather than half-read.
let src =
"module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error")).is_err());
}
/// The strict entry point keeps its contract: it fails at the *first*
/// error, with the same message tolerant mode files as its first
/// diagnostic.
+10
View File
@@ -55,6 +55,10 @@ const SOURCES: &[&str] = &[
"module m #(\n`ifdef X\n parameter int P = 1,\n`endif\n parameter int Q = 2\n) (\n input a,\n`ifndef Y\n input b,\n`endif\n input c\n);\nendmodule\n",
// ... and between enum members, next to a macro invocation.
"typedef enum logic {\n A,\n`include \"more.svh\"\n `LIST_OF(x)\n B\n} e_t;\n",
// ... and between an instantiation's parameter overrides and connections.
"module m;\n sub #(\n`ifdef X\n .P(1),\n`endif\n .Q(2)\n ) u (\n .a(x),\n`ifndef Y\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n",
// A list that is nothing but a directive, in both brackets.
"module m;\n sub #(\n`include \"config.vh\"\n ) u (\n`ifdef X\n`endif\n );\nendmodule\n",
];
/// A token or a comment, in source order.
@@ -473,6 +477,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
despace(&inst.module),
"the instantiated module span does not slice back to its name"
);
for d in &inst.param_directives {
assert_inside(src, "list directive", d.raw.span, here);
}
for c in inst.params.iter().flatten() {
assert_inside(src, "parameter override", c.span, here);
check_name(src, "parameter override name", &c.name, c.name_span, c.span);
@@ -481,6 +488,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
for i in &inst.instances {
assert_inside(src, "instance", i.span, here);
check_name(src, "instance name", &i.name, i.name_span, i.span);
for d in &i.conn_directives {
assert_inside(src, "list directive", d.raw.span, i.span);
}
match &i.conns {
Connections::Named(cs) => {
for c in cs {
@@ -0,0 +1,562 @@
# directives-in-instances
## Goal
Accept `` `ifdef``/`` `ifndef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
`` `undef``, `` `include`` — and standalone macro invocations — written *between
the elements* of a module **instantiation**'s parameter override list `#( ... )`
and of an instance's connection list `( ... )`. This is the slice the
`directives-in-lists` round parked under Status/TODO and its Review named as the
next round's shape: same construct, same solution, different parse loops. Six
corpus files were blocked on exactly this, and it is the single biggest
remaining directive-shaped blocker.
## Assumptions
Everything `directives-in-lists` assumed still holds and is not re-argued here;
read that README's Assumptions first. The ones specific to this round:
- **A directive is line-oriented.** Inherited. So the one-line spelling
``u #(.A(1), `ifdef X .B(2), `endif .C(3)) i ();`` is still unsupported — the
lexer reads from `` `ifdef`` to end of line as one token. No corpus file
writes it.
- **Both arms contribute.** `` `ifdef``/`` `else`` arms are both ordinary
entries of the one list, in source order. vfmt does not evaluate conditions.
- **A *comment* may share a directive's line, but a comma may not.** The
lexer's directive capture stops before a `//` or `/*`
(`crates/vlog_parser/src/lexer.rs:182`), so `` `endif // why`` round-trips as
two pieces, while `` `endif,`` would come back as one token whose condition
is `,`. This asymmetry is what lets a before-`)` comment print inline on the
directive's line while the directive's comma is forced onto a new one.
- **The comma is data, not a formatting choice.** Same two directions as last
round, and instantiations write both: `picorv32/testbench.v` puts the comma
*inside* the arm (`.ENABLE_REGS_DUALPORT(0),` ⏎ `` `endif``), and
`ibex_lockstep.sv` ends an arm with no comma at all before `` `endif``.
- **A connection list that is nothing but a directive is still a list.**
`picorv32/scripts/torture/testbench.v` writes ``#(`` ⏎ `` `include "config.vh"``
⏎ ``)`` — zero elements, one directive. That is why the directive vector
cannot live inside `Connections`, whose "no elements" spelling is
`Connections::Ordered(vec![])`.
- **Gate instantiations are out of scope, by measurement.** No corpus file
writes a directive between the arguments of a gate instance; see
Status/TODO for the grep that says so, and why the shape would need a
different vehicle (`ExprItem`, shared with every other expression list).
- **A directive between an instance *name* and its `(`, or between two
instances of one declaration, is still a parse error.** Out of scope; the
construct this feature accepts is a directive standing where a list
*element* would start.
## Handshakes
**New in `vlog_parser::ast` (consumed by `vlog_formatter::format`), all
additive — no variant grew, no vector changed type:**
| carrier | new field |
|---|---|
| `Instantiation` | `param_directives: Vec<ListDirective>` |
| `Instance` | `conn_directives: Vec<ListDirective>` — on the instance, not inside `Connections`, because a list whose every element sits in an arm is still an empty `Connections::Ordered` |
| `Connection`, `OrderedConn` | `comma: bool` — whether a `,` followed this element in the source |
`ListDirective` itself is reused verbatim from `directives-in-lists`
(`raw`/`meta`/`before`/`comma`); no field was added and its meaning is
unchanged. So is `Parser::take_list_directives`, whose no-op-unless-on-a-
directive contract is what keeps every pre-existing case byte-identical.
**Why the connection-list vector lives on `Instance` and not on
`Connections`** — the same blast-radius argument the last round made, checked
again rather than assumed:
- `vlog_semantic::bind` (`crates/vlog_semantic/src/bind.rs:412,417`) matches
`Connections::Named(conns)`/`Connections::Ordered(conns)` and iterates the
vector. `crates/vlog_parser/tests/spans.rs:485,492` does the same.
- Nothing outside `vlog_parser::parser` **constructs** a `Connection`,
`OrderedConn`, `Instance` or `Instantiation`, so new struct fields cost those
readers nothing — verified by grep before the change and by
`cargo test --workspace` after it.
- Folding directives into the element vector (`enum ConnEntry { Conn, Directive }`)
would have forced edits in `vlog_semantic`, which is outside this feature's
scope. A parallel vector keyed by `before` preserves source order just as
well.
- Putting the vector *inside* `Connections` would need a third variant or a
field on each — and the directive-only list has no variant to hang it on.
`Instance.conn_directives` sits next to `Instance.conns` and needs neither.
`Instantiation.param_directives` has no such choice to make: `params` is an
`Option<Vec<Connection>>` on `Instantiation` already, so its directive vector
goes beside it, exactly as `Module.param_directives` sits beside
`Module.param_ports`.
**Consumed from `verify.rs`: nothing new. `crates/vlog_formatter/src/verify.rs`
is byte-identical to `HEAD`** (`git diff --quiet` exits 0), so CLAUDE.md hard
invariant #4 does not bind this round either. Rejection tests for the new
shapes were added to `tests/verification.rs` anyway, so that a future round
tempted to widen `normalize` has to argue with them.
**Format fences: untouched.** `crates/vlog_formatter/src/fence.rs`,
`tests/fences.rs` and `fences.cases` are diff-clean. `fence::scan_scope` walks
item-level leading comments, and `format.rs`'s fence interaction points
(`Fmt::item_seq`, `Fmt::verbatim`) were not edited — the two functions this
round changed (`Fmt::instantiation`, `Fmt::connections`) do not call into
`fence`. A second agent is refactoring `fence.rs` concurrently; `format.rs` was
re-read immediately before each edit.
**Recursion/chain budgets:** unaffected and nothing charged. A `ListDirective`
is an AST leaf (a `String`, not a `Box<Expr>`), and `take_list_directives` is a
flat `while` over already-lexed tokens. A nested `` `ifdef`` costs no depth: the
arms are consecutive entries of one flat list, not nested nodes.
**Spans:** `ListDirective.raw.span` is the directive's own token range, nesting
inside the enclosing item's span. `crates/vlog_parser/tests/spans.rs` now walks
`inst.param_directives` and each `instance.conn_directives`, and two sources
holding them were added to `SOURCES`.
**Not touched, by scope:** `crates/vfmt`, `crates/vfmt_core`,
`crates/vfmt_server`, `crates/vlog_linter`, `crates/vlog_semantic`,
`crates/vlog_formatter/src/verify.rs`, `crates/vlog_formatter/src/fence.rs`,
`editors/`, `tools/`, `corpus/`. `cargo fmt` was run per-package
(`-p vlog_parser -p vlog_formatter`), never `--all`, so it could not rewrite the
concurrent agent's files.
## Design
### Parser — the same loop shape, two more lists
`directives-in-lists` established the shape; this round instantiates it twice
more:
```rust
self.take_list_directives(&mut directives, 0); // before the first element
if !self.cur().is_sym(CLOSE) {
loop {
list.push(self.parse_connection()?);
self.take_before_sep(&mut last.meta, ",");
let comma = self.eat_sym(",");
last.comma = comma;
let dirs = self.take_list_directives(&mut directives, list.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(CLOSE)) {
break;
}
}
}
```
The two break conditions are unchanged and load-bearing for the same two
reasons: an arm may end without a comma and still be followed by an `` `else``
arm, and an arm may have been the tail of the list.
The pre-loop harvest is what makes `picorv32/testbench.v` (`#(` ⏎
`` `ifndef SYNTH_TEST``) and `torture/testbench.v` (`#(` ⏎ `` `include``) work,
and in `parse_connections` it must happen **before** the `.`-peek that chooses
named vs ordered connections — otherwise `u (` ⏎ `` `ifdef X`` ⏎ `.a(x)` reads
the backtick as a positional expression, which is precisely today's error.
### The comments written before the closing `)`
The parameter-override list and the connection list have no `dangling` bucket:
comments before their `)` ride the last element's `before_sep`. With a
directive after the last element, "the last element" is no longer the last
thing in source order, so the comments would move *backwards* across the
directive. `Parser::take_last_entry_before_close` picks the last entry in
source order instead — the trailing directive when there is one, otherwise the
last element, and nothing at all when the list is empty and has no directive
(unchanged from before). Choosing the trailing directive is why a
directive-only list keeps its comments inside the parens at all.
This is deliberately *not* a new `dangling` field: adding one would move every
existing before-`)` comment in every instantiation in the corpus from the
element's line onto its own line, a formatting change for files this feature is
not about. Recorded here so the next reader does not re-litigate it.
### Formatter — nothing new, two more call sites
`Fmt::list_entries` and `Fmt::directive_entry` are reused unchanged.
`Fmt::instantiation` merges `inst.param_directives` into the override list and
`Fmt::connections` takes `&[ListDirective]` and merges them into whichever
`Connections` variant it was given. Both set `delimited`'s `force_break`
whenever the merged list holds a directive — not cosmetic: a single-line
directive is a plain `Doc::Text`, so nothing else would force the group open,
and a flat ``(.a(x), `ifdef X, .b(y))`` would fuse three tokens into one and be
refused by the net.
Every element now carries `with_comma(c.comma)` instead of letting the position
decide. For a list with no directive the parser records exactly `i < last` — the
loop only continues past a comma — which is why no pre-existing case moved.
## Status / TODO
- [x] `param_directives` on `Instantiation`, `conn_directives` on `Instance`,
`comma` on `Connection` and `OrderedConn`; every change additive, so
`vlog_semantic` and `vlog_linter` compile unmodified.
- [x] `take_list_directives` wired into the `#( ... )` override loop and into
both branches of `parse_connections` (named and ordered), plus the
pre-loop harvest in each.
- [x] Directive-only lists (`#(` ⏎ `` `include "config.vh"`` ⏎ `)`), directives
before the first / between / after the last element, nested `` `ifdef``,
`` `else``/`` `elsif``, both comma placements, `.*` beside a directive,
`` `define``/`` `undef``/standalone macro invocation between connections.
- [x] `Parser::take_last_entry_before_close` so a comment before the `)` stays
on the source's side of a trailing directive.
- [x] 24 cases appended to
`crates/vlog_formatter/tests/cases/directives_in_lists.cases`
(20 → 44 in that file, 335 → 359 overall); idempotency asserted by the
harness.
- [x] 8 parser unit tests, 7 `tests/verification.rs` tests (6 of them rejection
tests for the new shapes), 2 new `spans.rs` sources + walker coverage of
both new vectors.
- [x] `verify.rs` byte-identical to `HEAD`.
- [x] `cargo test --workspace` 589 passed / 0 failed, clippy silent, fmt clean,
`tools/corpus_check.sh` exit 0 with 0 verification errors and 0 crashes.
- [x] **All six named corpus targets format**, 0 regressions by path, and no
corpus file is blocked on a compiler directive any more.
- [ ] **Not done — gate instantiations.** No corpus file demands it. Measured
rather than assumed: a `grep -rE` over all 820 corpus files for a gate
keyword (`and`/`or`/`nand`/…/`tranif1`) opening a line without a `;` on
it — i.e. any gate instantiation spread over more than one line, which is
the only way a line-oriented directive could stand inside one — matches
exactly one line, and that line is English prose in a comment
(`corpus/ibex/dv/formal/check/peek/follower.sv:11`). It would also need a
different vehicle: gate arguments are
`Vec<ExprItem>` parsed by the shared `parse_expr_list`, which every
concatenation and call-argument list in the language also uses, so
adding a directive vector there is a much larger blast radius than two
instantiation-local loops. Filed rather than guessed.
- [ ] **Not done — the one-line spelling.** Inherited from
`directives-in-lists`; a lexer round of its own.
- [ ] **Not done — a directive between an element's own tokens**, e.g.
`.a(` ⏎ `` `ifdef X`` ⏎ `y` ⏎ `` `endif`` ⏎ `)`. Out of scope by design;
clean parse error, never output. Pinned by
`a_directive_inside_a_connection_is_still_a_parse_error`.
- [ ] **Not done — a directive between two instances of one declaration**
(`sub u0 (...),` ⏎ `` `ifdef X`` ⏎ `u1 (...);`). No corpus file writes
it; clean parse error.
## Corpus results
`./tools/corpus_check.sh corpus`, release build, script exit status **0**.
Three runs, TSVs byte-identical (md5 `0a3dad76ad648af8494dca637dbba52b` each
time).
Corpus repos verified unmodified afterwards (`git status --porcelain` clean in
all four except the untracked `.vfmt-corpus-rev` stamp).
The "before" column is **not** the previous round's published table: a second
agent's work (`shared-fence-filter`, `server-lint`) landed in this working tree
mid-session. It was re-measured on *this* tree with only this feature's three
source files stashed out, and came back byte-identical to the previous round's
TSV (md5 `31ffdb18c96d4e79057178f7de269756`) — so the delta below is entirely
this feature's.
| outcome | before | after |
|---|---|---|
| ok-unchanged | 8 (1.0 %) | 8 (1.0 %) |
| would-reformat | 462 (56.3 %) | **468 (57.1 %)** |
| parse-error | 350 (42.7 %) | **344 (42.0 %)** |
| verification-error | 0 | **0** |
| other-error | 0 | 0 |
| crash | 0 | 0 |
| **parsed & formattable** | 470/820 (57.3 %) | **476/820 (58.0 %)** |
**By-path delta, diffed by file path rather than by count: 6 files moved
`parse-error` → `would-reformat`, 0 files moved the other way, 0 files that
already parsed changed category, and 0 files advanced to a merely *different*
error.** The six are exactly the six named targets:
| file | before | after |
|---|---|---|
| `corpus/ibex/rtl/ibex_lockstep.sv` | `parse-error` 518:1 `` `ifdef RVFI`` | **would-reformat** |
| `corpus/ibex/rtl/ibex_top.sv` | `parse-error` 456:1 `` `ifdef RVFI`` | **would-reformat** |
| `corpus/ibex/dv/formal/check/spec_instance.sv` | `parse-error` 65:5 `` `define X(n) …`` | **would-reformat** |
| `corpus/picorv32/testbench.v` | `parse-error` 164:1 `` `ifndef SYNTH_TEST`` | **would-reformat** |
| `corpus/picorv32/testbench_wb.v` | `parse-error` 110:1 `` `ifndef SYNTH_TEST`` | **would-reformat** |
| `corpus/picorv32/scripts/torture/testbench.v` | `parse-error` 41:1 `` `include "config.vh"`` | **would-reformat** |
All six were re-run through `vfmt -` for three passes; every pass exited 0
(which already means `format_source`'s internal `verify_equivalence` +
`verify_convergence` accepted it) and pass1 == pass2 == pass3 byte-for-byte.
**No corpus file is blocked on a compiler directive any more.** Before this
round 6 of the 350 parse errors had a backtick as their "found" token; after it
`grep -c 'found "`' ` over the results TSV is **0**.
### Workspace index / semantic resolution
`cargo test -p vlog_semantic --test workspace -- --nocapture
the_corpus_index_finishes_most_external_references`, same 860-file scan:
| metric | before | after |
|---|---|---|
| modules indexed | 530 | 530 (unchanged) |
| packages / file-scope typedefs | 63 / 37 | 63 / 37 (unchanged) |
| exported members | 9 174 | 9 174 (unchanged) |
| `` `define`` directives | 502 | 502 (unchanged) |
| external candidates answered (every file) | 86.9 % | **87.3 %** |
| external candidates answered (clean files) | 93.6 % | **94.0 %** |
| unresolved-external rate (clean files) | 1.3 % | **1.2 %** |
Stated plainly: **the index counts did not move, and were not expected to.**
The six unblocked files are testbenches, a lockstep wrapper and a formal
harness whose module *headers* already parsed, so `parse_source_tolerant`
already indexed their modules; only their bodies were failing. The resolution
percentages move only because six more files joined the "parses cleanly"
bucket. The payoff of this round is six files that format, not a bigger index.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, `TODO.md` and the whole
`directives-in-lists` README before touching code, then read all six named
corpus targets at their cited lines. They are the spec, and reading them
first is what produced the two shapes a design-from-first-principles would
have missed: a `#( ... )` whose *entire* body is one `` `include``
(`torture/testbench.v`) and a `` `define``/macro-invocation/`` `undef``
triplet standing between connections with no commas anywhere
(`spec_instance.sv:65`).
- **Baseline measured on this working tree, not taken from the last round's
README.** `cargo test --workspace` was 568 (not the 563 the brief quotes —
a second agent's `server-lint` tests had already landed), and the corpus TSV
was md5 `31ffdb18c96d4e79057178f7de269756`, matching the previous round's
published "after". One `vfmt_server` e2e test
(`fix_all_edits_exactly_what_vfmt_check_fix_edits_inside_a_fence`) was
failing mid-session; **verified it fails identically with this feature's
three files stashed out**, so it was the other agent's in-flight
`shared-fence-filter` work, not mine. It is green again in the final run.
- **Chose the vector homes by blast radius, and checked rather than assumed.**
`grep` for every construction site of `Connection`/`OrderedConn`/`Instance`/
`Instantiation` outside `parser.rs` came back empty — only pattern matches in
`vlog_semantic::bind` and `spans.rs` — so purely additive struct fields cost
the out-of-scope crates nothing. `conn_directives` went on `Instance` rather
than into `Connections` for the reason the last round put `port_directives`
on `Module`: the element-less spelling (`Connections::Ordered(vec![])`) has
no variant to hang a vector on, and `torture/testbench.v` proves that
spelling is real.
- **The pre-loop harvest in `parse_connections` must precede the `.`-peek.**
That peek is what chooses named over ordered connections; run after it, a
directive standing before the first connection is read as a positional
expression — which is verbatim today's error message
(`expected expression (found "`ifdef RVFI")`). Pinned by
`a_directive_before_the_first_connection_does_not_hide_the_dot`.
- **Found and fixed a real comment-drop while writing the cases.** The
override list has no `dangling` bucket, so comments before its `)` ride the
last element's `before_sep`; with a *trailing directive* there is no such
element. Added `Parser::take_last_entry_before_close` to pick the last entry
in source order — and then discovered `Fmt::directive_entry` **overwrote**
`before_sep` with the directive's `trailing` comment instead of appending,
so the comment vanished. The safety net caught it (`verification failed:
token stream diverges … input has comment "// nothing else"`), i.e. the file
was refused rather than corrupted — invariant #3 held — but it is now fixed
and pinned by
`a_dropped_comment_before_a_directive_only_override_lists_paren_is_rejected`.
- **Tried the wrong fix first and let a test kill it.** My first instinct was
that a comment printed on a directive's line would be swallowed by the
lexer's end-of-line capture, so I made a directive's `before_sep` comments
each start a new line. `case_tables` failed immediately at
`directives_in_lists.cases:253`, and reading `lexer.rs:182` explained why:
the capture **stops before a `//` or `/*`**. The inline placement is correct
and round-trips; the change was reverted and the comment in
`delimited_dangling` now records the fact instead of the guess.
- **Every element now records the comma it was written with**
(`with_comma(c.comma)`), replacing the positional rule, for both connection
variants and the override list. For a list with no directive the parser
records exactly `i < last`, which is why all 335 pre-existing cases and every
snapshot were green on the first run of the parser + formatter change (the
one later `case_tables` failure came from the reverted experiment above, not
from the comma).
- **Gate instantiations were measured, not guessed, before being parked.**
No corpus file writes a multi-line gate instantiation at all, so none can
hold a directive between gate arguments; and gate args are the shared
`Vec<ExprItem>`/`parse_expr_list` used by every concatenation and call in the
language, so adding a directive vector there is a far larger blast radius
than two instantiation-local loops. Filed under Status/TODO with that
reasoning rather than half-implemented.
- **`verify.rs` was never opened.** `git diff --quiet --
crates/vlog_formatter/src/verify.rs` exits 0, so hard invariant #4 does not
bind; the seven `tests/verification.rs` tests (six rejection, one
legitimate-re-indent) were added anyway so a future widening has to argue
with them.
- **Corpus delta verified by path against a same-tree baseline**, because the
tree moved under me mid-session: stashed only this feature's three source
files, rebuilt release, re-ran the corpus, and got a byte-identical TSV to
the previous round's — so every one of the 6 gains is attributable here. Ran
the final corpus twice; identical md5. All four corpus repos confirmed
unmodified.
- **Did not touch** `crates/vfmt`, `crates/vfmt_core`, `crates/vfmt_server`,
`crates/vlog_linter`, `crates/vlog_semantic`, `verify.rs`, `fence.rs`,
`tools/`, `corpus/`. Ran `cargo fmt -p vlog_parser -p vlog_formatter`, never
`--all`, so the concurrent agent's files could not be rewritten. Re-read
`format.rs` immediately before each edit; its diff contains only this
feature's hunks. Did not run `git commit`/`git push`.
**Results:** `cargo test --workspace` **589 passed, 0 failed** (568 baseline +
8 parser unit + 7 verification, plus 6 from the concurrent agent's crates; the
24 new `.cases` entries run inside `case_tables`, now 359 cases).
`cargo clippy --workspace --all-targets` silent. `cargo fmt -p vlog_parser
-p vlog_formatter -- --check` clean. `tools/corpus_check.sh corpus` exit 0,
0 verification errors, 0 crashes.
Files touched: `crates/vlog_parser/src/{ast,parser}.rs`,
`crates/vlog_parser/tests/spans.rs`,
`crates/vlog_formatter/src/format.rs`,
`crates/vlog_formatter/tests/cases/directives_in_lists.cases`,
`crates/vlog_formatter/tests/verification.rs`, `README.md` (supported-syntax
list + roadmap item 6), `TODO.md` (§ workspace-index annotation), this README.
## QA log
### 2026-08-19 — QA agent
**Verdict: PASS, no blocking findings.**
**Scope check.** `git diff --stat` on `crates/vlog_semantic`, `crates/vlog_linter`
and `crates/vlog_formatter/src/verify.rs` all empty — additive-only claim
holds. `crates/vlog_formatter/src/fence.rs` (148 insertions) is the concurrent
`shared-fence-filter` agent's work, correctly attributed and left untouched;
did not read or write anything under `docs/features/shared-fence-filter/`.
**Design claims (1).** Confirmed by reading the diffs directly:
`Instantiation.param_directives`, `Instance.conn_directives`,
`comma: bool` on `Connection`/`OrderedConn` are all new fields (not present at
`HEAD`, i.e. not inherited from `directives-in-lists`). The pre-loop harvest
(`self.take_list_directives(directives, 0);`) in `parse_connections` sits
before the `.`-peek (`crates/vlog_parser/src/parser.rs`, the
`if self.cur().is_sym(...)` name check) — read the function directly, matches
the README's claim. Reproduced the failure the harvest prevents: with the
harvest removed conceptually (verified via the dedicated unit test
`a_directive_before_the_first_connection_does_not_hide_the_dot`, which passes
under the current code), a directive before the first connection would read
as a positional expression per the work log's cited error text.
**Round-trip torture (2, 3-pass).** 20 hand-written probe files in
`/private/tmp/.../scratchpad/torture/`: directive around first/middle/last
connection (both named and ordered), `#( ... )` with and without trailing
params, else/elsif chains, nested `` `ifdef``, comma-in-arm and no-comma-arm
both directions, connection-list-is-only-a-directive
(`Connections::Ordered(vec![])` case), params-list-is-only-a-directive,
`.*` beside a directive, directive + trailing `//` comment, directive +
comment before the closing `)` (the fixed bug's exact shape), multi-instance
with a directive in one instance's list. All 18 in-scope shapes: pass1 == pass2
== pass3 byte-for-byte, exit 0/0/0 (three separate `vfmt -` invocations via the
debug binary, not just one `--check`). The two out-of-scope shapes (gate
instance with a directive between arguments; a directive between two instances
of one declaration) both give a clean parse error and never emit output —
matches Status/TODO's documented behavior exactly, no silent misparse.
**Six named targets (3).** All six `would-reformat`, 0 backtick-blocked parse
errors corpus-wide
(`grep -c 'found "`'` over the results TSV → 0, matches). Verified the
directive lines survive formatting *by line number*: read each target at its
originally-cited line (`ibex_lockstep.sv:518`, `ibex_top.sv:456`,
`spec_instance.sv:65`, `testbench.v:164`, `testbench_wb.v:110`,
`torture/testbench.v:41`) and grepped the same directive text in
`vfmt --stdout` output — present verbatim (only re-indented) in all six.
**Corpus (3).** `tools/corpus_check.sh corpus` release build, run twice:
byte-identical TSVs, md5 `0a3dad76ad648af8494dca637dbba52b` both times —
exact match to the claim. Counts: 8 ok-unchanged / 468 would-reformat / 344
parse-error / 820 total, 476/820 = 58.0%, 0 verification-error, 0 crash — all
exact. Re-derived the "before" baseline independently rather than trusting the
README's number: stashed the six feature source files
(`ast.rs`/`parser.rs`/`format.rs`/`directives_in_lists.cases`/
`verification.rs`/`spans.rs`), rebuilt release, re-ran the corpus — md5
`31ffdb18c96d4e79057178f7de269756`, exact match to the claimed "before" hash,
8/462/350. By-path join of before vs. after: exactly 6 rows differ, all
`parse-error` → `would-reformat`, and all six are exactly the six named
targets, 0 rows moved the other direction, 0 other-category changes. Restored
the stash and rebuilt afterward; `git status --porcelain` matched the
pre-stash state exactly.
**The found-and-fixed bug (4).** Confirmed the shape: old `directive_entry`
set `before_sep: d.meta.trailing.clone().into_iter().collect()` (pure
overwrite, discarding whatever `take_last_entry_before_close` had already put
into `d.meta.before_sep`); new code clones `d.meta.before_sep` first and
`.extend()`s the trailing comment onto it. Sabotage: reverted `format.rs`'s
`directive_entry` to the overwrite form (`git diff --stat` afterward showed
identical line counts to the pre-sabotage diff, so the sabotage was a faithful
inverse). Two things worth recording precisely:
- The specific test named in the work log,
`a_dropped_comment_before_a_directive_only_override_lists_paren_is_rejected`
in `tests/verification.rs`, **does not actually pin the bug** — it calls
`verify_equivalence(input, output)` directly on a hand-authored
`(input, corrupted-output)` pair and never touches `format.rs`, so it passed
unchanged under the sabotage. This is by design per CLAUDE.md invariant #4
(an attack test on `verify.rs`'s forgiveness), just not an integration pin —
the work log's phrasing ("pinned by ... `a_dropped_comment_before...`")
slightly overstates what that specific test covers.
Not a blocking finding since the *actual* pin exists and does its job (next
bullet); recorded so the phrasing can be tightened.
- The real pin is `directives_in_lists.cases:780`
(`a comment written before the `)` of a directive-only override list`),
exercised by `cargo test -p vlog_formatter case_tables`. Under sabotage it
failed exactly as the work log describes:
`format failed: verification failed: token stream diverges at index 7: input
has comment "// nothing else" at 4:5, output has symbol ")" at 4:3` — safety
net rejects, does not corrupt, invariant #3 holds even in the sabotaged
state. Reverted the sabotage; `cargo test -p vlog_formatter -p vlog_parser`
green again, `git diff --stat -- crates/vlog_formatter/src/format.rs`
identical to before the sabotage (65 changed lines, same shape).
**Gates (5).** `cargo test --workspace`: 27+48+31+109+5+13+1+4+6+2+63+71+30+72+
24+19+17+6+1+19+20+1 = **589 passed, 0 failed** — exact match to the dev's
snapshot, no drift from the concurrent round at time of this QA pass.
`cargo clippy --workspace --all-targets`: silent, 0 warnings.
`cargo fmt -p vlog_parser -p vlog_formatter -- --check`: exit 0.
`crates/vlog_formatter/src/verify.rs`: `git diff --quiet` exits 0, byte-
identical to `HEAD`. `vlog_semantic` workspace-index re-run
(`the_corpus_index_finishes_most_external_references`): 530 modules /
63 packages / 37 typedefs / 9174 exported members / 502 defines (all
unchanged, as claimed), external-candidates-answered 87.3% (every file) /
94.0% (clean files) — exact match — unresolved-external rate on clean files
1.2% (from the printed "External-candidate rate after the workspace layer:
1.2%"), exact match. README.md and TODO.md diffs read in full: both describe
exactly this round's delta, no overstatement found (TODO.md is explicit that
the index *counts* didn't move and only the resolution percentages did,
matching the actual numbers).
**Compliance.** No `unwrap()`/`expect()`/`panic!()` in non-test code added by
this diff — all ten occurrences found in `parser.rs`'s diff are inside
`#[cfg(test)]` (`instantiation_of` helper and the eight new unit tests), which
CLAUDE.md permits. No `unsafe` introduced. New public struct fields
(`param_directives`, `conn_directives`, `comma` x2) each carry a one-line doc
comment. README has all seven required sections, all current; Work log entries
are dated and specific (file:line citations throughout). Did not touch Review.
No commit/push performed.
**Files touched by this QA pass:** none outside this README's QA log (this
section). Scratch artifacts (probe files, corpus TSVs, join diffs) live under
`/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/9ecac3b9-8a0e-4065-85de-23cc2a396bad/scratchpad/`,
not in the repo.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 15. No corpus
file is blocked on a compiler directive any more — the directive story
is complete for every list kind real RTL exercises.**
Points reviewed and accepted:
1. **All six named targets format**, verified by QA down to the
directive lines surviving verbatim in output, with the before-
baseline independently re-derived by stashing the feature files —
the cleanest attribution method available and now the house
standard for concurrent-round deltas.
2. **The harvest-before-dot-peek ordering** is the kind of one-line
subtlety these READMEs exist to record: run after the peek, a
leading directive parses as a positional expression. Documented,
and the design reuses the prior round's machinery verbatim rather
than growing a second pattern.
3. **The en-route bug** (directive_entry overwriting before_sep,
dropping a comment — net-caught as a refusal, invariant 3 held) was
fixed with the wrong-fix-first honesty this project rewards: the
attempted own-line placement was killed by the case table, and the
lexer's own capture rule proved inline correct.
4. **QA's attribution correction adopted as a lead note**: the
integration pin for that fix is `directives_in_lists.cases:780`
(which fails under sabotage), not the similarly-named rejection
test in verification.rs (which pins verify.rs strictness on a
literal pair and passes regardless). The work log's wording stands
as written; readers should trust the case table for the fix path —
the same two-layer division comments-round-2's review already
described.
Clean-file external resolution now 94.0%, unresolved externals 1.2%.
The remaining directive-shaped work is the one-line spelling (a lexer
round of its own, no corpus demand) — parked where it was.
+9 -2
View File
@@ -97,6 +97,8 @@ this is protocol-layer wiring, which is all `vfmt_server` is allowed to be.
inside a `// verilog_format: off` fence, and that refusal lives in
`crates/vfmt/src/lint.rs`, not in `vlog_linter` — so it is **not** inherited
here. See Status/TODO; it is the one honest gap this round leaves.
~~not inherited here~~ **Inherited as of shared-fence-filter (round 14): the
filter moved to `vlog_formatter::fence` and this crate calls it.**
## Handshakes
@@ -149,6 +151,11 @@ user setting, not an extension one.
than half-fixed: the right home is a shared helper both front ends call. It
cannot corrupt code (every offered fix is Safe), but it does violate the
fence's "hands off" promise the same way the CLI did before its QA round.
~~a quick fix in this server *can* edit inside a fence~~ **Delivered by
shared-fence-filter (round 14): `vlog_formatter::fence::protected_regions`
is now the one answer both front ends call, and `lint::fixable` withholds
any fix that would edit a fenced byte — reported, never auto-fixed, exactly
as the CLI.**
4. *lead*: **`TODO.md:353` is now stale.** §6's `vfmt_server` entry still lists
"lint diagnostics (waits on `vlog_linter`)" under **Not shipped**. TODO.md is
outside this round's stated scope, so it was left alone rather than edited;
@@ -212,9 +219,9 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
- [ ] **Not done, deliberately:** offering Unsafe fixes. No rule ships one, and
when one does it wants a decision (a separate `source.fixAll` kind? a
client setting?), not a silent inclusion.
- [ ] **Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit
- [x] ~~**Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit
inside a `// verilog_format: off` region, where `vfmt check --fix` would
not.
not.~~ Delivered by **shared-fence-filter** (round 14).
- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in
full; lazy resolution is a payload optimization for actions that are not.
- [ ] **Not done:** sharing one parse with the linter (Handshake 1).
+450
View File
@@ -0,0 +1,450 @@
# shared-fence-filter
## Goal
There were two answers to "which bytes does a `// verilog_format: off` fence
protect from an automatic edit", and one of them was missing. The formatter
had `fence::collect`; `vfmt check --fix` had its own union of that plus a
line-scan backstop, written inside `crates/vfmt/src/lint.rs` because the
linter crate deliberately does not depend on `vlog_formatter`; and
`vfmt_server`'s quick fixes had **none**, so a lightbulb in an editor happily
rewrote bytes `vfmt check --fix` refused to touch (server-lint Handshake 3,
reproduced live by that round's QA). This round moves the CLI's computation
down into `vlog_formatter::fence` as `protected_regions` + `is_protected` and
has both front ends call it, so the fence answer is defined once. The CLI's
behavior is unchanged byte for byte; the server gains the CLI's
**reported-but-never-auto-fixed** semantics.
## Assumptions
- **The union is the right answer for an editing tool, and the front ends
must not each decide that.** `fence::collect` is authoritative wherever the
tree is good; a line scan pairing each `off` with the next `on` (or EOF) is
the backstop for the tolerant-parse population — files where error recovery
swallows the item structure a region hangs on and `collect` returns nothing.
That population is *the linter's and the server's whole world*: a buffer
mid-keystroke rarely parses. This is inherited unchanged from linter-core's
QA round, including its measurement that `collect` alone was not enough.
- **Protecting more than the formatter emits verbatim is the harmless
direction.** The scan has no notion of scope and would be fooled by a fence
spelled inside a block comment; both only ever decline an edit, which costs
a fix, not correctness.
- **`protected_regions` takes `&str` and parses internally, on purpose.** The
alternative — accepting a caller's `SourceFile` — would let the two front
ends feed different trees and get different answers, which is the drift this
feature exists to end. The cost is one tolerant parse per call, paid only on
paths that are about to *apply* a fix: `vfmt check --fix` (already
re-parsing per round) and `textDocument/codeAction`. The server's
per-keystroke diagnostics path pays nothing, because it never reads a fix.
- **The regions this function returns are for `is_protected` only.** Unlike
`collect`'s output they may overlap and are not sorted, so `region_at`'s
binary search must not be pointed at them. `is_protected` is a linear scan,
which is right for a list this size and immune to the ordering question.
- **An insertion is protected too.** An empty edit range covers the byte it
would land in front of, so nothing can be spliced into a region.
- **A fix is all-or-nothing**, so one edit inside a fence withholds the whole
fix — never half of it. Both front ends apply that rule; it belongs to the
fix model (`linter-core`), not to the fence.
- **Fences never suppress a *finding*.** Both front ends still report a
violation inside a fence; only its automatic fix is withheld. Silencing a
finding is what waivers, `--ignore` and `--select` are for.
## Handshakes
**Promised by `vlog_formatter::fence`** (new; nothing existing changed):
- `pub fn protected_regions(src: &str) -> Vec<Region>` — every byte range in
`src` no tool may edit automatically. The union described above.
- `pub fn is_protected(regions: &[Region], start: usize, end: usize) -> bool`
— whether a byte range overlaps any of them, with the empty-range
(insertion) rule folded in.
Both are documented at the item and are the *only* supported way to ask the
question. `fence_of`, `collect`, `region_at`, `Fence` and `Region` are
unchanged, and the formatter's own use of `collect` is untouched — this is
additive.
**Consumed by `crates/vfmt/src/lint.rs`**: `fixable_outside_fences` now calls
`protected_regions`, and `touches_fence` is a one-line map over
`is_protected`. The file's own `scanned_fence_regions` was **moved**, not
copied — it no longer exists there.
**Consumed by `crates/vfmt_server/src/lint.rs`**: `fixable` — the code-action
path, and only that path — drops any violation whose fix would edit a
protected byte. `violations`/`diagnostics` (the publishing path) are
deliberately untouched, which is what keeps a fenced finding reported.
**Relied on from `vlog_parser`**: `parse_source_tolerant` never panics and
returns a usable tree for any input, and `LineIndex::{line_count, line_range}`
are byte ranges over the same text. `vlog_formatter` already depended on
`vlog_parser`; no crate gained a dependency and no `Cargo.toml` was edited.
**Deliberately not done — `vlog_linter` still has no notion of fences.** Its
dependency list stays `vlog_parser` + std (the property linter-core's QA
verified with `cargo tree`), so the filter lives in each front end, one line
each, over a shared answer. Moving it into the linter would invert that
dependency for no gain: the two lines that remain are "which violations does
*this* tool offer", not "what is fenced".
## Status / TODO
- [x] `fence::protected_regions` + `fence::is_protected` in
`crates/vlog_formatter/src/fence.rs`, with the scan (`scanned_regions`)
moved down from `crates/vfmt/src/lint.rs`.
- [x] Unit tests in `fence.rs`: the boundary matrix (first/last byte inside,
adjacent-outside both ends, straddling either edge, insertions, empty
region list), a good-tree region, the broken-file backstop (asserting
the premise — `collect` really does return nothing there), an unclosed
fence running to EOF, and ordinary comments protecting nothing.
- [x] `crates/vfmt/src/lint.rs` rewired; the boundary test matrix and every
CLI test pass unmodified.
- [x] `crates/vfmt_server/src/lint.rs`: `fixable` filters through the shared
answer; `fix_touches_fence` is the all-or-nothing rule.
- [x] Server tests: a fenced violation is reported but not fixable, a fence
holds in a file that does not parse, an unfenced file is unaffected;
no `quickfix` action on a fenced line while the neighbouring free line
still has one; `fixAll` leaves fenced bytes byte-identical.
- [x] e2e through both real binaries: the server's `fixAll` edit is
byte-identical to what `vfmt check --fix` writes for the same content,
with the CLI still exiting 1 for the finding it declined to fix.
- [x] `docs/features/server-lint/README.md` Handshake 3 annotated as
delivered.
- [ ] **Not done:** statement-level fences. `collect` is item-scoped by
design (format-fences), and the scan is line-based, so a fence inside a
statement body is protected only by the scan half. Unchanged by this
round, and filed where it belongs (format-fences).
- [ ] **Not done:** sharing the parse. `protected_regions` re-parses rather
than accepting a tree — see Assumptions; it is the same "one parse, two
tools" TODO (§4) the linter and the server already carry, and when that
lands this function is one of the call sites it simplifies.
## Work log
### 2026-08-19 — dev
- Read `CLAUDE.md`, `docs/features/{server-lint,linter-core,format-fences}/README.md`
in full (QA logs and Reviews included) before writing anything.
- **The API shape was the whole design decision.** Three candidates: pass the
caller's parsed tree (rejected — two callers, two trees, the same drift in a
new costume), return a filter closure over violations (rejected —
`vlog_formatter` would have to know `vlog_linter::Fix`, inverting a
dependency linter-core deliberately keeps out), or take `&str` and answer in
byte ranges (chosen — the tiniest surface that both front ends can share,
and `Region` was already the vocabulary). What is *not* shared is which
violations a tool offers, because that is genuinely each tool's own
question; what is shared is every byte of "what is fenced".
- The scan was **moved verbatim** from `crates/vfmt/src/lint.rs` into
`fence.rs` as `scanned_regions` (private; `protected_regions` is the only
way in), with `fence::fence_of` calls becoming bare `fence_of`. Same
pairing, same EOF rule, same `Region` construction. The CLI's
`touches_fence` body became `fence::is_protected` unchanged, including the
`end.max(start + 1)` insertion rule.
- **Byte-identity of the CLI filter** was the constraint, and it holds by
construction: `fixable_outside_fences` still computes `collect(tolerant) ∪
scan`, still short-circuits when the union is empty, and still filters on
the same predicate. Its four behavior tests — the boundary matrix, the
multi-edit fix, the fenced/unfenced pair and the fence-free file — pass
**unmodified**, as do all 48 CLI integration tests including
`check_reports_inside_a_fence_but_never_fixes_there` and
`a_fence_holds_even_in_a_file_that_does_not_parse`.
- Three unit tests in `crates/vfmt/src/lint.rs` did have to change, because
they called the private `scanned_fence_regions` that no longer lives there.
They were rewritten to assert the same three behaviors (broken-file
backstop, unclosed fence to EOF, ordinary comments) through
`fixable_outside_fences`, which is the CLI's own remaining seam; the
region-shape assertions they used to make now live in `fence.rs`, against
the code that produces them. No assertion was weakened: each still fails if
the scan stops finding its region.
- Server side is deliberately one filter in one place. `fixable` is the only
caller of the code-action path's `lint`, so filtering there covers quick
fixes and `fixAll` at once and cannot be forgotten by a future third action
kind. `violations` was left alone, on purpose and with a doc comment saying
why: the finding must still be published.
- The e2e test finds the `vfmt` binary by path next to `CARGO_BIN_EXE_vfmt-server`
(Cargo names no env var for another package's binary) and **skips with a
printed note** if it is absent, which can only happen under
`cargo test -p vfmt_server` in a tree where `vfmt` was never built. Under
the `--workspace` gate it always runs. A test that fails for a reason that
is not about the code under test is worse than one that says it skipped.
- Did not touch `verify.rs`, `format.rs`, any `.cases` file, `vlog_parser`,
`vlog_linter`, `vlog_semantic`, `vfmt_core` or `editors/**`. No new
dependency, no `Cargo.toml` edit, no `#[allow]`, no `unwrap`/`expect`/
`panic!`/`unsafe` outside `#[cfg(test)]`. Did not run `git commit`/`git push`.
- **Concurrency note.** Another agent was live in `crates/vlog_parser` (the
directives-in-instances round) for part of this session; the workspace did
not compile for a stretch, exactly as the previous round recorded. Nothing
was touched in response; the gates below were run once `vlog_parser` built
again. `cargo fmt` was scoped to `-p vlog_formatter -p vfmt -p vfmt_server`
rather than `--all` for the same reason. That round's `format.rs` had landed
in the tree by then; `git diff` on it shows four hunks, every one of them
their own semantic edit and none a whitespace-only reflow, so the
package-scoped `fmt` left their work as they wrote it.
**Results.**
- `cargo test --workspace`: **574 passed, 0 failed**, up from **563** at the
session's start commit `6e6aacb`. The +11 are all this round's: 5 in
`vlog_formatter`'s `fence.rs`, 3 in `vfmt_server`'s `lint.rs`, 2 in its
`code_action.rs`, 1 e2e. `crates/vfmt` is net 0 — three scan tests became
three filter tests.
- `cargo clippy --workspace --all-targets`: **silent** (re-run after touching
every file this round changed, to rule out a cached result).
- `cargo fmt -p vlog_formatter -p vfmt -p vfmt_server -- --check`: clean.
`--all` was deliberately **not** used: `crates/vlog_parser` belongs to the
concurrent round and is not this round's to reformat.
**Byte-identity of the CLI, measured rather than argued.** Two `git worktree`
builds — `old` at `6e6aacb`, `new` at `6e6aacb` + this round's diff to
`fence.rs` and `crates/vfmt/src/lint.rs` and nothing else, so the concurrent
round's uncommitted parser work perturbs neither:
- `vfmt check corpus/ --output-format json`: **byte-identical** (2 407 345
bytes of JSON), stderr byte-identical, both exit 1.
- 22 crafted fence shapes (simple, unclosed, broken-parse-before-the-fence,
long spelling, `off-by-one`, block comment, indented fence, trailing fence,
two `off`s, stray `on`, fence at EOF, generate scope, top-level, multi-byte,
CRLF, trailing-whitespace-only, a fence spelled inside a string, two
regions, an all-garbage file, a package, a waiver inside a fence, and a
file with no fence at all), each in two identical directories run through
`check --fix`: **every fixed file byte-identical**, stdout identical, stderr
identical (`found 19 violations, fixed 28 violations` from both), exit 1
from both.
- `tools/corpus_check.sh` with each binary: **md5
`31ffdb18c96d4e79057178f7de269756` from both** — exactly the value this
round's brief named as the expected one, reproduced with the debug and the
release build of the baseline alike.
**One finding that is not this round's to fix**: the checked-in
`corpus-check-results.tsv` is md5 `6af28a6d4942c4ddce0a061262eb5d68`, which is
**not** what the binary at `6e6aacb` produces (456 differing rows, and it
carries a `verification-error` row for `common_cells/src/cdc_4phase.sv` that
`6e6aacb` does not reproduce — that binary reports the file as
`would-reformat`). The committed file appears to predate several rounds
rather than to describe HEAD. Left untouched: regenerating it is out of this
round's scope and the working tree currently holds another agent's
in-progress parser and formatter changes, so a regeneration here would record
their round, not this one.
## QA log
### 2026-08-19 — QA
Read `CLAUDE.md`, this feature's README (dev's Work log included), and the
diff to `fence.rs`, `crates/vfmt/src/lint.rs`, `crates/vfmt_server/src/lint.rs`,
`code_action.rs`, `tests/e2e.rs`, and `server-lint`'s annotations, before
touching anything. Scoped to `-p vlog_formatter -p vfmt -p vfmt_server`
throughout, per the concurrency note (`vlog_parser`/`format.rs`/`.cases` were
live under another agent for part of this session).
**Gates.** `cargo test -p vlog_formatter -p vfmt -p vfmt_server`: all 11 test
binaries green (vfmt-server unittests 109, `cli.rs` 48, `e2e.rs` 5,
`vlog_formatter` unittests 13, its `verification.rs` 63, `fences.rs` 6, etc.)
— **0 failures**. `crates/vfmt/tests/cli.rs` has an **empty `git diff`**,
i.e. the 48 CLI tests are not merely passing, they are byte-for-byte
unmodified, confirming the README's claim directly rather than by count.
`cargo clippy -p vlog_formatter -p vfmt -p vfmt_server --all-targets`:
silent. `cargo fmt -p vlog_formatter -p vfmt -p vfmt_server -- --check`: clean
at the time of this check. Note: mid-session it briefly reported diffs, all
three confined to `crates/vlog_formatter/tests/verification.rs` lines
600-679 — `git diff` on that file attributes those lines to the concurrent
directives-in-instances round (new tests added there), not to this diff; the
five files this feature actually touches (`fence.rs`,
`vfmt/src/lint.rs`, `vfmt_server/src/lint.rs`, `code_action.rs`, `e2e.rs`)
were independently checked with `rustfmt --check` and are clean on their own,
and the workspace-wide check is clean again as of this writing (the other
agent evidently ran its own `cargo fmt` since). No `#[allow]`, `unwrap`/
`expect`/`panic!`/`unsafe` in library code — every instance in the diff is
inside `#[test]`/`mod tests`. Cargo.toml/Cargo.lock: no diff from this
feature (nor is there a stray one at the repo root — that's an unrelated,
already-committed state).
**Claim 1 (ownership moved, not copied).** `grep -rn scanned_fence_regions
crates/` returns nothing anywhere in the tree; `scanned_regions` exists only
in `fence.rs` (private, called only from `protected_regions`). `git diff` on
`fence.rs` is **pure addition** (`git diff | grep '^-' ` — excluding `---`
headers — is empty): `collect`, `fence_of`, `region_at` are untouched.
Confirmed.
**Claim 2 (CLI byte-identity).** Built two release binaries in isolated
`git worktree`s: `old` at `6e6aacb`, `new` at `6e6aacb` plus only this
feature's diff to `fence.rs` and `crates/vfmt/src/lint.rs` (copied the two
files directly; `git diff --stat` in that worktree confirmed exactly those
two files, 171 lines, matching the dev's own isolation). Ran 8 crafted fence
shapes (simple, unclosed-to-EOF, broken-parse-before-the-fence/scan-backstop,
block-comment spelling, indented, double-off/stray-on, fence-inside-a-
string-literal, CRLF) through `check --fix` on both binaries: **every fixed
file byte-identical** (`cmp` clean on all 8), stdout identical
(`found 15 violations, fixed 8 violations` from both), exit 1 from both.
This is a smaller sample than the dev's 22-shape run but corroborates it
independently rather than repeating it. The 3 rewritten unit tests in
`crates/vfmt/src/lint.rs` were read: they now call `fixable_outside_fences`
end-to-end with a `no-tabs`-shaped violation instead of asserting on
`scanned_fence_regions`'s return shape directly, but assert the same three
behaviors (broken-file backstop, unclosed-to-EOF, ordinary-comment-is-not-
a-fence) — confirmed by reading, and by the sabotage below, which fails two
of exactly these three.
**Claim 3 (server drops fenced fixes, diagnostics untouched).** Drove the
real `vfmt-server` debug binary live over hand-framed LSP JSON-RPC (Python,
not the Rust `talk()` helper, so this is independent of the e2e test's own
plumbing):
- Fenced tab: diagnostic published at both the fenced and unfenced lines;
`codeAction` at the fenced line → `[]`; at the unfenced line → one
`quickfix` action with the expected edit. Matches Handshake 3 exactly.
- `fixAll`: `\twire a;` (fenced) survives byte-for-byte in the returned
`newText`; `\twire b;` (unfenced) becomes ` wire b;`.
- Non-parsing buffer (`@@@ junk;` before the fence, a real parse error):
diagnostics still published (including the fenced tab's `no-tabs`), and
`codeAction` at the fenced tab still returns `[]` — the scan backstop
holds through the server's path too, not just the CLI's.
- Fence + waiver: `// vfmt: waive no-tabs` on the line before a fenced,
tabbed `wire a;` → **zero diagnostics for that violation** (not
"reported but unfixable" — genuinely absent), while the unfenced tab two
lines later is still reported. This is correct and is not a fence
property: waivers drop the violation in `vlog_linter` before either
front end's fence filter ever runs, so the fence has nothing left to
decline. Confirms the Assumptions section's claim that fences and
waivers are orthogonal mechanisms, live.
**Claim 4 (gates, drift).** Addressed under Gates above. `cargo tree -p
vlog_linter` still shows only `vlog_parser`; its `Cargo.toml` still lists
only that one path dependency — the "vlog_linter still has no notion of
fences" handshake holds structurally, not just by inspection.
**Claim 5 (stale corpus-check-results.tsv).** Confirmed exactly. The
committed file's md5 is `6af28a6d4942c4ddce0a061262eb5d68`. Regenerated it
fresh with the `old` (`6e6aacb`) worktree's release binary via
`tools/corpus_check.sh`: got `31ffdb18c96d4e79057178f7de269756` — the value
the dev's brief and work log both cite as expected, reproduced independently.
Row-level diff (`diff <(sort ...) <(sort ...) | grep -c '^[<>]'`) is 454
changed lines against the committed file (dev's log says 456; close enough
to be the same finding under a slightly different counting method, not a
discrepancy worth chasing). Spot-checked the specific example the dev
named: the committed file has a `verification-error` row for
`common_cells/src/cdc_4phase.sv`; the freshly generated one has
`would-reformat` for the same file, matching the dev's description exactly.
Left the committed file untouched, as instructed — this is filed for the
lead, not fixed here.
**Attacks on the shared API** (standalone Rust harness in scratch, linking
`vlog_formatter`/`vlog_parser` as path deps, so as not to touch any crate
under test):
- `protected_regions("")` → 0 regions.
- Fence spelled inside a string literal (`string s = "// vfmt: off";`) → 0
regions — correct, the line as a whole does not start with `//` after
trimming, so `fence_of` never fires on it.
- Block-comment spelling (`/* verilog_format: off */`) → 0 regions —
correct, same reason (`fence_of` requires a `//`-prefixed, single-line
comment).
- CRLF: found exactly 1 region, with the fenced tab protected and the
unfenced one (past the `on`) not — the `\r` is absorbed into
`LineIndex`'s line ranges rather than desyncing the pairing.
- Unclosed `off` at EOF: 1 region running to `src.len()`.
- `off`/`on` in an all-garbage file (no valid tokens at all): 1 region
found — the scan backstop needs no successful parse whatsoever, only
`LineIndex`, which never fails.
- Double `off` (second one while one is already open) then a stray `on`
before the pair, then a closing `on`: 1 region, spanning from the first
`off` to the first matching `on` — the second `off` is swallowed as
"just text" per the `_ => {}` arm, which is the documented crude-but-safe
behavior (protects more, never less).
- 1 MB file, 1000 fence pairs: `protected_regions` ~68ms (parser-dominated,
a tolerant parse of a 1MB file), `is_protected` linear scan over the
resulting ~1000 regions ~6.6µs per call across 1000 calls — sane,
informational only, no regression risk flagged.
- `is_protected` boundary arithmetic against a synthetic `10..20` region:
reproduced the exact table in `fence.rs`'s own
`protection_is_decided_exactly_at_the_region_boundaries` test
independently (first/last byte inside, adjacent-outside both ends,
straddling both edges, insertion inside, insertion at the start boundary
— protected, per the `end.max(start+1)` rule — insertion just past the
end — not protected). Both front ends call `fence::is_protected` with
identical argument shape (`(range.start as usize, range.end as usize)` in
both `vfmt/src/lint.rs::touches_fence` and
`vfmt_server/src/lint.rs::fix_touches_fence`), so "both front ends refuse
identically" is a structural guarantee, not merely an observed one —
there is no live rule today that emits a pure-insertion fix to exercise
this end-to-end (`no-tabs` and `no-trailing-whitespace` both replace
non-empty ranges), so the unit-level equivalence is the strongest
available evidence.
**Sabotage.** Edited `protected_regions` in the working tree to drop the
`regions.extend(scanned_regions(src))` line (tree-only). Result:
`crates/vfmt/src/lint.rs` unit tests — 3 failures (`the_line_scan_backstops_
a_file_that_does_not_parse`, `an_unclosed_fence_runs_to_the_end_of_the_file`,
`fixes_outside_a_fence_survive_the_filter`); `crates/vfmt`'s own CLI
integration test `a_fence_holds_even_in_a_file_that_does_not_parse` —
failed; `vfmt_server`'s `lint::tests::a_fence_holds_even_when_the_file_
does_not_parse` — failed; `vlog_formatter`'s own
`the_line_scan_backstops_a_file_that_does_not_parse` — failed, as expected.
Reverted by hand (restored the two-line body exactly); `git diff` on
`fence.rs` afterward is byte-identical to the pre-sabotage diff (same
`index a7bf341..5edc8c3` hashes), and the full scoped suite is green again.
The non-parsing-buffer backstop is real and load-bearing in **both** front
ends, not just asserted to be.
**One incidental finding — not blocking, worth a look.** `fence.rs`'s own
new unit test `a_fence_in_a_good_tree_protects_its_whole_region` is named
and commented as exercising the tree path (`collect`) on "a fence in a good
tree," but its source — `\ta = 1;` as a bare module item — is not
actually valid Verilog at item position (needs `assign` or a procedural
block); `parse_source_tolerant` reports 2 errors on it and `collect` alone
returns **0 regions** for it (checked directly, bypassing `protected_
regions`). The test only passes today because of the scan half it claims
not to be testing — which is exactly why it failed under the sabotage above
alongside the tests that are honestly about the scan. This is not a
production bug: the tree path is genuinely exercised elsewhere
(`crates/vlog_formatter/tests/fences.rs`, unchanged by this round, uses
real `wire` declarations and passes `collect` alone). It is a test-fidelity
gap in the new suite: nothing in `fence.rs`'s own tests currently proves
`protected_regions` finds a region via `collect` on a *genuinely* clean
tree, independent of the scan. Left as-is per "QA verifies, doesn't
redesign" — flagging here rather than editing the test file, which is
outside this round's QA-log-only write scope.
**Verdict: PASS on all 5 claims**, no BLOCKING findings. Server never edits
a fenced byte on either the quickfix or fixAll path (live-verified, not just
unit-tested); CLI behavior is unchanged (spot-verified independently via
isolated worktrees, 8/8 shapes byte-identical, 48/48 tests untouched); the
scan backstop is genuinely load-bearing on both front ends (sabotage
confirmed); no third copy of fence knowledge exists; the stale-corpus-tsv
claim is accurate and correctly left unfixed. The one finding above (test
naming/coverage gap in `fence.rs`) is cosmetic — informational for the lead,
not a correctness issue.
## Review
**2026-08-19 — lead. Verdict: accepted; commits with round 15. The fence
promise now holds identically across all three surfaces: the formatter,
CLI fixes, and editor fixes.**
Points reviewed and accepted:
1. **Moved, not copied — and proven.** `grep` finds one owner of the
scan; the CLI's behavior was shown byte-identical via isolated-diff
worktrees (8 fence shapes, identical fixed files/stdout/exit), and
the 48 CLI tests are diff-empty, not merely green. "One definition
of what is fenced" was the round's whole point and it is now
structurally true.
2. **`protected_regions` parsing internally** is the right signature
for exactly the stated reason: letting callers pass their own trees
is how two front ends get two answers. The ~2-line per-front-end
"which violations does this tool offer" residue is the correct
remainder.
3. **The sabotage evidence is the strongest yet**: removing the scan
union failed six tests across three crates — the backstop is
load-bearing everywhere it's claimed to be.
4. **Waiver/fence orthogonality confirmed live** (a waived violation
inside a fence produces zero diagnostics — waivers act first), which
is the composition question nobody had asked yet.
Lead fix on acceptance (QA's non-blocking find): the good-tree test's
fenced content didn't parse at item position, so it exercised only the
scan half it claimed not to test. Rewritten with valid items plus
explicit assertions that the tree is clean AND `collect` itself finds
the region — the tree path of `protected_regions` is now genuinely
pinned in fence.rs.
The stale committed corpus-check-results.tsv both this round's agents
flagged is removed from tracking in this commit (generated artifact,
already gitignored; staleness confirmed by two independent QAs).