Files
lucisv/crates/vlog_parser/src/parser/mod.rs
T
lucioandClaude Fable 5 9b93f33ae3 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]>
2026-09-02 21:13:32 -07:00

478 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Recursive-descent parser producing the AST in [`crate::ast`].
//!
//! Comment plumbing: [`Parser::bump`] moves any leading comments of a
//! consumed token into `pending_leading` and its trailing comment into
//! `pending_trailing`. Statements/items/list elements harvest those at
//! well-defined points; anything left over is folded into the next node's
//! leading comments so no comment is ever dropped.
//!
//! Depth limiting: recursive descent means input nesting becomes call
//! nesting, and a stack overflow aborts the process (it is not a catchable
//! panic). Every parse function that can recurse without consuming a bounded
//! number of tokens per level brackets itself with [`Parser::enter`] /
//! [`Parser::leave`], turning nesting past [`MAX_NESTING_DEPTH`] into an
//! ordinary [`ParseError`].
//!
//! Error tolerance: [`parse`] stops at the first error, which is what the
//! formatter needs. [`parse_tolerant`] shares this same grammar code but
//! recovers instead — see `docs/features/error-recovery/README.md`.
//!
//! Layout: this file holds the parser's state and entry points — [`Parser`]
//! and its budgets, `Rewind`, [`parse`] / [`parse_tolerant`] — and the few
//! grammar helpers every file shares (scoped names, labels). The grammar
//! itself is one `impl Parser` block per sibling file, cut by what a reader
//! would look for:
//!
//! | file | holds |
//! |---|---|
//! | `cursor` | the token cursor, spans, `expect`/`eat`, the comment plumbing |
//! | `recover` | tolerant-mode error recovery |
//! | `item` | the file and item loops, the keyword → item dispatch, packages, imports, DPI, generate |
//! | `module` | module/interface/program headers, ports, modports, clocking blocks |
//! | `decl` | data types, declarators, parameters, `typedef`/`enum`/`struct` |
//! | `tf` | `function`, `task` and `let` declarations |
//! | `instance` | continuous assigns, instantiations and connections, gates, `bind` |
//! | `stmt`, `keyword_stmt` | statements; the keyword → statement dispatch table |
//! | `expr`, `primary` | the operator grammar; its leaves and argument lists |
//! | `class`, `covergroup` | classes with their constraints; covergroups |
//! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar |
//! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode |
//! | `split` | conditional-directive split recovery |
//! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers |
//!
//! Tests live in `tests/`, one file per grammar file they exercise.
use crate::ast::*;
use crate::span::TextRange;
use crate::token::{Comment, Token, TokenKind};
mod assertion;
mod class;
mod covergroup;
mod cursor;
mod decl;
mod directive;
mod expr;
mod instance;
mod item;
mod keyword_stmt;
mod module;
mod primary;
mod recover;
mod split;
mod stmt;
mod sva;
mod tf;
mod verbatim;
pub(crate) use recover::error_file;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone)]
pub struct ParseError {
pub line: u32,
pub col: u32,
pub message: String,
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
impl std::error::Error for ParseError {}
/// An error [`parse_tolerant`] recovered from, in the same words a
/// [`ParseError`] would have used plus the byte range it points at.
#[derive(Debug, Clone)]
pub struct ParseDiagnostic {
/// What went wrong, e.g. ``expected `;` (found "endmodule")``.
pub message: String,
/// 1-based line of the token the parser gave up on.
pub line: u32,
/// 1-based column (in bytes) of that token.
pub col: u32,
/// Byte extent of that token; empty at end of file.
pub span: TextRange,
}
impl std::fmt::Display for ParseDiagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
type PResult<T> = Result<T, ParseError>;
const TYPE_KEYWORDS: &[&str] = &[
"logic",
"reg",
"bit",
"byte",
"shortint",
"int",
"longint",
"integer",
"time",
"realtime",
"real",
"shortreal",
"string",
"chandle",
"event",
"void",
];
const NET_KEYWORDS: &[&str] =
&["wire", "tri", "tri0", "tri1", "wand", "wor", "trireg", "supply0", "supply1", "uwire"];
const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
/// How deeply constructs may nest before the parser gives up.
///
/// Chosen from measured stack use, not from taste: nested statements are the
/// most expensive family at ~94 KiB of stack per level in an unoptimized
/// build, so the whole pipeline on an input that trips the limit peaks at
/// ~5.9 MiB there and ~0.8 MiB in an optimized build. That budget is only
/// safe on a thread big enough to hold it, which is what
/// [`PARSE_STACK_SIZE`] names — this limit bounds how *many* levels run, not
/// what one costs. Real RTL nests roughly an order of magnitude less than
/// this; see `docs/features/recursion-limit/README.md`.
pub const MAX_NESTING_DEPTH: u32 = 64;
/// How much stack a thread that parses must be given.
///
/// [`MAX_NESTING_DEPTH`] turns over-deep input into a parse error instead of
/// a stack overflow, but only on a thread that can hold the levels it *does*
/// allow: the guard fires at level 64, and reaching level 64 costs stack. On
/// a smaller thread the overflow happens first, and a stack overflow is an
/// abort, not a `Result` — the whole process dies. So the stack has to fit
/// the limit; the limit is not lowered to fit some thread's stack.
///
/// [`MAX_CHAIN_LENGTH`] is the other half of what has to fit: it bounds AST
/// depth the same way, and since 2026-08-29 it, not nesting, sets the peak.
///
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
/// format → verify) over every nesting and chain family, on input sized to
/// trip a limit or to sit exactly at it: **~9.7 MiB unoptimized, ~0.8 MiB
/// optimized** — a maximal postfix chain inside statement nesting. 32 MiB is
/// that with 3.3× to spare, which is the margin this wants: unoptimized frame
/// sizes drift upward with the compiler — the nesting worst case measured
/// ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28 on rustc 1.97 — and there
/// is no recoverable failure mode to fall back to.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
/// `rayon::ThreadPoolBuilder::new().stack_size(PARSE_STACK_SIZE)`. Thread
/// stacks are committed by the OS a page at a time, so an unused one costs
/// address space rather than memory. `docs/features/recursion-limit/README.md`
/// lists every site.
pub const PARSE_STACK_SIZE: usize = 32 * 1024 * 1024;
/// How many links a left-nested chain may add to the tree on one path.
///
/// Some constructs are parsed by a loop rather than by recursion — postfix
/// segments (`a.b`, `a::b`, `a[i]`, `a(x)`, `a++`) and binary/`inside`
/// operator chains (`a + b + c`) — but each iteration still wraps what came
/// before in another AST layer, which the *formatter* then recurses over.
/// They therefore get their own budget: it is accumulated along a path the
/// same way [`MAX_NESTING_DEPTH`] is, so total AST depth stays bounded by
/// the two limits together no matter how chains and nesting are combined.
///
/// It is much larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap
/// — ~9.2 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement — and because long flat chains are the one deep shape real
/// RTL genuinely produces. 256 was not enough for real code: OpenTitan's
/// generated register files build one `|` chain per register file, and the
/// largest (`pinmux_reg_top.sv`) needs **567** links, so seven real files were
/// rejected. 1024 is 1.8× the largest chain the whole 3,943-file tree
/// contains, where only two files pass 512 and only seven pass 256.
///
/// Unlike raising [`MAX_NESTING_DEPTH`], raising this does not change which
/// *nesting* a file may use — but it is no longer free on the stack: at 1024
/// a maximal postfix chain peaks at ~9.4 MiB unoptimized, past the ~5.9 MiB
/// maximal nesting costs, so this limit now sets the worst case
/// [`PARSE_STACK_SIZE`] is measured against. See
/// `docs/features/recursion-limit/README.md`.
pub const MAX_CHAIN_LENGTH: u32 = 1024;
pub struct Parser<'a> {
tokens: Vec<Token>,
pos: usize,
pending_leading: Vec<Comment>,
pending_trailing: Vec<Comment>,
/// Currently open nested constructs; see [`MAX_NESTING_DEPTH`].
depth: u32,
/// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`].
links: u32,
/// Conditional-compilation regions open **at item scope** at the cursor:
/// one per `` `ifdef `` / `` `ifndef `` that stood as an item and has not
/// been closed by an `` `endif `` standing as an item.
///
/// Kept as running state because the split-conditional recovery must know
/// whether a closing directive closes anything at all — a stray
/// `` `endif `` is broken input, not a split. Maintained by exactly two
/// places, [`Parser::note_item_conditional`] and
/// [`Parser::split_conditional_item`]; see the former's doc for why it is
/// *not* maintained in [`Parser::bump`].
open_conds: u32,
/// Recover from errors instead of returning them; see [`parse_tolerant`].
tolerant: bool,
/// The text the tokens were lexed from, in both modes: recovery copies a
/// skipped range into an error node out of it, and so do the verbatim
/// class-scope blocks.
source: &'a str,
/// Errors recovered from, in source order. Always empty in strict mode.
diagnostics: Vec<ParseDiagnostic>,
/// Constraint bodies that did not fit the constraint grammar and were
/// captured verbatim instead; see [`SourceFile::constraint_fallbacks`].
constraint_fallbacks: u32,
/// Covergroups parsed into a [`ItemKind::Covergroup`], and covergroups
/// that did not fit the grammar and were captured verbatim instead; see
/// [`SourceFile::covergroups`].
covergroups: u32,
covergroup_fallbacks: u32,
/// `property`/`sequence` declarations and concurrent assertions parsed
/// into real nodes, and the ones that did not fit the SVA grammar and
/// were captured verbatim instead; see [`SourceFile::assertions`].
prop_seq_decls: u32,
prop_seq_fallbacks: u32,
assertions: u32,
assertion_fallbacks: u32,
/// While a covergroup bin's spec is being read, a postfix `with ( ... )`
/// is the **bin's** own filter (IEEE 1800 §19.5.1.1), not an array
/// method's iterator argument, so the expression parser must stop in
/// front of it. Set and cleared around that one operand, and never left
/// set on an error path.
no_with: bool,
/// While a `property` / `sequence` formal list is being read, `sequence`
/// and `property` are *type* spellings (IEEE 1800 §16.8's
/// `property_formal_type`), not the keywords that open a declaration.
/// Set and cleared around that one list, and never left set on an error
/// path. The sibling of [`Parser::no_with`], for the same reason.
sva_formals: bool,
/// The comments written in the gap before the `;` that ends the statement
/// currently being parsed — `x = 1 /* inclusive */ ;`.
///
/// The `;` is consumed in a dozen places (some of which read it to decide
/// the statement's *shape*), so the gap is handed up here instead of
/// through a dozen return types, and [`Parser::parse_stmt_inner`] moves it
/// onto [`Stmt::before_semi`] — the single owner of that gap, the way
/// `ConstraintItem::before_semi` is of a constraint item's. Cleared before
/// every statement kind is parsed, so nothing can leak from one statement
/// to the next.
semi_comments: Vec<Comment>,
}
/// Everything a speculative parse may move, so that a failed one can be put
/// back exactly where it started.
///
/// Only [`Parser::parse_constraint`], [`Parser::parse_with_constraint`] and
/// [`Parser::parse_covergroup`] use it, and only to retry the *same* bytes
/// down the pre-existing verbatim path. The token vector's own `leading` buckets are deliberately not
/// snapshotted: a retry that drained one has already decided to swallow those
/// bytes whole, and `verbatim_since` drops every comment that falls inside
/// the captured span.
struct Rewind {
pos: usize,
pending_leading: Vec<Comment>,
pending_trailing: Vec<Comment>,
depth: u32,
links: u32,
open_conds: u32,
diags: usize,
}
/// Parse a token stream, stopping at the first error.
///
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
///
/// Recurses with input nesting: call this only on a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
/// instead of returning `Err`.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
}
/// Parse a token stream that may be broken, recording errors instead of
/// failing.
///
/// The unparsable parts of the file become [`ItemKind::Error`] /
/// [`StmtKind::Error`] leaves holding the source text they cover, so the tree
/// still spans the whole file. `source` must be the exact text `tokens` were
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
/// the diagnostics are empty.
///
/// Same stack requirement as [`parse`]: needs a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
/// parses of the same over-deep input overflow at the same depth.
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
let mut p = Parser::new(tokens, source, true);
match p.parse_source_file() {
Ok(file) => (file, p.diagnostics),
// Unreachable in practice: every error path inside a file body is
// recovered. Rather than assert that, fall back to one error item
// covering the file, which is what a lex-level failure gets too.
Err(e) => {
let span = TextRange::new(0, source.len() as u32);
let diag = ParseDiagnostic { message: e.message, line: e.line, col: e.col, span };
let mut diagnostics = p.diagnostics;
diagnostics.push(diag);
(error_file(source), diagnostics)
}
}
}
/// Where an item — or a statement — started, for the recovery that may have to
/// replace it whole.
struct ItemMark {
/// Index of the construct's first token, past its attributes.
pos: usize,
/// Conditional regions open at that token.
conds: u32,
/// Diagnostics recorded before the item ran; a replaced parse's notes are
/// dropped back to this length (tolerant mode only — strict has none).
diags: usize,
}
/// True when `t` is a plain identifier spelling exactly `word`.
///
/// The constraint sub-grammar's four operator words — `soft`, `dist`,
/// `solve`, `before` — are read through this rather than reserved in
/// `token.rs`, the way `restrict` is: see
/// `docs/features/constraint-bodies/README.md`.
fn word_at(t: &Token, word: &str) -> bool {
t.kind == TokenKind::Ident && t.text == word
}
/// Move the comments written at or after byte `gap` out of `queue` and onto
/// `out`, in source order, leaving the earlier ones queued where they were.
fn take_since(queue: &mut Vec<Comment>, gap: u32, out: &mut Vec<Comment>) {
for c in std::mem::take(queue) {
if c.span.start >= gap {
out.push(c);
} else {
queue.push(c);
}
}
}
/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep
/// a name in a `String` field store it as.
fn split_label(name: Option<Name>) -> (Option<String>, Option<TextRange>) {
match name {
Some(n) => (Some(n.text), Some(n.span)),
None => (None, None),
}
}
impl<'a> Parser<'a> {
pub(super) fn new(tokens: Vec<Token>, source: &'a str, tolerant: bool) -> Self {
Parser {
tokens,
pos: 0,
pending_leading: Vec::new(),
pending_trailing: Vec::new(),
depth: 0,
links: 0,
open_conds: 0,
tolerant,
source,
diagnostics: Vec::new(),
constraint_fallbacks: 0,
covergroups: 0,
covergroup_fallbacks: 0,
prop_seq_decls: 0,
prop_seq_fallbacks: 0,
assertions: 0,
assertion_fallbacks: 0,
no_with: false,
sva_formals: false,
semi_comments: Vec::new(),
}
}
/// The `: name` written after a `begin`/`fork`, or after a closing
/// keyword (`end`, `join`, `endfunction`, ...), if present. Kept on the
/// node so the formatter can print it back.
pub(super) fn parse_label(&mut self) -> PResult<Option<Name>> {
Ok(self.parse_label_with()?.1)
}
/// The same, plus the comments written in the label's two gaps
/// (`endgroup /*a*/ : /*b*/ cg`). Every construct that keeps a label
/// keeps these beside it, so neither comment drifts across the `:`.
pub(super) fn parse_label_with(&mut self) -> PResult<(Box<LabelComments>, Option<Name>)> {
let before_colon = self.gap_before(":");
if !self.eat_sym(":") {
return Ok((Box::default(), None));
}
let after_colon = self.take_gap();
let name = self.expect_name()?;
Ok((Box::new(LabelComments { before_colon, after_colon }), Some(name)))
}
/// A method name, with the `my_class::` scope of an out-of-body
/// definition split off so the returned [`Name`] is only the method's own.
pub(super) fn parse_method_name(&mut self) -> PResult<(Vec<ScopeSeg>, Name)> {
let mut name = self.expect_name()?;
let mut scope: Vec<ScopeSeg> = Vec::new();
while self.cur().is_sym("::") {
let before_sep = self.take_gap();
self.bump();
let after_sep = self.take_gap();
let next = self.expect_name()?;
scope.push(ScopeSeg { name, before_sep, after_sep });
name = next;
}
Ok((scope, name))
}
/// [`Parser::push_scope_segment`]'s `.` twin, for the hierarchical paths
/// a `bind`'s `: instance, list` glues into one name. Same rule, same
/// reason: whitespace is an escaped identifier's only terminator, so
/// `\my-inst .u_core` must not come back as `\my-inst.u_core`.
pub(super) fn push_path_segment(joined: &mut String, segment: &str) {
if joined.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
joined.push(' ');
}
joined.push('.');
joined.push_str(segment);
}
/// Append `::` plus the next segment to a joined scoped name, keeping the
/// whitespace an escaped segment needs to terminate.
///
/// `\my-pkg ::\state-t` is three tokens; joined tightly it reprints as
/// `\my-pkg::\state-t`, which is one — the corruption the safety net had
/// to catch before this round (`docs/topo.md` §2.9-21). Whitespace is an
/// escaped identifier's only terminator, so it is part of the name as
/// written and belongs in the joined text.
pub(super) fn push_scope_segment(joined: &mut String, segment: &str) {
if joined.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
joined.push(' ');
}
joined.push_str("::");
joined.push_str(segment);
}
/// A `pkg::name` chain, returned as the joined text plus the
/// range covering the whole chain.
pub(super) fn parse_scoped_name(&mut self) -> PResult<(String, TextRange)> {
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
Ok((name, self.span_from(start)))
}
}