Decomposition, lane A: vlog_parser's parser.rs and ast.rs become twenty-seven modules, a pure move

TODO section 28, lane A (the file-size rule in CLAUDE.md).
parser.rs (8 786 production + 5 044 test lines) becomes parser/{mod,
cursor, recover, directive, split, verbatim, item, module, decl, tf,
instance, stmt, keyword_stmt, expr, primary, class, covergroup,
assertion, sva}.rs with the tests regrouped into parser/tests/ (14
files, 309 tests, same names and bodies); ast.rs (3 313) becomes
ast/{mod, module, decl, stmt, expr, class, covergroup, sva}.rs, every
type re-exported so vlog_parser::ast::X is unchanged. Nothing over 800
production lines; the two keyword dispatch tables kept whole and
documented as such, parse_keyword_stmt in a file of its own. Carved by
a line-range manifest that had to concatenate back to the original
byte for byte before writing; 149 methods and 18 items pub(super) as
the compiler demanded. Proof: per-binary test counts identical
(workspace 3 215 / 48), 4 807 corpus + opentitan files byte-identical
to the v0.33.0 binary, cargo doc item list unchanged, and a multiset +
signature census done by the dev, redone by QA, re-run by the lead.

docs/features/decomposition-parser/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-02 21:13:32 -07:00
1 parent 159f6a0bd8
commit 9b93f33ae3
45 files changed
+17999 -17241

No files matched your search

