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

+593
View File
@@ -0,0 +1,593 @@
//! The items that instantiate or drive: continuous assignments, module and
//! gate instantiations with their parameter overrides and connections, and
//! `bind` directives. Drive strengths and delay values live here because
//! these are the only items that write them.
use super::*;
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
const DRIVE_STRENGTHS: &[&str] = &[
"supply0", "supply1", "strong0", "strong1", "pull0", "pull1", "weak0", "weak1", "highz0",
"highz1",
];
/// True when `t` is one of the strength keywords a drive strength names.
fn is_drive_strength(t: &Token) -> bool {
t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str())
}
impl<'a> Parser<'a> {
pub(super) fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} else {
None
};
let mut assigns = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let mark = self.pending_trailing.len();
let lhs = self.parse_unary()?;
// Whatever was written on either side of the `=` stays on its own
// side of it, as a procedural assignment's does.
let op_comments = self.take_around(mark);
self.expect_sym("=")?;
let rhs_comments = self.take_around(mark);
let rhs = self.parse_expr()?;
let span = self.span_from(start);
// The last pair's separator is the statement's `;`, so a comment
// written before it (`assign y = a /* c */;`) belongs on the
// value's side of it, not after it.
self.take_before_sep(&mut meta, ",");
self.take_before_sep(&mut meta, ";");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
assigns.push(AssignPair { meta, lhs, rhs, op_comments, rhs_comments, span });
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(ContAssign { strength, delay, assigns })
}
/// The optional `( strength0 , strength1 )` of a continuous assignment
/// (IEEE 1800 §10.3.1), e.g. `assign (weak0, pull1) x = y;` (corpus
/// `ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39`),
/// or of a gate — where a pull gate may also write one strength on its
/// own, `pullup (weak1) p (x);` (§28.3's `pullup_strength`).
///
/// Both orders are accepted, as the grammar allows; the `(` only opens a
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side — and a gate whose first argument is an expression — is
/// untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
self.bump(); // (
let first = self.bump().text;
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
}
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = Some(self.bump().text);
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
/// The value after a `#`: a bare primary, or a parenthesized delay —
/// one value, `min:typ:max`, or the `(rise, fall[, turn-off])` list of
/// IEEE 1800 §28.14.
///
/// A single value keeps the [`ExprKind::Paren`] node the one-value
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
/// exactly as written; only a real comma list yields more than one
/// element.
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
if !self.cur().is_sym("(") {
return Ok(vec![self.parse_primary()?]);
}
let start = self.here();
self.bump(); // (
let mut out = Vec::new();
loop {
let inner_start = self.here();
let first = self.parse_expr()?;
out.push(if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(first),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
first
});
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(")")?;
if out.len() == 1 {
let inner = out.remove(0);
return Ok(vec![self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
)]);
}
Ok(out)
}
/// The single delay value a net declaration or a continuous assignment
/// takes. The multi-value list is a gate-instantiation spelling only —
/// see [`Parser::parse_delay_values`].
pub(super) fn parse_delay_value(&mut self) -> PResult<Expr> {
let mut values = self.parse_delay_values()?;
if values.len() > 1 {
return self.error("a multi-value delay list is only allowed on a gate instantiation");
}
Ok(values.remove(0))
}
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
///
/// `bind` is deliberately *not* in the lexer's keyword table — the same
/// call lucisv makes for `new`/`this`/`super` — so that `obj.bind()` keeps
/// parsing as the ordinary method call it is in existing testbenches.
/// A directive is recognized from its shape instead: the word `bind`,
/// then a target scope (a name, possibly a `.`-separated hierarchical
/// path, each segment possibly carrying one `[…]` selector), then either
/// the `:` of an instance list or the module name of the instantiation.
/// A declaration of a variable called `bind` reaches `;`, `,`, `=` or a
/// dimension there, so it never matches — a `bind [3:0] x;` declaration
/// is a *dimension on the first name*, which is why the scan only steps
/// over a `[…]` that has a `.` or the instantiation after it.
pub(super) fn at_bind_directive(&self) -> bool {
let t = self.cur();
if t.kind != TokenKind::Ident || t.text != "bind" {
return false;
}
let mut p = self.pos + 1;
if !self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Ident) {
return false;
}
p += 1;
loop {
// `top.gen[0].u_core` (IEEE 1800 §23.11's bind_target_instance):
// binding SVA into a generate array is the shape formal setups
// write. One selector per segment; anything more is not a bind
// this parser reads, and stays the clean error it always was.
if self.tokens.get(p).is_some_and(|t| t.is_sym("[")) {
let after = self.scan_matching(p, "[", "]");
if after == p {
return false;
}
p = after;
}
if self.tokens.get(p).is_some_and(|t| t.is_sym("."))
&& self.tokens.get(p + 1).is_some_and(|t| t.kind == TokenKind::Ident)
{
p += 2;
continue;
}
break;
}
self.tokens.get(p).is_some_and(|t| t.is_sym(":") || t.kind == TokenKind::Ident)
}
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
pub(super) fn parse_bind(&mut self) -> PResult<BindDirective> {
self.bump(); // `bind`
// The target is a bare string, so a comment written before it has no
// node to attach to: harvest it here, where source order is still
// known, rather than letting it drift onto the instance below.
let target_comments = self.take_dangling();
let start = self.here();
let mut target = vec![self.parse_path_segment()?];
while self.cur().is_sym(".") {
self.bump();
target.push(self.parse_path_segment()?);
}
let target_span = self.span_from(start);
let mut instances = Vec::new();
if self.eat_sym(":") {
loop {
instances.push(self.parse_bind_instance()?);
if !self.eat_sym(",") {
break;
}
}
}
let module_comments = self.take_dangling();
let inst = self.parse_instantiation()?;
Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst })
}
/// One entry of a `bind`'s `: instance_list`. The LRM spells these as bare
/// instance names, but vendor tools accept — and OpenTitan writes — a
/// hierarchical path: `bind prim_packer_fifo :
/// dut.u_entropy_src_core.u_prim_packer_fifo_precon ...`
/// (`entropy_src/dv/tb/tb.sv:94`). The dots are glued into the one name
/// the list already carries, exactly as `bind`'s own target path is.
fn parse_bind_instance(&mut self) -> PResult<Name> {
let start = self.here();
let mut text = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
let segment = self.expect_ident()?;
Self::push_path_segment(&mut text, &segment);
}
Ok(Name { text, span: self.span_from(start) })
}
/// One segment of a `bind` target path: a name and the one `[…]`
/// selector it may carry.
fn parse_path_segment(&mut self) -> PResult<PathSegment> {
let Name { text: name, span } = self.expect_name()?;
let mut index = None;
if self.eat_sym("[") {
index = Some(self.parse_expr()?);
self.expect_sym("]")?;
}
Ok(PathSegment { name, span, index })
}
pub(super) fn parse_instantiation(&mut self) -> PResult<Instantiation> {
let module_start = self.here();
let mut module = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut module, &segment);
}
let module_span = self.span_from(module_start);
let param_comments = self.take_before_open("#");
let mut params = None;
let mut after_hash = Vec::new();
let mut param_directives = Vec::new();
if self.cur().is_sym("#") {
self.bump();
after_hash = self.take_gap();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
// Same two break conditions as a header's lists (see
// `Parser::parse_module`): no comma and no directive ends
// the list, and after a directive only the closing bracket
// does — an `` `ifdef`` arm may end without a comma and
// still be followed by an `` `else`` arm.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
}
// Comments before the `)` of the override list belong inside it.
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
params = Some(list);
}
let mut instances = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
let dims = self.parse_dims()?;
let conn_comments = self.take_before_open("(");
self.expect_sym("(")?;
let mut conn_directives = Vec::new();
let conns = self.parse_connections(&mut conn_directives)?;
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
instances.push(Instance {
meta,
name,
name_span,
dims,
conn_comments,
conns,
conn_directives,
span,
});
if !more {
break;
}
}
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(Instantiation {
module,
module_span,
param_comments,
after_hash,
params,
param_directives,
instances,
before_semi,
})
}
/// Move the comments written before a list's closing bracket onto the last
/// entry *in source order*, which is a trailing directive when the list has
/// one and the last element otherwise.
///
/// Without the directive case they would print before it, having moved
/// backwards across a token; with an element-less list (`` #(`include
/// "config.vh") ``) the directive is the only place they can go at all.
pub(super) fn take_last_entry_before_close(
&mut self,
last_element: Option<&mut Meta>,
directives: &mut [ListDirective],
elements: usize,
) {
if let Some(d) = directives.last_mut().filter(|d| d.before == elements) {
self.take_before_sep(&mut d.meta, ")");
} else if let Some(meta) = last_element {
self.take_before_sep(meta, ")");
}
}
/// The connections of one instance. `directives` collects the
/// `` `ifdef``-style lines written between them; the harvest must run
/// before the `.`-peek below, or a directive standing before the first
/// connection would be read as a positional expression.
fn parse_connections(&mut self, directives: &mut Vec<ListDirective>) -> PResult<Connections> {
self.take_list_directives(directives, 0);
if self.cur().is_sym(")") {
return Ok(Connections::Ordered(Vec::new()));
}
if self.at_named_connection() {
let mut conns = Vec::new();
loop {
conns.push(self.parse_connection()?);
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = conns.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
// Comments before the closing `)` belong to the last entry: after
// it they would sit outside the connection list entirely.
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Named(conns))
} else {
let mut conns = Vec::new();
loop {
let start = self.here();
let meta = self.take_meta();
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
None
} else {
Some(self.parse_expr()?)
};
// An omitted connection (`u (a, , c)`) consumed no token, so
// this is the empty span where it would have started.
let span = self.span_from(start);
let mut meta = meta;
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
if comma {
meta.trailing = self.take_trailing();
}
conns.push(OrderedConn { meta, expr, comma, span });
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
break;
}
}
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
Ok(Connections::Ordered(conns))
}
}
/// True when the connection list starts with a named connection. The
/// leading `(* ... *)` attributes of the first entry are looked past:
/// they belong to the connection, not to the list.
fn at_named_connection(&self) -> bool {
let mut i = self.pos;
while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute {
i += 1;
}
self.tokens.get(i).is_some_and(|t| t.is_sym("."))
}
/// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and
/// ordered parameter overrides) a bare expression.
pub(super) fn parse_connection(&mut self) -> PResult<Connection> {
let start = self.here();
let mut meta = self.take_meta();
// `(* async *) .async_data_o (x)` — an attribute instance may precede
// a port connection (IEEE 1800 §A.4.1.1), corpus
// `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way
// an item's or a statement's attributes are.
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
if self.eat_sym(".") {
let after_dot = self.take_gap();
let star = self.cur().span;
if self.eat_sym("*") {
let span = self.span_from(start);
return Ok(Connection {
meta,
after_dot,
name: "*".to_string(),
name_span: star,
before_open: Vec::new(),
after_open: Vec::new(),
expr: None,
close_comments: Vec::new(),
comma: false,
span,
});
}
let Name { text: name, span: name_span } = self.expect_name()?;
let before_open = self.take_before_open("(");
let mark = self.pending_trailing.len();
let paren_start = self.here();
let mut close_comments = Vec::new();
let mut after_open = Vec::new();
let expr = if self.eat_sym("(") {
if self.cur().is_sym(")") {
// `.name(/* unused */)`: the comments were written inside
// these parens and are printed back inside them.
let inside = self.take_around(mark);
self.bump();
Some(self.expr_at(paren_start, ExprKind::Empty(inside)))
} else {
after_open = self.take_gap();
let value_mark = self.pending_trailing.len();
let e = match self.conditional_region_end(")") {
Some(end_pos) => self.parse_verbatim_expr(end_pos),
None => self.parse_expr_or_type()?,
};
// `.name(x /* c */)`: written inside the parens, so it is
// printed inside them too.
close_comments = self.take_around(value_mark);
self.expect_sym(")")?;
Some(e)
}
} else {
None
};
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection {
meta,
after_dot,
name,
name_span,
before_open,
after_open,
expr,
close_comments,
comma: false,
span,
})
} else {
let e = self.parse_expr_or_type()?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection {
meta,
after_dot: Vec::new(),
name: String::new(),
name_span: TextRange::empty(span.start),
before_open: Vec::new(),
after_open: Vec::new(),
expr: Some(e),
close_comments: Vec::new(),
comma: false,
span,
})
}
}
/// Consume the tokens up to `end_pos` as one verbatim expression.
///
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
/// scope only, and a construct that walks its body through
/// [`Parser::bump`] inherits "does not count" by doing nothing — see
/// [`Parser::note_item_conditional`].
fn parse_verbatim_expr(&mut self, end_pos: usize) -> Expr {
let start = self.here();
let col = self.cur().col;
while self.pos < end_pos && !self.at_eof() {
self.bump();
}
let raw = self.verbatim_since(start, col);
self.expr_at(start, ExprKind::Verbatim(raw))
}
pub(super) fn parse_gate_instantiation(&mut self) -> PResult<GateInstantiation> {
let gate = self.bump().text;
// `pullup (weak1) p (x);` — the strength stands where an unnamed
// instance's argument list would, and only a strength keyword after
// the `(` tells the two apart.
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
self.parse_delay_values()?
} else {
Vec::new()
};
let mut instances = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let (name, name_span) = split_label(name);
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
instances.push(GateInstance { meta, name, name_span, args, span });
if !more {
break;
}
}
self.expect_sym(";")?;
Ok(GateInstantiation { gate, strength, delay, instances })
}
}