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

+542
View File
@@ -0,0 +1,542 @@
//! The module, interface and program header, and the body constructs that
//! belong only to them: parameter ports, ports (ANSI and non-ANSI),
//! modports and clocking blocks.
use super::*;
/// The three pieces a `#( parameter ... )` port list yields, so module and
/// class headers can share one parse.
#[derive(Default)]
pub(super) struct ParamPortList {
/// `None` when no `#( ... )` was written at all.
pub(super) ports: Option<Vec<ParamPort>>,
pub(super) directives: Vec<ListDirective>,
pub(super) dangling: Vec<Comment>,
/// Comments written between the `#` and the `(`.
pub(super) after_hash: Vec<Comment>,
}
impl<'a> Parser<'a> {
/// A `module` / `macromodule` / `interface` declaration. The three share
/// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list —
/// only the closing keyword differs, so `end_kw` is the whole difference.
pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
let kw = self.bump().text;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let mut imports = Vec::new();
while self.cur().is_kw("import") {
let mut meta = self.take_meta();
let paths = self.parse_import_list()?;
meta.trailing = self.take_trailing();
imports.push(HeaderImport { meta, paths });
}
let param_comments = self.take_before_open("#");
let ParamPortList {
ports: param_ports,
directives: param_directives,
dangling: param_dangling,
after_hash: param_after_hash,
} = self.parse_param_port_list()?;
let port_comments = self.take_before_open("(");
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end(end_kw) {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer(end_kw)?;
let (end_label_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(Module {
kw,
before_name,
name,
param_after_hash,
name_span,
imports,
param_comments,
param_ports,
param_directives,
param_dangling,
port_comments,
ports,
port_directives,
port_dangling,
before_semi,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
})
}
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5).
pub(super) fn parse_modport(&mut self) -> PResult<Vec<ModportDecl>> {
self.expect_kw("modport")?;
let mut out = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
self.expect_sym("(")?;
let mut ports = Vec::new();
while !self.cur().is_sym(")") && !self.at_eof() {
ports.push(self.parse_modport_port()?);
if !ports.last().is_some_and(|p: &ModportPort| p.comma) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
let span = self.span_from(start);
if let Some(last) = ports.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
out.push(ModportDecl { meta, name, name_span, ports, dangling, comma, span });
if !comma {
break;
}
}
self.expect_sym(";")?;
Ok(out)
}
/// One direction group of a modport's port list. `input a, b, output c` is
/// two groups: the comma keeps the group open only while a plain name
/// follows it — a direction keyword starts the next group.
fn parse_modport_port(&mut self) -> PResult<ModportPort> {
const MODPORT_KEYWORDS: &[&str] =
&["input", "output", "inout", "ref", "import", "export", "clocking"];
let start = self.here();
let mut meta = self.take_meta();
let t = self.cur();
if t.kind != TokenKind::Keyword || !MODPORT_KEYWORDS.contains(&t.text.as_str()) {
return self.error("expected a modport port direction");
}
let kw = self.bump().text;
let mut names = vec![self.expect_name()?];
let mut span = self.span_from(start);
let mut comma = false;
loop {
self.take_before_sep(&mut meta, ",");
if !self.eat_sym(",") {
break;
}
if self.cur().kind != TokenKind::Ident {
// The comma separates this group from the next one.
comma = true;
break;
}
names.push(self.expect_name()?);
span = self.span_from(start);
}
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ModportPort { meta, kw, names, comma, span })
}
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3). The
/// `default` keyword, when written, has already been consumed.
pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult<ClockingDecl> {
self.expect_kw("clocking")?;
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
// `default clocking cb;` selects an existing block and has no body.
let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
self.expect_sym(";")?;
if event.is_none() {
return Ok(ClockingDecl {
is_default,
name,
event,
items: Vec::new(),
dangling: Vec::new(),
has_end: false,
end_label_comments: Box::default(),
end_label: None,
end_label_span: None,
});
}
let mut items = Vec::new();
while !self.at_body_end("endclocking") {
items.push(self.parse_clocking_item()?);
}
let dangling = self.take_dangling();
self.expect_closer("endclocking")?;
let (end_label_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(ClockingDecl {
is_default,
name,
event,
items,
dangling,
end_label_comments,
has_end: true,
end_label,
end_label_span,
})
}
/// One item of a clocking block's body: `default input #1step output #0;`
/// or a direction group (`input #2 a, b;`).
fn parse_clocking_item(&mut self) -> PResult<ClockingItem> {
let start = self.here();
let mut meta = self.take_meta();
let kind = if self.eat_kw("default") {
let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None };
let output =
if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None };
if input.is_none() && output.is_none() {
return self.error("expected `input` or `output` after `default`");
}
ClockingItemKind::Default { input, output }
} else {
let t = self.cur();
if !(t.is_kw("input") || t.is_kw("output") || t.is_kw("inout")) {
return self.error("expected a clocking item");
}
let dir = self.bump().text;
let skew =
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
let mut signals = vec![self.parse_clocking_signal()?];
while self.eat_sym(",") {
signals.push(self.parse_clocking_signal()?);
}
ClockingItemKind::Signals { dir, skew, signals }
};
let span = self.span_from(start);
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ClockingItem { meta, kind, span })
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
/// §14.4's `clocking_decl_assign`. The expression names what the clocking
/// signal is really bound to (`output tms = _tms_internal;`), and it is an
/// ordinary expression rather than a second grammar.
fn parse_clocking_signal(&mut self) -> PResult<ClockingSignal> {
let name = self.expect_name()?;
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
Ok(ClockingSignal { name, value })
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
let t = self.cur();
t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge")
}
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
/// it is a delay or an edge, never something lucisv re-lays out — so the
/// printer writes back exactly what the source said. The `#(min:typ:max)`
/// spelling is not supported; see the feature README's Assumptions.
fn parse_clocking_skew(&mut self) -> PResult<String> {
if self.eat_sym("#") {
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
return Ok(format!("#{}", self.bump().text));
}
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
return Ok(self.bump().text);
}
self.error("expected a clocking skew")
}
/// A `#( parameter ... )` port list, shared by module and class headers.
/// `ports` is `None` when no `#(` was written at the cursor at all.
pub(super) fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
let mut out = ParamPortList::default();
if !self.cur().is_sym("#") {
return Ok(out);
}
self.bump();
out.after_hash = self.take_gap();
self.expect_sym("(")?;
let mut list = Vec::new();
self.take_list_directives(&mut out.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, ",");
}
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 out.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;
}
}
}
out.dangling = self.take_dangling();
self.expect_sym(")")?;
out.ports = Some(list);
Ok(out)
}
/// An optional `= value`, with the comments written on either side of the
/// `=` (`W /*a*/ = /*b*/ 8`). The value is read by `parse`, since a
/// `type` parameter's default is a type and everything else's is an
/// expression.
pub(super) fn parse_eq_default(
&mut self,
parse: fn(&mut Self) -> PResult<Expr>,
) -> PResult<(Box<BinaryComments>, Option<Expr>)> {
if !self.cur().is_sym("=") {
return Ok((Box::default(), None));
}
let before = self.take_gap();
self.bump();
let after = self.take_gap();
let value = parse(self)?;
Ok((Box::new(BinaryComments { before, after }), Some(value)))
}
fn parse_param_port(&mut self) -> PResult<ParamPort> {
let start = self.here();
let mut meta = self.take_meta();
let mut after_kw = Vec::new();
let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") {
let word = self.bump().text;
after_kw = self.take_gap();
Some(word)
} else {
None
};
if self.eat_kw("type") {
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_type_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
return Ok(ParamPort {
meta,
kw,
after_kw,
ty: DataType::default(),
is_type: true,
before_name,
name,
name_span,
unpacked: Vec::new(),
eq_comments,
default,
comma: false,
span,
});
}
let ty = self.parse_opt_data_type()?;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(ParamPort {
meta,
kw,
after_kw,
ty,
is_type: false,
before_name,
name,
name_span,
unpacked,
eq_comments,
default,
comma: false,
span,
})
}
/// 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(), 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, directives));
}
let ansi = {
let t = self.cur();
t.is_kw("input")
|| t.is_kw("output")
|| t.is_kw("inout")
|| t.is_kw("ref")
|| TYPE_KEYWORDS.contains(&t.text.as_str())
|| NET_KEYWORDS.contains(&t.text.as_str())
// A direction is optional on the *first* ANSI port too (IEEE
// 1800 §23.2.2.2), and an interface port is normally written
// with none at all: `module m (bus_if bus, input logic clk);`.
// Such a port opens with a plain identifier, exactly as a
// non-ANSI name list does, so the two are told apart by what
// follows it — a second identifier (past any `pkg::` chain,
// `#( ... )` override or packed dimensions) means a type and a
// name, while the `,` or `)` of `module m (a, b);` does not.
|| (t.kind == TokenKind::Ident
&& (self.at_typed_declarator() || self.at_modport_port()))
};
if ansi {
let mut ports = Vec::new();
loop {
ports.push(self.parse_ansi_port()?);
if let Some(last) = ports.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = ports.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 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();
self.expect_sym(")")?;
// A trailing comment on the closing line belongs to the last
// port — but only when the header did not write a `;` right
// after the `)`. `module m (input a) /*c*/ ;` writes its comment
// in the *header's* gap, and printing it back inside the parens
// moves it across the `)`.
if !self.cur().is_sym(";") {
if let Some(last) = ports.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
}
Ok((PortList::Ansi(ports), dangling, directives))
} else {
let mut ports = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
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, directives))
}
}
fn parse_ansi_port(&mut self) -> PResult<AnsiPort> {
let start = self.here();
let mut meta = self.take_meta();
let dir = {
let t = self.cur();
if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
Some(self.bump().text)
} else {
None
}
};
let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() };
let net = {
let t = self.cur();
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
if is_net || t.is_kw("var") {
Some(self.bump().text)
} else {
None
}
};
let ty = if self.at_modport_port() {
self.parse_modport_port_type()?
} else {
self.parse_opt_data_type()?
};
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(AnsiPort {
meta,
dir,
after_dir,
net,
ty,
before_name,
name,
name_span,
unpacked,
eq_comments,
default,
comma: false,
span,
})
}
/// Does the cursor sit on an interface port that names a modport,
/// `bus_if.mp bus` (IEEE 1800 §25.4)? Only a *port header* is spelled this
/// way — after an identifier anywhere else a `.` opens a member access —
/// so the shape is recognized here rather than in `parse_opt_data_type`.
pub(super) fn at_modport_port(&self) -> bool {
self.cur().kind == TokenKind::Ident
&& self.nth(1).is_sym(".")
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(3).kind == TokenKind::Ident
}
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
/// onto the interface name exactly as a `pkg::` qualifier is, so every
/// consumer that prints or scans a type name still sees one string.
pub(super) fn parse_modport_port_type(&mut self) -> PResult<DataType> {
let mut name = self.expect_ident()?;
self.expect_sym(".")?;
name.push('.');
name.push_str(&self.expect_ident()?);
Ok(DataType { name, ..DataType::default() })
}
}