Add directives-in-lists: ifdef/define/`include between list elements

Roadmap item 6: conditional-compilation directives are now accepted
between elements of port lists, parameter-port lists and enum member
lists, carried as parallel ListDirective vectors (source order via a
before-index; additive AST so vlog_semantic and vlog_linter compile
unmodified) and emitted verbatim. Commas are STORED, never derived:
two real corpus shapes (comma inside the `ifdef arm; no comma at all
in `else alternatives) kill any derivation rule in opposite
directions. A comma printed on a directive's line would be swallowed
into the condition on re-parse -- prevented by a forced break,
sabotage-verified against the safety net.

Corpus: parse-error 352 -> 350 (ibex_core.sv formats), six more
files advance to later blockers -- picorv32.v parses 1986 lines
further but still refuses on restrict property (item 7). The real
payoff is the workspace index: picorv32/_axi/_wb now index
(530 modules, 9174 members), cross-file external resolution
87.0% -> 93.6% on clean files, unresolved externals 2.6% -> 1.3%.
0 verification errors, 0 crashes, verify.rs byte-identical.

563 workspace tests (20 new cases, 9 verification, 7 parser units).
Dev: Opus agent; QA: Sonnet agent (both semantic baselines
reproduced from a detached worktree); review in
docs/features/directives-in-lists/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 11:31:14 -07:00
1 parent 2ba995d1c9
commit 6e6aacb392
9 files changed
+1441 -45

No files matched your search

+18 -2
View File
@@ -250,6 +250,14 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
function and task bodies. The invocation is passed through verbatim (a
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`
Not yet supported (parse errors). Roadmap ordered by measured impact on
real RTL — see `docs/features/corpus-check/README.md` for the 820-file
@@ -265,8 +273,16 @@ corpus baseline this ordering comes from:
4. Dynamic arrays and queues
5. Declarations with identifier (typedef'd) types in some positions
(`my_t [N-1:0] x;`)
6. `` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum
list (they are accepted at item and statement position already)
6. ~~`` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum
list~~ — **done**; see `docs/features/directives-in-lists/README.md`.
Two corpus files unblocked and six advanced to their next blocker
(`picorv32.v` itself now parses 1986 lines further but still does not
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)
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
+8
View File
@@ -334,6 +334,14 @@ later:
external rate from 19.6 % to 2.6 % of all references. Duplicate-name
policy, `` `define`` lookup (no include graph → no resolution order) and
the honest gaps in `docs/features/workspace-index/README.md`.
→ The index's biggest named gap has since closed: accepting `` `ifdef``
inside a port/parameter/enum list (README roadmap item 6,
`docs/features/directives-in-lists/README.md`) means `picorv32`,
`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.
- [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`),
+90 -19
View File
@@ -120,6 +120,16 @@ struct ListItem {
/// Comments written between the element and the separator that follows.
before_sep: Vec<Comment>,
trailing: Option<Comment>,
/// Whether a `,` follows this entry. `None` means "decide from the
/// position" — the last entry of the list gets none — which is right for
/// every list that cannot hold a compiler directive. The three that can
/// (a header's parameter ports and ports, an enum's members) set it from
/// the source, because a directive between two elements can move the
/// comma to the other side of it.
comma: Option<bool>,
/// True for a `` `ifdef``-style entry. A directive runs to end of line,
/// so whatever follows it — a comma included — starts a new line.
directive: bool,
}
impl ListItem {
@@ -129,8 +139,17 @@ impl ListItem {
doc,
before_sep: meta.before_sep.clone(),
trailing: meta.trailing.clone(),
comma: None,
directive: false,
}
}
/// Record the `,` the source wrote after this element, instead of letting
/// the list derive one from the element's position.
fn with_comma(mut self, comma: bool) -> Self {
self.comma = Some(comma);
self
}
}
impl<'a> Fmt<'a> {
@@ -406,8 +425,10 @@ impl<'a> Fmt<'a> {
// Comments written before the separator print on this element's
// side of it, which is where the source put them.
let has_before_sep = !item.before_sep.is_empty();
let ends_line = self.inline_comments(&item.before_sep, &mut inner);
if i < last {
// A directive swallows the rest of its line, so its comma — and
// any comment written before that comma — must start a new one.
let ends_line = self.inline_comments(&item.before_sep, &mut inner) || item.directive;
if item.comma.unwrap_or(i < last) {
if ends_line {
inner.push(Doc::HardLine);
}
@@ -440,6 +461,48 @@ impl<'a> Fmt<'a> {
group(docs)
}
/// Put a list's elements and the `` `ifdef``-style directives written
/// between them back into source order.
///
/// A directive is an entry like any other except that it never takes a
/// comma of its own unless the source wrote one after it, and that it
/// forces the list open: `delimited_dangling`'s `force_break` must be set
/// whenever the result holds one, or the printer could put the next entry
/// on the directive's line, where the lexer would swallow it.
fn list_entries(&self, elements: Vec<ListItem>, directives: &[ListDirective]) -> Vec<ListItem> {
if directives.is_empty() {
return elements;
}
let mut out = Vec::with_capacity(elements.len() + directives.len());
let mut pending = directives.iter().peekable();
for (i, element) in elements.into_iter().enumerate() {
while let Some(d) = pending.next_if(|d| d.before <= i) {
out.push(self.directive_entry(d));
}
out.push(element);
}
for d in pending {
out.push(self.directive_entry(d));
}
out
}
/// One directive standing between list elements, verbatim.
///
/// 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.
fn directive_entry(&self, d: &ListDirective) -> ListItem {
ListItem {
leading: d.meta.leading.clone(),
doc: self.raw_text(&d.raw),
before_sep: d.meta.trailing.clone().into_iter().collect(),
trailing: None,
comma: Some(d.comma),
directive: true,
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -642,38 +705,44 @@ impl<'a> Fmt<'a> {
// A written-but-empty `#()` is printed back; a missing one stays
// missing.
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> =
params.iter().map(|p| ListItem::from_meta(&p.meta, self.param_port(p))).collect();
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", false));
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken));
on_fresh_line = false;
}
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
// A port list whose every element sits in an `ifdef arm still holds
// directives while being `PortList::Empty`, so the two are laid out by
// the same code.
let broken = !m.port_directives.is_empty();
match &m.ports {
PortList::None => docs.push(text(";")),
PortList::Empty => {
if !on_fresh_line {
docs.push(text(" "));
}
docs.push(self.delimited_dangling("(", Vec::new(), &m.port_dangling, ")", false));
docs.push(text(";"));
}
PortList::Ansi(_) | PortList::NonAnsi(_) => {
PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => {
let items: Vec<ListItem> = match &m.ports {
PortList::Ansi(ports) => ports
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.ansi_port(p)))
.map(|p| {
ListItem::from_meta(&p.meta, self.ansi_port(p)).with_comma(p.comma)
})
.collect(),
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| ListItem::from_meta(&p.meta, text(p.name.clone())))
.map(|p| {
ListItem::from_meta(&p.meta, text(p.name.clone())).with_comma(p.comma)
})
.collect(),
_ => unreachable!(),
_ => Vec::new(),
};
let items = self.list_entries(items, &m.port_directives);
if !on_fresh_line {
docs.push(text(" "));
}
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", false));
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken));
docs.push(text(";"));
}
}
@@ -962,13 +1031,15 @@ impl<'a> Fmt<'a> {
d.push(text(" = "));
d.push(self.expr(v));
}
ListItem::from_meta(&m.meta, concat(d))
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
})
.collect();
let items = self.list_entries(items, &e.directives);
// `e.dangling` — comments written before the closing `}` —
// is printed inside the braces; the enum has no other place
// to put it, and dropping it loses a comment.
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", false));
let broken = !e.directives.is_empty();
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken));
docs.push(text(format!(" {};", t.name)));
concat(docs)
}
@@ -0,0 +1,366 @@
# `ifdef around one port in the middle of the list
module m (
input a,
`ifdef X
input b,
`endif
input c
);
endmodule
----
module m (
input a,
`ifdef X
input b,
`endif
input c
);
endmodule
====
# `ifdef around the trailing ports: the comma before it stays put
module m (
input a,
`ifdef X
input b,
input c
`endif
);
endmodule
----
module m (
input a,
`ifdef X
input b,
input c
`endif
);
endmodule
====
# `ifdef around the first port
module m (
`ifdef X
input a,
`endif
input b
);
endmodule
----
module m (
`ifdef X
input a,
`endif
input b
);
endmodule
====
# `else arm: neither arm's last port writes a comma
module m (
`ifdef X
input a
`else
input b
`endif
);
endmodule
----
module m (
`ifdef X
input a
`else
input b
`endif
);
endmodule
====
# `elsif chain in a parameter port list
module m #(
`ifdef A
parameter int W = 1,
`elsif B
parameter int W = 2,
`else
parameter int W = 3,
`endif
parameter int D = 4
) ();
endmodule
----
module m #(
`ifdef A
parameter int W = 1,
`elsif B
parameter int W = 2,
`else
parameter int W = 3,
`endif
parameter int D = 4
) ();
endmodule
====
# `ifndef
module m (
`ifndef SYNTHESIS
input dbg,
`endif
input clk
);
endmodule
----
module m (
`ifndef SYNTHESIS
input dbg,
`endif
input clk
);
endmodule
====
# `define inside a parameter port list
module m #(
`define W 8
parameter int P = `W
) ();
endmodule
----
module m #(
`define W 8
parameter int P = `W
) ();
endmodule
====
# `include inside a parameter port list
module m #(
`include "params.svh"
parameter int P = 1
) ();
endmodule
----
module m #(
`include "params.svh"
parameter int P = 1
) ();
endmodule
====
# `include between enum members
typedef enum logic [7:0] {
A,
B,
// custom instructions
`include "more.svh"
LAST
} e_t;
----
typedef enum logic [7:0] {
A,
B,
// custom instructions
`include "more.svh"
LAST
} e_t;
====
# enum members under `ifdef/`else
typedef enum logic {
`ifdef X
A
`else
B
`endif
} e_t;
----
typedef enum logic {
`ifdef X
A
`else
B
`endif
} e_t;
====
# nested `ifdef in a port list
module m (
input a,
`ifdef X
`ifdef Y
input b,
`endif
input c,
`endif
input d
);
endmodule
----
module m (
input a,
`ifdef X
`ifdef Y
input b,
`endif
input c,
`endif
input d
);
endmodule
====
# the comma written after the directive, not before it
module m #(
parameter int A = 1
`ifdef SIM
,
parameter string B = ""
`endif
) ();
endmodule
----
module m #(
parameter int A = 1
`ifdef SIM
,
parameter string B = ""
`endif
) ();
endmodule
====
# non-ANSI port list with a conditional port
module m (a,
`ifdef X
b,
`endif
c);
endmodule
----
module m (
a,
`ifdef X
b,
`endif
c
);
endmodule
====
# a port list that is one `ifdef arm and nothing else
module m (
`ifdef VERILATOR
input clk
`endif
);
endmodule
----
module m (
`ifdef VERILATOR
input clk
`endif
);
endmodule
====
# comments before and after a list directive
module m (
input a,
// conditional from here
`ifdef X // only when X
input b
`endif
);
endmodule
----
module m (
input a,
// conditional from here
`ifdef X // only when X
input b
`endif
);
endmodule
====
# a macro invocation standing between enum members
typedef enum logic [7:0] {
A,
B,
`VECTOR_INCLUDE("more.sv")
LAST
} e_t;
----
typedef enum logic [7:0] {
A,
B,
`VECTOR_INCLUDE("more.sv")
LAST
} e_t;
====
# a `define with a line continuation inside a parameter port list
module m #(
`define TWO_LINES a \
b
parameter int P = 1
) ();
endmodule
----
module m #(
`define TWO_LINES a \
b
parameter int P = 1
) ();
endmodule
====
# a header that would otherwise fit on one line is broken by its directive
module m (input a,
`ifdef X
input b
`endif
);
endmodule
----
module m (
input a,
`ifdef X
input b
`endif
);
endmodule
====
# blank lines around a list directive are dropped like any other
module m (
input a,
`ifdef X
input b,
`endif
input c
);
endmodule
----
module m (
input a,
`ifdef X
input b,
`endif
input c
);
endmodule
====
# directive in a parameter list and in the port list of one header
module m #(
`ifdef X
parameter int P = 1,
`endif
parameter int Q = 2
) (
`ifdef Y
input a,
`endif
input b
);
endmodule
----
module m #(
`ifdef X
parameter int P = 1,
`endif
parameter int Q = 2
) (
`ifdef Y
input a,
`endif
input b
);
endmodule
@@ -512,3 +512,91 @@ fn a_dropped_instance_name_comment_is_still_rejected() {
let output = "module m;\n sub #(.W(1)) u (.a(b));\nendmodule\n";
expect_divergence(input, output);
}
// ---------------------------------------------------------------------------
// `ifdef and friends between list elements (docs/features/directives-in-lists)
//
// This feature added no normalization — `verify.rs` is byte-identical to the
// commit before it — so hard invariant #4 does not bind. The tests below exist
// anyway, one per corruption the new list plumbing could plausibly produce, so
// that any future widening of the net has to survive them first.
// ---------------------------------------------------------------------------
#[test]
fn a_comma_swallowed_into_a_list_directive_is_rejected() {
// The sharpest hazard in this feature: a directive runs to end of line, so
// printing its comma on the *same* line fuses the two into one token. The
// formatter puts the comma on a fresh line; this pins what happens if it
// ever stops.
let input = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let output = "module m #(\n parameter int A = 1\n `ifdef S,\n parameter int B = 2\n `endif\n) ();\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_moved_across_a_list_directive_is_rejected() {
// Deriving each element's comma from its index instead of from the source
// produces exactly this: the comma hops to the other side of the `ifdef.
let input = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let output = "module m #(\n parameter int A = 1,\n `ifdef S\n parameter int B = 2\n `endif\n) ();\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_invented_between_two_ifdef_arms_is_rejected() {
// `ifdef X a `else b `endif — neither arm writes a comma, and a list that
// commas every element but the last would add one after `a`.
let input = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let output =
"module m (\n `ifdef X\n input a,\n `else\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_dropped_before_a_list_directive_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_list_directive_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n input b\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_list_directive_printed_out_of_order_is_rejected() {
// `before` is what puts the directives back among the elements; an
// off-by-one there emits `endif before the port it was written after.
let input = "module m (\n input a,\n`ifdef X\n input b,\n`endif\n input c\n);\nendmodule\n";
let output =
"module m (\n input a,\n `ifdef X\n `endif\n input b,\n input c\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_changed_list_directive_condition_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n `ifdef Y\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_on_a_list_directive_is_rejected() {
// The directive's own `Meta` is new plumbing, so it gets the same
// dropped-comment guard the bracket buckets have (hard invariant #3).
let input = "module m (\n input a,\n // only when X\n`ifdef X // why\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_list_directive_may_still_be_reindented() {
// The other direction: moving the directive to the list's indent level is
// what the formatter legitimately does, and must stay accepted.
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
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");
}
+51
View File
@@ -80,6 +80,35 @@ pub struct RawText {
pub span: TextRange,
}
/// 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.
///
/// 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
/// `vlog_linter`, and a directive is not a port. `before` is what puts the
/// two back into source order. vfmt does not evaluate the condition — both
/// arms' elements are ordinary elements of the one list, exactly as an
/// `` `ifdef`` at item position already works.
#[derive(Debug)]
pub struct ListDirective {
/// The directive line, verbatim.
pub raw: RawText,
/// Comments written before the directive (`leading`) and the one written
/// after it on the same line (`trailing`).
pub meta: Meta,
/// Index of the element this directive was written before;
/// `elements.len()` when it stands after the last one. Several directives
/// at the same index keep their source order in the vector.
pub before: usize,
/// True when the `,` separating the surrounding elements was written
/// *after* this directive (`` `ifdef X`` ⏎ `, parameter string P = ""`),
/// which is how a conditional list tail stays legal in both arms.
pub comma: bool,
}
/// A macro invocation standing where a module item or a statement belongs
/// (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) ``). Its arguments are token soup
/// handed to a preprocessor we do not run, so the whole invocation is kept as
@@ -181,12 +210,18 @@ pub struct Module {
/// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a
/// written-but-empty `#()`, which must be printed back.
pub param_ports: Option<Vec<ParamPort>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before the `)`.
pub param_dangling: Vec<Comment>,
/// Comments written between whatever precedes the port list and its `(`.
/// Empty when the header wrote no parenthesized port list.
pub port_comments: Vec<Comment>,
pub ports: PortList,
/// Directives written between the header's ports, in source order. They
/// live here rather than inside [`PortList`] because a list whose every
/// element sits in an `` `ifdef`` arm is still a [`PortList::Empty`].
pub port_directives: Vec<ListDirective>,
/// Comments written after the last port and before the `)`.
pub port_dangling: Vec<Comment>,
pub items: Vec<Item>,
@@ -224,6 +259,11 @@ pub enum PortList {
pub struct NonAnsiPort {
pub meta: Meta,
pub name: String,
/// True when a `,` followed this element in the source. See
/// [`ListDirective::comma`]: a directive between two elements can move
/// the comma to the other side of it, so the formatter reproduces the
/// placement it parsed rather than deriving it from the element's index.
pub comma: bool,
/// Code extent of the port name.
pub span: TextRange,
}
@@ -239,6 +279,9 @@ pub struct AnsiPort {
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
pub default: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the port declaration.
pub span: TextRange,
}
@@ -255,6 +298,9 @@ pub struct ParamPort {
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
pub default: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the parameter port.
pub span: TextRange,
}
@@ -303,6 +349,8 @@ pub enum TypedefKind {
pub struct EnumType {
pub base: Option<DataType>,
pub members: Vec<EnumMember>,
/// Directives written between the members, in source order.
pub directives: Vec<ListDirective>,
pub dangling: Vec<Comment>,
}
@@ -313,6 +361,9 @@ pub struct EnumMember {
/// Byte range of `name`.
pub name_span: TextRange,
pub value: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the member.
pub span: TextRange,
}
+198 -24
View File
@@ -139,6 +139,16 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
pub const MAX_CHAIN_LENGTH: u32 = 256;
/// What [`Parser::take_list_directives`] found between two list elements.
#[derive(Default)]
struct Harvested {
/// At least one directive stood here.
any: bool,
/// One of them carried the `,` that separates the surrounding elements,
/// so the list continues even though the previous element wrote no comma.
carried_comma: bool,
}
pub struct Parser<'a> {
tokens: Vec<Token>,
pos: usize,
@@ -600,6 +610,31 @@ impl<'a> Parser<'a> {
self.take_dangling()
}
/// Consume the compiler directives — and the standalone macro invocations
/// [`Parser::at_macro_item`] recognizes — standing where a list element
/// would start, recording each one's place in the list and the `,` (if
/// any) written after it.
///
/// `before` is the number of elements parsed so far, which is the index
/// of the element the directives precede.
///
/// A directive runs to end of line, so it can only ever stand *between*
/// elements; one written inside an element is left where it is and
/// becomes an ordinary parse error, as it always was.
fn take_list_directives(&mut self, out: &mut Vec<ListDirective>, before: usize) -> Harvested {
let mut found = Harvested::default();
while self.cur().kind == TokenKind::Directive || self.at_macro_item() {
let mut meta = self.take_meta();
let raw = self.take_raw_text();
meta.trailing = self.take_trailing();
let comma = self.eat_sym(",");
found.any = true;
found.carried_comma |= comma;
out.push(ListDirective { raw, meta, before, comma });
}
found
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
/// ...) — they belong inside the enclosing construct.
fn take_dangling(&mut self) -> Vec<Comment> {
@@ -992,25 +1027,35 @@ impl<'a> Parser<'a> {
}
let param_comments = self.take_before_open("#");
let mut param_ports = None;
let mut param_directives = Vec::new();
let mut param_dangling = 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_param_port()?);
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());
// Without a comma and without a directive the list is
// over. With one, only the closing bracket says so: an
// `` `ifdef`` arm may end without a comma and another arm
// may still follow (`` `else``), or the arm may have been
// the tail of the list.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
param_dangling = self.take_dangling();
@@ -1018,7 +1063,7 @@ impl<'a> Parser<'a> {
param_ports = Some(list);
}
let port_comments = self.take_before_open("(");
let (ports, port_dangling) = self.parse_port_list()?;
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end("endmodule") {
@@ -1034,9 +1079,11 @@ impl<'a> Parser<'a> {
imports,
param_comments,
param_ports,
param_directives,
param_dangling,
port_comments,
ports,
port_directives,
port_dangling,
items,
dangling,
@@ -1067,6 +1114,7 @@ impl<'a> Parser<'a> {
name_span,
unpacked: Vec::new(),
default,
comma: false,
span,
});
}
@@ -1076,20 +1124,37 @@ impl<'a> Parser<'a> {
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(ParamPort { meta, kw, ty, is_type: false, name, name_span, unpacked, default, span })
Ok(ParamPort {
meta,
kw,
ty,
is_type: false,
name,
name_span,
unpacked,
default,
comma: false,
span,
})
}
/// The header port list plus the comments written before its closing `)`.
fn parse_port_list(&mut self) -> PResult<(PortList, Vec<Comment>)> {
/// The header port list, the comments written before its closing `)`, and
/// the directives written between its ports.
fn parse_port_list(&mut self) -> PResult<(PortList, Vec<Comment>, Vec<ListDirective>)> {
if !self.cur().is_sym("(") {
return Ok((PortList::None, Vec::new()));
return Ok((PortList::None, Vec::new(), Vec::new()));
}
self.bump();
// Directives before the first port. Harvested here rather than in the
// loop below because both the ANSI/non-ANSI decision and the
// written-but-empty check read the token after them.
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
if self.cur().is_sym(")") {
// `module m (/* c */);` — the comments stay between the parens.
let dangling = self.take_dangling();
self.bump();
return Ok((PortList::Empty, dangling));
return Ok((PortList::Empty, dangling, directives));
}
let ansi = {
let t = self.cur();
@@ -1107,14 +1172,17 @@ impl<'a> Parser<'a> {
if let Some(last) = ports.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
let comma = self.eat_sym(",");
if let Some(last) = ports.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 directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
// Comments on their own lines before the `)` belong inside it.
let dangling = self.take_dangling();
@@ -1125,7 +1193,7 @@ impl<'a> Parser<'a> {
last.meta.trailing = self.take_trailing();
}
}
Ok((PortList::Ansi(ports), dangling))
Ok((PortList::Ansi(ports), dangling, directives))
} else {
let mut ports = Vec::new();
loop {
@@ -1134,16 +1202,17 @@ impl<'a> Parser<'a> {
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
ports.push(NonAnsiPort { meta, name, span });
if !more {
ports.push(NonAnsiPort { meta, name, comma, span });
let dirs = self.take_list_directives(&mut directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
Ok((PortList::NonAnsi(ports), dangling))
Ok((PortList::NonAnsi(ports), dangling, directives))
}
}
@@ -1173,7 +1242,7 @@ impl<'a> Parser<'a> {
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, span })
Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, comma: false, span })
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
@@ -1337,6 +1406,8 @@ impl<'a> Parser<'a> {
};
self.expect_sym("{")?;
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
let start = self.here();
let mut meta = self.take_meta();
@@ -1345,10 +1416,11 @@ impl<'a> Parser<'a> {
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, name_span, value, span });
if !more {
members.push(EnumMember { meta, name, name_span, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) {
break;
}
}
@@ -1361,7 +1433,7 @@ impl<'a> Parser<'a> {
name,
name_span,
unpacked,
kind: TypedefKind::Enum(EnumType { base, members, dangling }),
kind: TypedefKind::Enum(EnumType { base, members, directives, dangling }),
});
}
if self.cur().is_kw("struct") || self.cur().is_kw("union") {
@@ -3382,6 +3454,108 @@ mod tests {
assert_eq!(p.links, 0, "chain budget left open after recovery");
}
fn module_of(file: &SourceFile) -> &Module {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
m
}
#[test]
fn a_directive_between_ports_records_its_place_and_the_commas_around_it() {
let src =
"module m (\n input a,\n`ifdef X\n input b,\n`endif\n input c\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.len(), 3);
assert_eq!(
ports.iter().map(|p| p.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &m.port_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second port");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2, "written before the third port");
assert!(d.iter().all(|d| !d.comma), "no comma follows either directive");
}
#[test]
fn a_comma_written_after_a_directive_belongs_to_the_directive() {
// The shape `prim_sparse_fsm_flop.sv` writes: the comma lives inside
// the `ifdef arm so that both arms are legal. Deriving the comma from
// the element's position would move it across the directive.
let src = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 2);
assert!(!params[0].comma, "the first parameter wrote no comma of its own");
assert!(!params[1].comma);
assert_eq!(m.param_directives.len(), 2);
assert!(m.param_directives[0].comma, "`ifdef carries the comma");
assert!(!m.param_directives[1].comma);
}
#[test]
fn a_list_with_no_directive_keeps_an_empty_directive_vector() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing list byte-for-byte unchanged.
let src = "module m #(parameter int P = 1) (input a, input b);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
assert!(m.param_directives.is_empty());
assert!(m.port_directives.is_empty());
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
}
#[test]
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
// vfmt does not evaluate the condition: an `ifdef/`else pair simply
// contributes every element of both arms, in source order.
let src = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
assert!(ports.iter().all(|p| !p.comma), "neither arm's port wrote a comma");
assert_eq!(m.port_directives.len(), 3);
}
#[test]
fn a_directive_between_enum_members_lands_on_the_enum() {
let src = "typedef enum logic {\n A,\n`include \"more.svh\"\n B\n} e_t;\n";
let file = parse_ok(src);
let ItemKind::Typedef(t) = &file.items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.members.len(), 2);
assert_eq!(e.directives.len(), 1);
assert_eq!(e.directives[0].raw.text, "`include \"more.svh\"");
assert_eq!(e.directives[0].before, 1);
}
#[test]
fn a_comment_before_a_list_directive_stays_with_the_directive() {
let src = "module m (\n input a,\n // only when X\n`ifdef X // why\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let d = &m.port_directives[0];
assert_eq!(d.meta.leading.len(), 1);
assert_eq!(d.meta.leading[0].text, "// only when X");
assert_eq!(d.meta.trailing.as_ref().expect("a trailing comment").text, "// why");
}
#[test]
fn a_directive_inside_an_element_is_still_a_parse_error() {
// A directive runs to end of line, so it can only stand *between*
// elements. One written mid-declaration is out of scope by design;
// this pins that it is refused rather than half-parsed.
let src = "module m (\n input\n`ifdef X\n logic\n`endif\n a\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
@@ -51,6 +51,10 @@ const SOURCES: &[&str] = &[
// A string literal that spans a physical line.
"module m;\n initial $display(\"line one\n line two\");\nendmodule\n",
"module m;\n assign y = a inside {[0:3], 4} ? int'(b) + {2{c}} : '{default: 0};\n assign z = pkg::t'(v.field[3:0][2 +: 2]);\nendmodule\n",
// Compiler directives between the elements of a header's lists.
"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",
];
/// A token or a comment, in source order.
@@ -378,6 +382,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
for imp in &m.imports {
check_import_paths(src, &imp.paths, here);
}
for d in m.param_directives.iter().chain(&m.port_directives) {
assert_inside(src, "list directive", d.raw.span, here);
}
if let Some(params) = &m.param_ports {
for p in params {
assert_inside(src, "parameter port", p.span, here);
@@ -423,6 +430,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
ItemKind::Typedef(t) => {
check_name(src, "typedef name", &t.name, t.name_span, here);
if let TypedefKind::Enum(e) = &t.kind {
for d in &e.directives {
assert_inside(src, "list directive", d.raw.span, here);
}
for member in &e.members {
assert_inside(src, "enum member", member.span, here);
check_name(
+612
View File
@@ -0,0 +1,612 @@
# directives-in-lists
## Goal
Accept `` `ifdef``/`` `ifndef``/`` `else``/`` `elsif``/`` `endif``,
`` `define``, `` `include`` — and standalone macro invocations — written
*between the elements* of a module header's port list, its parameter port
list, and an enum member list. They were already accepted wherever a module
item or a statement belongs (`macro-items`); a port list was the one place
real RTL writes them that vfmt refused. This is README roadmap item 6, and
its named payoff is the workspace index: `picorv32`, `picorv32_axi` and
`picorv32_wb` were the index's biggest named gaps (570 external references)
because their headers hold an `` `ifdef`` inside the port list, which swallowed
the whole `module` declaration into an error node so the module never
indexed. **Result: all three now index (521 → 530 modules, 8044 → 9174
exported members), the workspace answers 87.0 % → 93.6 % of external
candidates on cleanly-parsed corpus files, two more corpus files format,
six more advance past this construct to their next blocker, zero regressions,
and `verify.rs` is byte-identical to `HEAD`.**
## Assumptions
- **vfmt does not evaluate the condition, and this feature does not change
that.** Both arms of an `` `ifdef``/`` `else`` contribute their elements to
the one list, in source order, exactly as an `` `ifdef`` at item position
already contributes both arms' items. The formatter is a text tool; a
preprocessor is a different program.
- **A directive is line-oriented, and the lexer captures it to end of line.**
That is a pre-existing shape (`docs/features/macro-items/README.md`) and it
is load-bearing here twice over: a directive can only stand *between*
elements, and nothing the formatter emits may share its line. The direct
consequence is that the one-line spelling `` module m (a, `ifdef X b,
`endif c); `` is **not** supported — the lexer reads `` `ifdef X b, `endif
c); `` as a single directive token. Every corpus file writes the directive
on its own line; see Status/TODO for why the lexer was left alone.
- **The comma placement is data, not a formatting choice.** Between two
elements there is exactly one `,`, but a directive in that gap can sit on
either side of it. Both spellings are real: `picorv32` writes
`eoi,` ⏎ `` `ifdef RISCV_FORMAL`` (comma before the directive), and
`prim_sparse_fsm_flop.sv` writes `` `ifdef SIMULATION`` ⏎ `,` (comma after
it, so that both arms stay legal). See Design for why the comma is stored
rather than derived.
- **An `` `ifdef`` arm need not end with a comma.** `` `ifdef X`` ⏎ `input a`
⏎ `` `else`` ⏎ `input b` ⏎ `` `endif`` is two elements and no comma at all.
A list that commas every element but the last would add one, and the safety
net would refuse the file.
- **A directive inside an *element* stays a parse error**, by design and out
of scope: `input` ⏎ `` `ifdef X`` ⏎ `logic` ⏎ `` `endif`` ⏎ `a` is a
declaration cut in half, not a list with a directive in it. Pinned by
`a_directive_inside_an_element_is_still_a_parse_error`.
- **A macro invocation between elements is disambiguated by the existing
`at_macro_item` rule**, not a new one. So `` `MY_TYPE_T sig`` is still a
port whose type is a macro, and `` `VECTOR_INCLUDE("x.sv")`` before an enum
member is a standalone entry. The one shape that rule gets wrong is
unchanged and inherited: a *parameterized* macro type
(`` `SOME_TYPE(8) sig``) reads as a standalone invocation. No corpus file
writes one.
- **Blank lines inside a bracketed list are dropped**, directives included —
that is the pre-existing `delimited_dangling` rule, not something this
feature chose.
## Handshakes
**New in `vlog_parser::ast` (consumed by `vlog_formatter::format`):**
```rust
pub struct ListDirective {
pub raw: RawText, // the directive line (or macro invocation), verbatim
pub meta: Meta, // comments before it, and the one after it on its line
pub before: usize, // index of the element it was written before
pub comma: bool, // a `,` was written after *it*, not after the element
}
```
| carrier | new field |
|---|---|
| `Module` | `param_directives: Vec<ListDirective>` |
| `Module` | `port_directives: Vec<ListDirective>` — on the module, not inside `PortList`, because a list whose every element sits in an arm is still a `PortList::Empty` |
| `EnumType` | `directives: Vec<ListDirective>` |
| `NonAnsiPort`, `AnsiPort`, `ParamPort`, `EnumMember` | `comma: bool` — whether a `,` followed this element in the source |
**Every change is additive; no variant grew and no vector changed type.**
That was the deciding constraint on the shape: `vlog_semantic::bind` and
`vlog_linter`'s `explicit_parameter_storage_type` iterate
`m.param_ports`, `PortList::Ansi(ports)` and `e.members` directly, so folding
directives into those vectors (`enum PortEntry { Port(..), Directive(..) }`)
would have forced edits in two crates outside this feature's scope. A parallel
vector keyed by `before` preserves source order just as well and costs those
crates nothing — **they were not recompiled against a changed API, only
against new fields they ignore**.
New parser helper: `Parser::take_list_directives(&mut Vec<ListDirective>,
before) -> Harvested`, the list-element twin of `parse_item_kind`'s directive
arm. It is a **no-op unless the cursor is on a directive or a standalone macro
invocation**, deliberately copied from `take_before_sep` / `take_before_open`:
that is why a change reaching four parse loops left all 315 pre-existing
`.cases`, every snapshot and every pre-existing test byte-for-byte green.
Pinned by `a_list_with_no_directive_keeps_an_empty_directive_vector`.
New formatter helpers: `Fmt::list_entries` (interleaves elements and
directives back into source order; returns the elements untouched when there
are no directives) and `Fmt::directive_entry`. `ListItem` gained
`comma: Option<bool>` (`None` = "decide from the position", which every list
that cannot hold a directive keeps) and `directive: bool` (a directive's comma
starts a new line).
**Consumed from `verify.rs`: nothing new. No normalization was added,
broadened or weakened** — `git diff --quiet -- crates/vlog_formatter/src/verify.rs`
exits 0, so CLAUDE.md hard invariant #4 does not bind this round. Nine tests
were added to `tests/verification.rs` anyway — eight **rejection** tests, one
per corruption this plumbing could plausibly produce, plus one asserting the
legitimate re-indent is still accepted. The comma problem was solved by making
the parser record what it read, not by teaching the net to forgive a moved
comma; if it ever tempts someone to widen `normalize`, those eight tests are
what the widening has to survive.
**Multi-line directives ride the existing `RawText.col` path.** A `` `define``
with a `\` continuation inside a parameter port list is emitted by
`Fmt::raw_text`, dedented by `col - 1` and re-indented by the printer — the
same contract `ItemKind::Directive` and `Meta::attrs` already have, including
the string-crossing verbatim fallback. Nothing about
`verify::line_starts_inside_string` changed; it is still the single definition
of which line breaks are data.
**Format fences (`docs/features/format-fences/README.md`): unchanged.**
`fence::scan_scope` walks item-level leading comments only, so a
`// vfmt: off` written before a list directive opens no region — exactly as it
opened none when the same comment landed in the first port's `meta.leading`.
`fence.rs`, `tests/fences.rs` and `fences.cases` are untouched and green.
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):**
unaffected, and no budget is charged. A `ListDirective` is an AST **leaf** — it
holds a `String`, not a `Box<Expr>` — so it adds no root-to-leaf depth, and
`take_list_directives` is a flat `while` over already-lexed tokens. Nesting
`` `ifdef`` inside `` `ifdef`` costs nothing structurally: the arms are not
nested in the AST, they are consecutive entries of one flat list.
**Spans (`docs/features/spans/README.md`):** `ListDirective.raw.span` is the
directive's own token range, which nests inside the enclosing item's span. The
`spans.rs` walker checks all three buckets, and two sources holding list
directives were added to its `SOURCES` table so
`every_node_span_nests_inside_its_parent` and the token-coverage tests cover
them.
**Not touched, by scope:** `crates/vfmt`, `crates/vfmt_core`,
`crates/vfmt_server`, `crates/vlog_linter`, `crates/vlog_semantic`,
`crates/vlog_formatter/src/verify.rs`, `editors/`, `tools/`, `corpus/`. A
second agent was working in `vfmt_server` and `vlog_linter` concurrently; both
crates compile and their tests pass against this diff unmodified. `cargo fmt`
was run per-package (`-p vlog_parser -p vlog_formatter`) rather than `--all`,
so it could not rewrite the other agent's files.
## Design
### The comma problem, and why the comma is stored rather than derived
The obvious cheap rule — *an element gets a `,` unless it is the last one* —
is what every other list in the formatter uses, and it is wrong here in two
directions:
| source | positional rule prints | verdict |
|---|---|---|
| `A = 1` ⏎ `` `ifdef S`` ⏎ `,` ⏎ `B = 2` ⏎ `` `endif`` (`prim_sparse_fsm_flop.sv`) | `A = 1,` ⏎ `` `ifdef S`` ⏎ `B = 2` | the comma hopped across the directive |
| `` `ifdef X`` ⏎ `input a` ⏎ `` `else`` ⏎ `input b` ⏎ `` `endif`` | `input a,` ⏎ `` `else`` ⏎ `input b` | a comma invented that the source never wrote |
Both are token-stream changes, so both would be *refused* rather than
corrupting — but a file vfmt refuses is a file vfmt cannot format, and the
second shape is ordinary RTL. A derivation rule that consults the gap's
directives handles the first case and still fails the second, so it was
rejected as clever-and-wrong.
The shipped rule is one sentence: **every entry records whether a `,` followed
it in the source, and the formatter prints what it recorded.** For a list with
no directive that is exactly `i < last`, which is why not one of the 315
pre-existing cases moved. The element flag lives on the four element structs;
the directive's own flag lives on `ListDirective`.
Two consequences worth stating:
- A trailing comma before the closing bracket (`module m (a, );`) is still a
parse error. The loop only continues past a comma into another element or a
directive; `` `ifdef X`` ⏎ `` `endif`` ⏎ `)` after a comma is malformed
Verilog in every arm and is refused as before.
- The comma that a directive carries is printed on its **own line**, because
anything on the directive's line is swallowed into the directive token by
the lexer. That is what `ListItem::directive` is for, and
`a_comma_swallowed_into_a_list_directive_is_rejected` is the test that pins
the failure mode.
### Parser — one loop shape, three lists
```rust
loop {
elements.push(self.parse_element()?);
self.take_before_sep(&mut last.meta, ",");
let comma = self.eat_sym(",");
last.comma = comma;
let dirs = self.take_list_directives(&mut directives, elements.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(CLOSE)) {
break;
}
}
```
The two break conditions are the whole grammar change:
- **no comma and no directive** — the list is over, as it always was;
- **a directive, and then the closing bracket** — the arm was the tail of the
list (`` `ifdef VERILATOR`` ⏎ `input clk` ⏎ `` `endif`` ⏎ `)`).
Anything else keeps reading elements, which is what lets an `` `else`` arm
follow an arm that wrote no comma. Directives before the *first* element are
harvested once before the loop, because both the ANSI/non-ANSI decision and
the written-but-empty check read the token after them.
### Formatter — an entry is a `ListItem`
`Fmt::list_entries` merges the elements and the directives by `before` into
the vector `delimited_dangling` already takes, so the layout, the comment
plumbing, the dangling bucket and the fence handling are all the existing
code. A directive entry differs in exactly three ways: its doc is
`raw_text(&d.raw)`, its comma comes from the source, and its trailing comment
goes in `before_sep` (which is where the source put it — between the directive
and any comma that follows it) rather than in `trailing`.
`force_break` is set whenever a list holds a directive. It is not cosmetic: a
single-line directive is a plain `Doc::Text`, so nothing else would force the
group open, and a flat `(a, `ifdef X, b)` would fuse three tokens into one.
## Status / TODO
- [x] `ListDirective` + `comma` on the four element structs; every change
additive so `vlog_semantic` and `vlog_linter` need no edit.
- [x] `Parser::take_list_directives`, wired into the parameter port list, the
ANSI port list, the non-ANSI port list and the enum member list.
- [x] Both comma placements (before and after the directive) round-trip; both
shapes come from real corpus files.
- [x] `` `else``/`` `elsif`` arms, nested `` `ifdef``, `` `define`` and
`` `include`` in a list, a list that is nothing but one arm, a header
with directives in both its lists.
- [x] Standalone macro invocations between elements, via the existing
`at_macro_item` predicate (`` `VECTOR_INCLUDE("...")`` between enum
members, `riscv_instr_pkg.sv`).
- [x] 20 cases in `crates/vlog_formatter/tests/cases/directives_in_lists.cases`
(315 → 335 overall); idempotency asserted by the harness.
- [x] 7 parser unit tests, 9 `tests/verification.rs` tests (8 of them
rejection tests), 2 new `spans.rs` sources + walker coverage.
- [x] `verify.rs` byte-identical to `HEAD`; hard invariant #4 does not bind.
- [x] `cargo test --workspace` 563 passed, clippy silent, fmt clean,
`tools/corpus_check.sh` exit 0 with 0 verification errors and 0 crashes.
- [ ] **Not done — the same construct in an instantiation's lists.** Six
corpus files write `` `ifdef``/`` `include``/`` `define`` inside a
module instantiation's `#( ... )` parameter overrides or its `( ... )`
connection list: `ibex_lockstep.sv:518`, `ibex_top.sv:456`,
`spec_instance.sv:65`, `picorv32/testbench.v:164`,
`picorv32/testbench_wb.v:110`, `picorv32/scripts/torture/testbench.v:41`.
Same shape, same solution, different parse loops; out of this round's
stated scope. This is the obvious next slice and it is the single
biggest remaining directive-shaped blocker.
- [ ] **Not done — the one-line spelling**
`` module m (a, `ifdef X b, `endif c); ``. The lexer captures a
directive to end of line, so this is one token, not five. Shortening the
capture for the five conditional directives (which take at most one
argument) would fix it, but it changes what
`ItemKind::Directive`/`StmtKind::Directive` hold for every file in the
tree and would make code after a directive on the same line newly
*parsed* rather than passed through — a lexer round of its own. No
corpus file writes it; every one puts the directive on its own line.
- [ ] **Not done — a directive between an element's own tokens.** Out of
scope by design; see Assumptions. Clean parse error, never output.
- [ ] **Known refusal, not corruption:** a directive with a trailing comment
*and* a comma after it (`` `ifdef X // why`` ⏎ `, port`) prints the
comment and the comma in the source's order only when the comment comes
first; the reverse spelling is refused by the net. Nothing in the corpus
writes either.
## Corpus results
`./tools/corpus_check.sh corpus`, release build, script exit status **0**.
Corpus verified unmodified afterwards (`git status --porcelain` clean in all
four repos except the untracked `.vfmt-corpus-rev` stamp). Two runs, TSVs
byte-identical (deterministic).
| outcome | before (`3a503e1`, the tree this work started from) | after |
|---|---|---|
| ok-unchanged | 8 (1.0 %) | 8 (1.0 %) |
| would-reformat | 460 (56.1 %) | **462 (56.3 %)** |
| parse-error | 352 (42.9 %) | **350 (42.7 %)** |
| verification-error | 0 | **0** |
| other-error | 0 | 0 |
| crash | 0 | 0 |
| **parsed & formattable** | 460/820 (56.1 %) | **470/820 (57.3 %)** |
TSV md5 `aa982463f68c1a3568c02a0fc5e0c455` → `31ffdb18c96d4e79057178f7de269756`.
**By-path delta, diffed by file path rather than by count: 2 files moved
`parse-error` → `would-reformat`, 0 files moved the other way, and no file
that already parsed changed category.** The two:
| file | before | after |
|---|---|---|
| `corpus/ibex/rtl/ibex_core.sv` | `parse-error` 127:1, `` `ifdef RVFI`` in the port list | `would-reformat`, round-trip idempotent |
| `corpus/picorv32/scripts/csmith/testbench.v` | `parse-error` 4:1, `` `ifdef VERILATOR`` around the whole port list | `would-reformat`, round-trip idempotent |
**Six more files advanced past this construct to a different, unrelated
blocker** — the honest half of the ledger, and the reason the headline number
is 2 and not 8:
| file | was | now |
|---|---|---|
| `corpus/picorv32/picorv32.v` | 123:1 `` `ifdef RISCV_FORMAL`` (port list) | 2109:2 `restrict property` — roadmap item 7, concurrent assertions |
| `corpus/ibex/rtl/ibex_top.sv` | 136:1 `` `ifdef RVFI`` (port list) | 456:1 `` `ifdef RVFI`` in an **instantiation connection list** |
| `corpus/ibex/dv/formal/check/top.sv` | 49:3 `` `ifndef YOSYS`` (port list) | 143:1 `default clocking` — roadmap item 8 |
| `corpus/ibex/vendor/lowrisc_ip/.../prim_sparse_fsm_flop.sv` | 14:1 `` `ifdef SIMULATION`` (parameter list) | 48:32 a `for` header declaring two variables |
| `corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv` | 651:5 `` `include`` (enum members) | 1214:41 `$`-bound in a range |
| `corpus/picorv32/scripts/torture/testbench.v` | 2:1 `` `ifdef VERILATOR`` (port list) | 41:1 `` `include`` in an **instantiation parameter list** |
Two of those six are the instantiation-list gap parked under Status/TODO.
### picorv32, stated plainly
**`picorv32.v` still does not format**, and it will not until roadmap item 7
lands: its header now parses, and the file gets 1986 lines further before
hitting `restrict property (...)` inside `` `ifdef FORMAL``. The brief named
picorv32/picorv32_axi as the acceptance target because of what the *index*
could not see, and that half is fully delivered — the index uses
`parse_source_tolerant`, so a module whose header parses is indexed even when a
later item does not:
| unit | `HEAD` | after |
|---|---|---|
| `picorv32` | **0 defs** | 1 (`corpus/picorv32/picorv32.v`) |
| `picorv32_axi` | **0 defs** | 1 (same file) |
| `picorv32_wb` | **0 defs** | 1 (same file) |
| `picorv32_pcpi_mul` | 1 | 1 (unchanged control — it has no directive in its header) |
### Workspace index / semantic resolution
`cargo test -p vlog_semantic --test workspace -- --nocapture
the_corpus_index_finishes_most_external_references`, same 860-file scan, run
on a `HEAD` worktree and on this tree:
| metric | `HEAD` | after |
|---|---|---|
| modules indexed | 521 | **530** |
| packages | 63 | 63 |
| file-scope typedefs | 38 | 37 |
| exported members | 8 044 | **9 174** |
| `` `define`` directives | 502 | 502 |
| external candidates answered (every file) | 81.4 % | **86.9 %** |
| external candidates answered (cleanly-parsed files) | 87.0 % | **93.6 %** |
| unresolved-external rate, all references (every file) | 3.6 % | **2.6 %** |
| unresolved-external rate, all references (clean files) | 2.6 % | **1.3 %** |
The +1130 exported members are mostly picorv32's four modules' ports and
parameters, which had never been indexed. The one *lost* file-scope typedef is
a `riscv_instr_pkg.sv` enum that used to be recovered at file scope out of an
error node and is now parsed inside its package, where it belongs — a
correction, not a loss.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, and the `macro-items`, `workspace-index`,
`comments-round-2` and `spans` READMEs before touching code. Baseline on
this working tree: `cargo test --workspace` **547 passed** (the brief's 524
is the `comments-round-2` figure; the concurrent `server-lint` work, since
committed as `2ba995d`, had already added tests to the same tree), clippy
silent, fmt clean, corpus TSV md5 `aa982463f68c1a3568c02a0fc5e0c455`,
exit 0. All before/after comparisons below are against `3a503e1`, the
commit this work branched from; `2ba995d` landed alongside it and touches
neither `vlog_parser` nor `vlog_formatter`.
- **Measured the actual shapes before designing anything.** Ran the corpus
check first and pulled every parse error whose "found" token starts with a
backtick: 12 files, in four distinct shapes. That is what turned the comma
problem from a hypothetical into a requirement — `prim_sparse_fsm_flop.sv`
writes the comma *inside* the `` `ifdef`` arm, which no positional rule can
reproduce, and `ibex/dv/formal/check/top.sv` writes an arm with no comma at
all.
- **Tried the cheap derivation first and rejected it with a counterexample,
not a hunch.** "An element takes the gap's comma unless a directive in that
gap carries it" handles `prim_sparse_fsm_flop` and still invents a comma
between two `` `else`` arms. Storing the flag is three more struct fields
and no reasoning at all at print time, so it won.
- **Chose a parallel `Vec<ListDirective>` over one entry enum because of the
crates I am not allowed to touch.** `vlog_semantic::bind` and the
`explicit_parameter_storage_type` lint iterate the element vectors
directly; changing `Vec<AnsiPort>` to `Vec<PortEntry>` would have required
edits in two out-of-scope crates. `before: usize` preserves source order
just as well. Recorded under Handshakes so the next reader does not
re-litigate it.
- **The `` `else``-arm case is what forced the second break condition.** The
first draft continued the list only when a comma had been written
(element's or directive's), which parses `picorv32` fine and dies on
`` `ifdef X`` ⏎ `a` ⏎ `` `else`` ⏎ `b` ⏎ `` `endif``. The fix — keep reading
unless the closing bracket is next — also makes the "list is one arm"
shape work, which is what `picorv32/scripts/csmith/testbench.v` writes, and
it is why `module m (a, );` is still a parse error: that break is only
reachable when a directive was actually harvested.
- **The sharpest hazard is a comma printed on a directive's line.** The lexer
captures a directive to end of line, so `` `ifdef S, `` is *one* token: the
comma would vanish into the condition. Handled by `ListItem::directive`
forcing a break before the comma, and pinned by a rejection test rather
than by prose.
- **Extended the harvest to standalone macro invocations** because
`riscv_instr_pkg.sv` writes `` `VECTOR_INCLUDE("...")`` between enum
members, reusing `at_macro_item` rather than inventing a second
disambiguation rule. That predicate already declines bare `` `TYPE name``,
so macro-typed ports keep parsing as ports.
- **Left the lexer alone**, deliberately, which costs the one-line spelling
the brief used as its illustration. Shortening the directive capture is a
cross-cutting change (it decides what every `ItemKind::Directive` in the
tree holds and would newly *parse* code written after a directive on the
same line); no corpus file needs it. Written up under Assumptions and
Status/TODO instead of half-done.
- **`verify.rs` was never opened.** The comma problem is a parser bookkeeping
problem, and solving it by teaching the net to forgive a moved comma is
precisely the move CLAUDE.md invariant #4 exists to stop. `git diff
--quiet -- crates/vlog_formatter/src/verify.rs` exits 0; the eight
rejection tests are there so a future round has to argue with them.
- **Verified the corpus delta by path, not by count** (2 gained, 0 lost, 0
category changes among already-parsing files) and read all six
still-failing files' new errors to confirm each is an unrelated construct.
Ran the corpus check twice — byte-identical TSVs. All four corpus repos
confirmed unmodified.
- **Measured the index payoff against a real `HEAD` worktree**, not against
memory: built a detached worktree at `3a503e1`, ran the same
`WorkspaceIndex` probe in both, and confirmed `picorv32`/`picorv32_axi`/
`picorv32_wb` go from **0 defs to 1** while the control
(`picorv32_pcpi_mul`, whose header has no directive) is 1 in both. The
probe test was deleted from both trees afterwards; `git status` confirmed
clean.
- **Reported the picorv32 acceptance honestly**: the file still does not
format, because of `restrict property`. The brief's stated payoff (the
index) is delivered; the formatting half is blocked behind roadmap item 7
and saying otherwise would be a lie the numbers would catch.
- Did not touch `crates/vfmt_server`, `crates/vlog_linter`,
`crates/vlog_semantic`, `crates/vfmt*`, `tools/` or `corpus/`. Ran
`cargo fmt -p vlog_parser -p vlog_formatter` rather than `--all` so the
concurrent agent's files could not be rewritten. Did not run
`git commit`/`git push`.
**Results:** `cargo test --workspace` **563 passed, 0 failed** (547 baseline +
7 parser unit + 9 verification; the 20 new `.cases` entries run inside the
existing `case_tables` test, which now covers 335 cases).
`cargo clippy --workspace --all-targets` silent. `cargo fmt --all --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` (new),
`crates/vlog_formatter/tests/verification.rs`, `README.md` (roadmap item 6),
`TODO.md` (§6 workspace-index annotation), this README.
## QA log
### 2026-08-19 — QA agent
**Verdict: PASS. No blocking findings.** All five claims verified; two minor
documentation nits filed below (non-blocking).
**Gates.** `cargo test --workspace`: **563 passed, 0 failed** (exact match).
`cargo clippy --workspace --all-targets`: silent. `cargo fmt --all -- --check`:
clean. `git diff --quiet -- crates/vlog_formatter/src/verify.rs`: exit 0
(byte-identical to `HEAD`). Same for `fence.rs`, `tests/fences.rs`,
`fences.cases`: all diff-clean.
**Cross-crate untouched claim.** `git diff --stat crates/vlog_semantic
crates/vlog_linter crates/vfmt crates/vfmt_core crates/vfmt_server` is empty.
`crates/vfmt_server/` and `crates/vlog_linter/` are untracked (concurrent
agent's work per the README) so nothing to diff there either; both compiled
and their tests passed as part of the 563.
**Corpus.** `tools/corpus_check.sh corpus`, release build, ran twice:
byte-identical TSVs, md5 `31ffdb18c96d4e79057178f7de269756` both times,
exit 0 both times. Table matches exactly: 8 ok-unchanged, 462
would-reformat, 350 parse-error, 0 verification-error, 0 crash, 470/820
formattable. Corpus repos confirmed clean afterwards (`git status
--porcelain` in each of the four, only the untracked `.vfmt-corpus-rev`
stamp). Spot-checked every by-path claim directly against the TSV and the
source files:
- `ibex_core.sv` → `would-reformat` ✓; `csmith/testbench.v` → `would-reformat` ✓.
- `picorv32.v` → `parse-error 2109:2: expected declaration or instantiation
(found "restrict")`; read the source at that line — it is
`restrict property (...)` inside `` `ifdef FORMAL``, exactly as claimed.
- `ibex_top.sv` → `456:1` `` `ifdef RVFI`` — read the source, it is inside an
instantiation's connection list (`.rvfi_valid,` follows). `top.sv` → `143:1`
`default clocking`. Both match.
- Read all 6 "parked — instantiation lists" files at their cited
locations (`ibex_lockstep.sv:518`, `ibex_top.sv:456`,
`picorv32/testbench.v:164`, `picorv32/testbench_wb.v:110`,
`picorv32/scripts/torture/testbench.v:41`, plus confirmed
`spec_instance.sv` exists at the stated path) — every one genuinely has a
directive inside `#( ... )` or `( ... )` of an instantiation, not a header.
**Semantic re-measurement.** Ran `cargo test -p vlog_semantic --test
workspace -- --nocapture the_corpus_index_finishes_most_external_references`
on this tree: 530 modules, 63 packages, 37 file-scope typedefs, 9174 exported
members, 502 defines, 86.9%/93.6% answered (every-file/clean-file), 2.6%/1.3%
unresolved (every-file/clean-file) — **exact match** to every number in the
README's "after" column.
**Independently reproduced the `3a503e1` baseline** in a detached worktree
(`git worktree add --detach <tmp> 3a503e1`, corpus symlinked in) rather than
trusting the README's "before" column: 521 modules, 38 typedefs, 8044
members, 87.0%/2.6% (clean-file answered/unresolved) — exact match to the
claimed "before" figures, and `picorv32`/`ibex_top` show up in that tree's
"still unresolved" list but not in the after-tree's. Also added a temporary
probe test (`WorkspaceIndex::units(name).len()`) to both trees, ran it, then
reverted (`git checkout --` in this tree; worktree deleted) —
`picorv32`/`picorv32_axi`/`picorv32_wb`: **0 defs → 1 defs**, control
`picorv32_pcpi_mul`: **1 → 1** (unchanged), confirming the index payoff
directly rather than by proxy. `git status --porcelain` clean in this tree
afterward; worktree removed.
**Round-trip torture on the new construct.** Wrote 20 probe files covering
every requested shape (ifdef at first/middle/last position in ports, params,
and enums; an `` `elsif``/`` `else`` chain; 3-deep nesting; the
`prim_sparse_fsm_flop` comma-inside-the-arm shape; a no-comma `` `else``
pair; a list that is one arm and nothing else — `PortList::Empty` with
`port_directives`; a directive immediately before the closing paren; two
adjacent directives (`` `ifdef``+`` `define``); a `` `define`` with a `\`
continuation inside a parameter list; an arm element carrying a trailing
comment; an enum with `` `include`` + a macro invocation between members;
a non-ANSI header with directives). Ran each through the debug binary via
`vfmt -` for 3 passes (`vfmt(vfmt(vfmt(x)))`); every pass exited 0 (which
already means `format_source`'s internal `verify_equivalence` +
`verify_convergence` accepted it — no corruption, no dropped comment/token
possible on a 0 exit) and pass2==pass3 byte-for-byte on all 20. Eyeballed 6
of the trickier outputs directly (comma-inside-arm, no-comma-else,
every-element-in-arm, define-continuation, enum-include+macro, non-ANSI) —
all correct: no invented/lost comma anywhere, comment on the arm element
survived, `` `define`` continuation stayed properly dedented/reindented,
`` `include`` and the macro invocation both preserved in source order.
**Sabotage round (both reverted, diff-verified clean afterward).**
1. Removed `|| item.directive` from the `ends_line` computation in
`format.rs` (the forced-break that keeps a directive's comma off the
directive's own line). Result: `cargo test -p vlog_formatter` immediately
failed — not silently — inside `case_tables`, at exactly
`directives_in_lists.cases:202` ("the comma written after the directive,
not before it"), with diagnostic `token stream diverges at index 9: input
has directive "`ifdef SIM" at 3:1, output has directive "`ifdef SIM," at
3:3`. This is `format_source`'s internal `verify_equivalence` catching the
comma-fusion hazard live, exactly as the README's Design section predicts.
The 8 hardcoded `verification.rs` rejection tests did **not** fail under
this sabotage (expected — they exercise `verify.rs` directly with literal
strings and don't touch the formatter's `list_entries`/`ListItem`
plumbing; `verify.rs` was correctly never touched by this feature). Reverted
the one line; `cases_tables`, clippy, and `git diff --stat format.rs`
(109 insertions/19 deletions, matching the original) all confirm a clean
revert.
2. Injected an invented comma into the `` `else``-arm case at
`directives_in_lists.cases:56` ("neither arm's last port writes a comma").
`case_tables` failed immediately with a precise line diff. Reverted;
`case_tables` green again.
Re-ran the full corpus check after both sabotage/revert cycles: still
byte-identical to `run1.tsv`, same md5, corpus repos still clean.
**`module m (a, );` still a parse error** — confirmed directly:
`./target/release/vfmt --check` on that exact input exits 2 with
`expected identifier (found ")")`.
**Findings (both non-blocking, documentation only):**
- `README.md` roadmap item 6's strike-through text says picorv32/
picorv32_axi/picorv32_wb "now index" and lists the still-open instantiation
gap, but never explicitly states that `picorv32.v` itself still fails to
*format* (blocked on `restrict property`, roadmap item 7) — that fact only
appears in this feature's own README ("picorv32, stated plainly"). Nothing
in `README.md` is false, but a reader of just the top-level roadmap line
could come away thinking picorv32 now formats. Did not fix (touches a file
outside this agent's QA-log-only write scope); flagging for the lead.
- No other findings. Design, parser loop, formatter forced-break, spans
coverage, and every numeric claim (corpus, semantic, index) checked out
exactly, including independent reproduction of the `3a503e1` baseline.
## Review
**2026-08-19 — lead. Verdict: accepted and committed. The workspace
index's biggest named gap closes: cross-file external resolution
93.6% on clean files, unresolved externals halved to 1.3%.**
Points reviewed and accepted:
1. **The stored-comma decision is the round's load-bearing judgment**,
and it was made the right way: two real corpus shapes
(comma-inside-the-arm vs no-comma `else` alternatives) kill any
derivation rule in opposite directions, so the parser records what
was written and the formatter reproduces it. `Option<bool>` with
`None` = positional is why all 315 pre-existing cases stayed
byte-identical — the take_before_sep pattern's third successful
application.
2. **Parallel ListDirective vectors over an entry enum** because the
entry enum would have forced edits in two out-of-scope crates
(vlog_semantic, vlog_linter) — QA confirmed both compile and pass
unmodified. Choosing the shape by its blast radius is the
architecture discipline working.
3. **The comma-on-directive-line hazard** (a printed comma the lexer
would swallow into the condition) prevented structurally by a
forced break, and QA's sabotage confirmed the net catches it at the
exact case if the break is removed.
4. **No overclaim**: picorv32 parses 1986 lines further and its
modules index (the actual payoff), but the file still refuses on
`restrict property` — stated plainly, and the lead has added that
caveat to the top-level roadmap per QA's nit.
The parked follow-ups are the next round's shape: directives in
instantiation `#()`/connection lists (6 named corpus files — the
biggest remaining directive blocker), the one-line spelling (a lexer
round of its own), and the shared fence helper filed by server-lint.