+550
View File
@@ -0,0 +1,550 @@
//! What a module, interface or program is made of: the header (parameter
//! ports, ports), the items that instantiate or drive (continuous assignments,
//! instantiations, gates, `bind`), generate constructs, modports and clocking
//! blocks.
use super::*;
/// A `module` / `macromodule` / `interface` declaration.
///
/// An interface header is the module header's grammar (IEEE 1800 §25.3) and an
/// interface body is the module body's item list plus `modport` and `clocking`,
/// so the two share one node; `kw` says which was written and
/// [`Module::end_kw`] the closing keyword that goes with it.
#[derive(Debug)]
pub struct Module {
pub kw: String,
/// Comments written between the keyword and the name
/// (`module /*c*/ m`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// One entry per `import` statement written in the header. A header may
/// write several (`module m import a::*; import b::t; (...)`), and merging
/// them into one statement would replace a `;` with a `,`.
pub imports: Vec<HeaderImport>,
/// Comments written between the header's name (or its last `import`) and
/// the `#` of the parameter port list. Empty when the header wrote none.
pub param_comments: Vec<Comment>,
/// Comments written between that `#` and its `(`.
pub param_after_hash: Vec<Comment>,
/// `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>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of the footer's `: name` label.
pub end_label_comments: Box<LabelComments>,
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
impl Module {
/// The keyword that closes this declaration: `endmodule`, `endinterface`
/// or `endprogram`.
pub fn end_kw(&self) -> &'static str {
match self.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
}
}
}
/// One `import` statement in a module header, with the comments written
/// around it. A header import is not an [`Item`], so it needs its own place
/// to keep them.
#[derive(Debug)]
pub struct HeaderImport {
pub meta: Meta,
/// The comma-separated paths of this one statement.
pub paths: Vec<ImportPath>,
}
#[derive(Debug)]
pub enum PortList {
/// No port list at all: `module m;`
None,
/// Empty parens: `module m();`
Empty,
/// ANSI-style declarations in the header.
Ansi(Vec<AnsiPort>),
/// Non-ANSI: just names in the header, declared in the body.
NonAnsi(Vec<NonAnsiPort>),
}
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
/// `name_span`: the port *is* its name, so `span` already is that range.
#[derive(Debug)]
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,
}
#[derive(Debug)]
pub struct AnsiPort {
pub meta: Meta,
pub dir: Option<String>,
/// Comments written between the direction keyword and the type
/// (`input /*c*/ logic clk`). Empty when no direction was written.
pub after_dir: Vec<Comment>,
pub net: Option<String>,
pub ty: DataType,
/// Comments written between the type and the port's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
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,
}
#[derive(Debug)]
pub struct ParamPort {
pub meta: Meta,
/// `parameter` or `localparam`; empty if omitted (continuation params).
pub kw: Option<String>,
/// Comments written between that keyword and the type
/// (`parameter /*c*/ int W = 8`).
pub after_kw: Vec<Comment>,
pub ty: DataType,
pub is_type: bool,
/// Comments written between the type and the parameter's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
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,
}
#[derive(Debug)]
pub struct ContAssign {
/// Drive strength: the `(weak0, pull1)` in
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
pub strength: Option<DriveStrength>,
/// Delay expression: the `5` in `assign #5 x = y;`
pub delay: Option<Expr>,
pub assigns: Vec<AssignPair>,
}
/// The `( strength0 , strength1 )` of a continuous assignment or a gate. The
/// two strengths are stored in the order the source wrote them — the language
/// allows either order and lucisv is not a legality checker.
#[derive(Debug)]
pub struct DriveStrength {
pub first: String,
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
pub second: Option<String>,
}
#[derive(Debug)]
pub struct AssignPair {
pub meta: Meta,
pub lhs: Expr,
pub rhs: Expr,
/// Comments written between the left-hand side and the `=`
/// (`assign y /*c*/ = x;`).
pub op_comments: Vec<Comment>,
/// Comments written between the `=` and the right-hand side. Kept here so
/// they print on the `=`'s side of the value instead of drifting into it.
pub rhs_comments: Vec<Comment>,
/// Code extent of `lhs = rhs`.
pub span: TextRange,
}
#[derive(Debug)]
pub struct Instantiation {
pub module: String,
/// Byte range of `module`. A scope-qualified name (`pkg::mod`) is stored
/// with its `::` glued, so there the slice matches `module` only modulo
/// the whitespace the source may have written around the `::`.
pub module_span: TextRange,
/// Comments written between the module name and the `#` of the parameter
/// override list. Empty when the source wrote no `#(...)`.
pub param_comments: Vec<Comment>,
/// Comments written between that `#` and its `(`.
pub after_hash: Vec<Comment>,
/// The parameter override list, `None` when the source wrote no `#(...)`
/// 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>,
/// Comments written between the last instance and the `;`.
pub before_semi: Vec<Comment>,
}
#[derive(Debug)]
pub struct Instance {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub dims: Vec<Dim>,
/// Comments written between the instance name (or its dimensions) and the
/// `(` 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,
}
#[derive(Debug)]
pub enum Connections {
Ordered(Vec<OrderedConn>),
Named(Vec<Connection>),
}
#[derive(Debug)]
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,
}
#[derive(Debug)]
pub struct Connection {
pub meta: Meta,
/// Comments written between the `.` and the port name (`. /*c*/ clk(x)`).
pub after_dot: Vec<Comment>,
/// Port/parameter name; `*` for the SystemVerilog `.*` wildcard.
pub name: String,
/// Byte range of `name`; empty for a positional connection, which has no
/// name to point at.
pub name_span: TextRange,
/// Comments written between the name and the `(` (`.clk /*c*/ (x)`).
pub before_open: Vec<Comment>,
/// Comments written just inside the `(` (`.clk( /*c*/ x)`). An empty
/// connection keeps its own in [`ExprKind::Empty`], as it always has.
pub after_open: Vec<Comment>,
/// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`.
/// An explicitly empty connection `.name()` is `Some(Expr::Empty)`.
pub expr: Option<Expr>,
/// Comments written between the value and the connection's own `)`
/// (`.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,
}
/// One segment of a hierarchical path: the `gen[0]` of `top.gen[0].u_core`.
///
/// Only a `bind` directive's target is written this way today. Every other
/// dotted name in the AST is either an expression
/// ([`ExprKind::Member`]) or a joined string, and neither wanted a third
/// spelling — this one exists because a bind target is a *scope*, not a
/// value, and because its `[…]` is not part of any name.
#[derive(Debug)]
pub struct PathSegment {
/// The segment's identifier, exactly as written.
pub name: String,
/// Byte range of `name`.
pub span: TextRange,
/// The `[…]` selector written after it, if any: `gen[0]`'s `0`.
pub index: Option<Expr>,
}
/// A `bind` directive: everything after the target scope is an ordinary
/// module instantiation, so it is parsed and printed as one.
#[derive(Debug)]
pub struct BindDirective {
/// The bind target: a module or interface name (`prim_secded_22_16_tb`),
/// an instance name (`i_nopass1`) or a hierarchical path
/// (`top.u_dut.u_core`, `top.gen[0].u_core`), one [`PathSegment`] per
/// name. A path is *not* joined into one string: an escaped segment needs
/// the whitespace that terminates it (`docs/topo.md` §2.9-21), and an
/// indexed segment is not a name at all.
pub target: Vec<PathSegment>,
/// Byte range of the whole target path, `.` separators and `[…]`
/// selectors included.
pub target_span: TextRange,
/// Comments written between `bind` and the target name. They have no node
/// of their own to hang on — the target is a bare string — so they are
/// kept here and printed back between the same two tokens.
pub target_comments: Vec<Comment>,
/// The `: u_a, u_b` instance list that narrows a module target to
/// particular instances. Empty when the source wrote no `:`.
pub instances: Vec<Name>,
/// Comments written between the target (or the instance list) and the
/// module name of the instantiation, for the same reason.
pub module_comments: Vec<Comment>,
/// The instantiation being bound, identical in shape to a standalone one.
pub inst: Instantiation,
}
impl BindDirective {
/// The target path as one dotted string, for consumers that want a
/// spelling rather than the segments — the workspace's paths, a
/// diagnostic, a test. An escaped segment keeps the space that terminates
/// it, so the spelling re-lexes as the same names.
pub fn target_path(&self) -> String {
let mut out = String::new();
for seg in &self.target {
if !out.is_empty() {
if out.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
out.push(' ');
}
out.push('.');
}
out.push_str(&seg.name);
}
out
}
/// The head of the target path — the module, interface or instance name a
/// `bind` starts at. `None` only for a path with no segments, which the
/// parser never builds.
pub fn head(&self) -> Option<&PathSegment> {
self.target.first()
}
}
#[derive(Debug)]
pub struct GateInstantiation {
/// `and`, `or`, `not`, ...
pub gate: String,
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
/// `(strong0, strong1)` pair every driving gate also accepts.
pub strength: Option<DriveStrength>,
/// The delay written after `#`: empty when there is none, one element for
/// every spelling a net or a continuous assignment also accepts, and two
/// or three for the `(rise, fall[, turn-off])` list that only a gate
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
pub delay: Vec<Expr>,
pub instances: Vec<GateInstance>,
}
#[derive(Debug)]
pub struct GateInstance {
pub meta: Meta,
pub name: Option<String>,
/// Byte range of `name`.
pub name_span: Option<TextRange>,
pub args: Vec<ExprItem>,
/// Code extent of the gate instance.
pub span: TextRange,
}
#[derive(Debug)]
pub struct GenIf {
pub cond: Expr,
pub then: GenBlock,
pub els: Option<Box<GenElse>>,
/// Code extent of the whole `if`, its `else` branch included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum GenElse {
/// `else if`: boxed because a `Meta` plus a whole `GenIf` inline makes
/// this variant several times the size of `Block`.
If(Meta, Box<GenIf>),
Block(GenBlock),
}
#[derive(Debug)]
pub struct GenFor {
pub init: SimpleAssign,
pub init_genvar: bool,
/// Comments written between the `genvar` keyword and the loop variable.
/// Empty when no `genvar` was written.
pub after_genvar: Vec<Comment>,
pub cond: Expr,
pub step: ForStep,
/// The same seven header slots a statement `for` owns.
pub comments: Box<ForComments>,
pub body: GenBlock,
}
#[derive(Debug)]
pub struct GenCase {
pub expr: Expr,
pub items: Vec<GenCaseItem>,
pub dangling: Vec<Comment>,
}
#[derive(Debug)]
pub struct GenCaseItem {
pub meta: Meta,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
/// Comments written between the last label — or the `default` keyword —
/// and the `:` that ends the label list.
pub before_colon: Vec<Comment>,
pub body: GenBlock,
/// Code extent of the case item, its body included.
pub span: TextRange,
}
/// A single generate block: either a labeled/unlabeled begin..end with items,
/// or a single item.
#[derive(Debug)]
pub struct GenBlock {
/// Comments written between whatever precedes the block and its `begin`
/// (`for (…) /*c*/ begin : g`). Empty for a block-less single item, which
/// keeps them in its own leading comments.
pub before_kw: Vec<Comment>,
/// Comments written between `begin` and the `:` of its label.
pub before_colon: Vec<Comment>,
/// Comments written between that `:` and the label name.
pub after_colon: Vec<Comment>,
pub label: Option<String>,
/// Byte range of `label`.
pub label_span: Option<TextRange>,
pub is_block: bool,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `end : g`.
pub end_label_comments: Box<LabelComments>,
/// Label after `end :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// Code extent of the block or of the single item it holds.
pub span: TextRange,
}
/// One modport of a `modport a (...), b (...);` declaration (IEEE 1800 §25.5).
#[derive(Debug)]
pub struct ModportDecl {
/// Comments written around this modport within the declaration.
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub ports: Vec<ModportPort>,
/// Comments written after the last port and before the `)`.
pub dangling: Vec<Comment>,
/// True when a `,` followed this modport in the source.
pub comma: bool,
/// Code extent from the name through the closing `)`.
pub span: TextRange,
}
/// One direction group of a modport's port list: the keyword plus every name
/// it governs. `input a, b, output c` is two groups, which is how the source's
/// grouping survives a reformat.
#[derive(Debug)]
pub struct ModportPort {
pub meta: Meta,
/// `input`, `output`, `inout`, `ref`, `import`, `export` or `clocking`.
pub kw: String,
/// The names this keyword governs. A `clocking` group names exactly one.
pub names: Vec<Name>,
/// True when a `,` followed the last name of this group in the source.
pub comma: bool,
/// Code extent from the keyword through its last name.
pub span: TextRange,
}
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), including
/// the `default clocking` spellings and the body-less
/// `default clocking cb;` clocking assignment (§14.12).
#[derive(Debug)]
pub struct ClockingDecl {
/// True when the declaration was written `default clocking ...`.
pub is_default: bool,
/// `None` for the anonymous `default clocking @(posedge clk);` form.
pub name: Option<Name>,
/// The `@( ... )` clocking event. `None` for `default clocking cb;`, which
/// selects an existing clocking block and has no body.
pub event: Option<SensList>,
/// Empty when there is no body (`default clocking cb;`).
pub items: Vec<ClockingItem>,
pub dangling: Vec<Comment>,
/// True when the declaration wrote an `endclocking`.
pub has_end: bool,
/// Comments written in the two gaps of `endclocking : cb`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endclocking :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
}
/// One item of a clocking block's body.
#[derive(Debug)]
pub struct ClockingItem {
pub meta: Meta,
pub kind: ClockingItemKind,
/// Code extent of the item, its `;` excluded.
pub span: TextRange,
}
#[derive(Debug)]
pub enum ClockingItemKind {
/// `default input #1step output #0;` — at least one half is written.
Default { input: Option<String>, output: Option<String> },
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression binds the clocking signal to
/// something other than the same-named signal in the enclosing scope:
/// `output tms = _tms_internal;`.
#[derive(Debug)]
pub struct ClockingSignal {
pub name: Name,
/// `None` for the plain `input tdo;` spelling.
pub value: Option<Expr>,
}