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]>
471 lines
21 KiB
Rust
471 lines
21 KiB
Rust
//! Data types and the declarations that use them.
|
|
//!
|
|
//! [`Parser::parse_opt_data_type`] is the one type grammar every position
|
|
//! shares (ports, parameters, declarators, casts, function returns); around
|
|
//! it stand the declarators, `parameter`/`localparam`, `typedef`, `enum` and
|
|
//! `struct`/`union` bodies, and the lookaheads that decide whether a name
|
|
//! at the cursor begins a declaration at all.
|
|
|
|
use super::item::MEMBER_QUALIFIERS;
|
|
use super::*;
|
|
|
|
impl<'a> Parser<'a> {
|
|
/// Parse a possibly-implicit data type. Stops before the declarator name.
|
|
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
|
|
let mut ty = DataType::default();
|
|
// `property p(sequence a, property b);` — inside a property's or a
|
|
// sequence's formal list, and nowhere else, the two keywords name a
|
|
// formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is
|
|
// an ordinary identifier and already reads as a user-defined type.
|
|
if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) {
|
|
ty.name = self.bump().text;
|
|
return Ok(ty);
|
|
}
|
|
// `virtual [interface] <iface>` — a virtual interface type reference
|
|
// (IEEE 1800 §25.9). It stands wherever a type does: a typedef's base
|
|
// type, a task/function argument, a variable. (A *declaration* reaches
|
|
// this function with the `virtual` already taken into
|
|
// `DataDecl::qualifiers`, so this only fires for the other positions.)
|
|
if self.cur().is_kw("virtual") {
|
|
self.bump();
|
|
ty.virt =
|
|
Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare });
|
|
// `virtual spi_if.tb sif` — a modport-qualified virtual interface
|
|
// type (IEEE 1800 §25.9, `spi_device/pre_dv/tb/spid_common.sv:563`).
|
|
// Glued onto the interface name exactly as an interface *port*'s
|
|
// modport is, so every consumer still sees one type-name string.
|
|
if self.at_modport_port() {
|
|
ty.name = self.parse_modport_port_type()?.name;
|
|
return Ok(ty);
|
|
}
|
|
}
|
|
let t = self.cur();
|
|
// An anonymous aggregate stands where a type name does (IEEE 1800
|
|
// §6.19, §7.2): `enum logic [1:0] {IDLE, STOP} state, state_next;`
|
|
// (clock_divider.sv:59), `struct packed { ... } s;`. The body is the
|
|
// same one `typedef` takes, so the two share a parser.
|
|
if t.is_kw("enum") {
|
|
ty.extra = Some(Box::new(TypeExtra::Enum(self.parse_enum_type()?)));
|
|
return Ok(ty);
|
|
}
|
|
if t.is_kw("struct") || t.is_kw("union") {
|
|
ty.extra = Some(Box::new(TypeExtra::Struct(self.parse_struct_type()?)));
|
|
return Ok(ty);
|
|
}
|
|
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
|
|
ty.name = self.bump().text;
|
|
} else if t.kind == TokenKind::Ident {
|
|
// User-defined type only if what follows still leaves an
|
|
// identifier for the declarator name.
|
|
if self.at_typed_declarator() {
|
|
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);
|
|
}
|
|
ty.name = name;
|
|
if self.at_type_params() {
|
|
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
|
|
}
|
|
}
|
|
}
|
|
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
|
|
ty.signing = Some(self.bump().text);
|
|
}
|
|
ty.packed = self.parse_dims()?;
|
|
Ok(ty)
|
|
}
|
|
|
|
pub(super) fn parse_dims(&mut self) -> PResult<Vec<Dim>> {
|
|
let mut dims = Vec::new();
|
|
while self.cur().is_sym("[") {
|
|
let start = self.here();
|
|
// A dimension owns the same five slots a postfix `[ ]` segment
|
|
// does, and for the same reason: nothing else is written where a
|
|
// comment inside the brackets could attach.
|
|
let mut comments =
|
|
SegmentComments { before_open: self.take_gap(), ..Default::default() };
|
|
self.bump();
|
|
comments.after_open = self.take_gap();
|
|
let kind = if self.cur().is_sym("]") {
|
|
// `[]` — a dynamic array.
|
|
comments.before_close = std::mem::take(&mut comments.after_open);
|
|
self.bump();
|
|
dims.push(Dim {
|
|
kind: DimKind::Dynamic,
|
|
comments: Box::new(comments),
|
|
span: self.span_from(start),
|
|
});
|
|
continue;
|
|
} else if self.cur().is_sym("*") && self.nth(1).is_sym("]") {
|
|
// `[*]` — a wildcard-keyed associative array.
|
|
self.bump();
|
|
DimKind::Wildcard
|
|
} else {
|
|
let a = self.parse_expr()?;
|
|
comments.before_op = self.gap_before(":");
|
|
let b = if self.eat_sym(":") {
|
|
comments.after_op = self.take_gap();
|
|
Some(self.parse_expr()?)
|
|
} else {
|
|
None
|
|
};
|
|
DimKind::Range { a, b }
|
|
};
|
|
comments.before_close = self.gap_before("]");
|
|
self.expect_sym("]")?;
|
|
dims.push(Dim { kind, comments: Box::new(comments), span: self.span_from(start) });
|
|
}
|
|
Ok(dims)
|
|
}
|
|
|
|
pub(super) fn parse_type_expr(&mut self) -> PResult<Expr> {
|
|
let start = self.here();
|
|
let ty = self.parse_type_ref()?;
|
|
if ty.is_implicit() {
|
|
// Nothing that can be a type stands here. `parse_type_ref` takes a
|
|
// bare identifier, so whatever is at the cursor is not one and
|
|
// `expect_ident` always fails — naming the offending token the way
|
|
// this position has always named it.
|
|
self.expect_ident()?;
|
|
return self.error("expected a type");
|
|
}
|
|
Ok(self.expr_at(start, ExprKind::Type(ty)))
|
|
}
|
|
|
|
/// True when the cursor opens a parameterized type's `#( ... )`.
|
|
pub(super) fn at_type_params(&self) -> bool {
|
|
self.cur().is_sym("#") && self.nth(1).is_sym("(")
|
|
}
|
|
|
|
/// The `#( ... )` of a parameterized type or class reference, verbatim.
|
|
pub(super) fn parse_type_params(&mut self) -> PResult<RawText> {
|
|
let start = self.here();
|
|
let col = self.cur().col;
|
|
self.expect_sym("#")?;
|
|
self.expect_sym("(")?;
|
|
self.skip_balanced("(", ")")?;
|
|
Ok(self.verbatim_since(start, col))
|
|
}
|
|
|
|
/// Does the identifier at the cursor open a declaration whose type is a
|
|
/// user-defined name? True when a declarator identifier still follows it
|
|
/// past the optional `pkg::` chain, `#( ... )` overrides and packed
|
|
/// dimensions: `my_t x`, `pkg::my_t x`, `item #(A, B) req`,
|
|
/// `payload_t [NumOut-1:0][NumInp-1:0] out_data` (stream_xbar.sv:98).
|
|
///
|
|
/// This is what keeps `x[i] = 1;` an assignment: what follows the
|
|
/// brackets there is `=`, not a name.
|
|
pub(super) fn at_typed_declarator(&self) -> bool {
|
|
let mut p = self.pos;
|
|
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
|
|
p += 2;
|
|
}
|
|
let mut next = p + 1;
|
|
// A parameterized type puts `#( ... )` between the name and the
|
|
// declarator (`uvm_analysis_port #(bit [31:0]) port;`).
|
|
if self.tokens.get(next).is_some_and(|t| t.is_sym("#"))
|
|
&& self.tokens.get(next + 1).is_some_and(|t| t.is_sym("("))
|
|
{
|
|
next = self.scan_matching(next + 1, "(", ")");
|
|
}
|
|
while self.tokens.get(next).is_some_and(|t| t.is_sym("[")) {
|
|
next = self.scan_matching(next, "[", "]");
|
|
}
|
|
self.tokens.get(next).is_some_and(|t| t.kind == TokenKind::Ident)
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Declarations
|
|
// ------------------------------------------------------------------
|
|
|
|
pub(super) fn parse_param_decl(&mut self) -> PResult<ParamDecl> {
|
|
let kw = self.bump().text;
|
|
let after_kw = self.take_gap();
|
|
// `localparam type payload_t = logic [$clog2(NumReq)-1:0];` — a type
|
|
// parameter outside the `#( ... )` list
|
|
// (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
|
|
let is_type = self.eat_kw("type");
|
|
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
|
|
let declarators = self.parse_declarator_list(is_type)?;
|
|
Ok(ParamDecl { kw, after_kw, is_type, ty, declarators })
|
|
}
|
|
|
|
/// Parse declarators up to (but not consuming) the terminating `;`.
|
|
pub(super) fn parse_declarators(&mut self) -> PResult<Vec<Declarator>> {
|
|
self.parse_declarator_list(false)
|
|
}
|
|
|
|
/// Parse declarators; `type_init` makes each `= ...` a type rather than an
|
|
/// expression, which is what a `type` parameter's default is.
|
|
fn parse_declarator_list(&mut self, type_init: bool) -> PResult<Vec<Declarator>> {
|
|
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()?;
|
|
let unpacked = self.parse_dims()?;
|
|
let (eq_comments, init) = if type_init {
|
|
self.parse_eq_default(|p| p.parse_type_expr())?
|
|
} else {
|
|
self.parse_eq_default(|p| p.parse_expr())?
|
|
};
|
|
let span = self.span_from(start);
|
|
self.take_before_sep(&mut meta, ",");
|
|
let more = self.eat_sym(",");
|
|
// Harvested on the last declarator too: a comment written before
|
|
// the `;` (`logic x /* verilator split_var */;`) belongs to the
|
|
// declaration, and the `;` has not been consumed yet, so nothing
|
|
// written after it can be picked up here.
|
|
meta.trailing = self.take_trailing();
|
|
out.push(Declarator { meta, name, name_span, unpacked, eq_comments, init, span });
|
|
if !more {
|
|
break;
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub(super) fn parse_data_decl(&mut self) -> PResult<DataDecl> {
|
|
let mut net = None;
|
|
let mut qualifiers = Vec::new();
|
|
loop {
|
|
let t = self.cur();
|
|
if t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()) {
|
|
net = Some(self.bump().text);
|
|
} else if t.kind == TokenKind::Keyword && MEMBER_QUALIFIERS.contains(&t.text.as_str()) {
|
|
let was_virtual = t.is_kw("virtual");
|
|
let text = self.bump().text;
|
|
qualifiers.push(Qualifier { text, after: self.take_gap() });
|
|
// `virtual interface my_if h;` — the `interface` keyword is
|
|
// part of the qualifier, not a construct of its own, and is
|
|
// only ever legal directly after `virtual`.
|
|
if was_virtual && self.cur().is_kw("interface") {
|
|
let text = self.bump().text;
|
|
qualifiers.push(Qualifier { text, after: self.take_gap() });
|
|
}
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
let delay = if net.is_some() && self.cur().is_sym("#") {
|
|
self.bump();
|
|
Some(self.parse_delay_value()?)
|
|
} else {
|
|
None
|
|
};
|
|
// A declaration reaches here with its `virtual` already in
|
|
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
|
|
// fire: `virtual spi_if.tb tb_sif = sif.tb;`
|
|
// (`spi_device/pre_dv/tb/spid_jedec_tb.sv:32`) is recognized here
|
|
// instead, the way `parse_ansi_port` recognizes an interface port's.
|
|
let ty = if qualifiers.iter().any(|q| q.text == "virtual") && self.at_modport_port() {
|
|
self.parse_modport_port_type()?
|
|
} else {
|
|
self.parse_opt_data_type()?
|
|
};
|
|
let declarators = self.parse_declarators()?;
|
|
self.expect_sym(";")?;
|
|
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
|
|
}
|
|
|
|
pub(super) fn parse_port_decl(&mut self) -> PResult<PortDecl> {
|
|
let dir = self.bump().text;
|
|
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 = self.parse_opt_data_type()?;
|
|
let declarators = self.parse_declarators()?;
|
|
self.expect_sym(";")?;
|
|
Ok(PortDecl { dir, net, ty, declarators })
|
|
}
|
|
|
|
pub(super) fn parse_typedef(&mut self) -> PResult<Typedef> {
|
|
self.expect_kw("typedef")?;
|
|
let after_kw = self.take_gap();
|
|
let kind = if self.eat_kw("class") {
|
|
// Forward declaration: `typedef class my_class;` — no type to
|
|
// alias, just a name promised to exist later in the compilation.
|
|
TypedefKind::ForwardClass
|
|
} else if self.cur().is_kw("enum") {
|
|
TypedefKind::Enum(self.parse_enum_type()?)
|
|
} else if self.cur().is_kw("struct") || self.cur().is_kw("union") {
|
|
TypedefKind::Struct(self.parse_struct_type()?)
|
|
} else {
|
|
TypedefKind::Alias(self.parse_opt_data_type()?)
|
|
};
|
|
let before_name = self.take_gap();
|
|
let Name { text: name, span: name_span } = self.expect_name()?;
|
|
let unpacked =
|
|
if matches!(kind, TypedefKind::ForwardClass) { Vec::new() } else { self.parse_dims()? };
|
|
let before_semi = self.gap_before(";");
|
|
self.expect_sym(";")?;
|
|
Ok(Typedef { after_kw, before_name, name, name_span, unpacked, before_semi, kind })
|
|
}
|
|
|
|
/// `enum [base] { A, B = 2 }` — the cursor is on `enum` and stops on the
|
|
/// token after the closing `}`. Shared by `typedef enum ...` and by an
|
|
/// anonymous enum used as a type in place (IEEE 1800 §6.19).
|
|
fn parse_enum_type(&mut self) -> PResult<EnumType> {
|
|
self.expect_kw("enum")?;
|
|
let after_kw = self.take_gap();
|
|
// The base type may be a keyword (`logic [1:0]`) or a typedef'd name
|
|
// (`typedef enum action_mask_t {...}`, prim_count_pkg.sv:10).
|
|
let base = if self.cur().is_sym("{") { None } else { Some(self.parse_type_ref()?) };
|
|
let before_open = self.take_before_open("{");
|
|
self.expect_sym("{")?;
|
|
let (members, directives) = self.parse_enum_members(false)?;
|
|
let dangling = self.take_dangling();
|
|
self.expect_sym("}")?;
|
|
Ok(EnumType { after_kw, base, before_open, members, directives, dangling })
|
|
}
|
|
|
|
/// An `enum`'s member list, with the `` `ifdef``-style directives written
|
|
/// between the members.
|
|
///
|
|
/// The cursor starts just past the `{` and stops on the `}` that closes
|
|
/// it. `to_eof` swaps that closer for end of file, which is the only
|
|
/// difference between an enum body and an enum-member fragment — one
|
|
/// grammar, read by both (`docs/features/fragment-mode/README.md`).
|
|
pub(super) fn parse_enum_members(
|
|
&mut self,
|
|
to_eof: bool,
|
|
) -> PResult<(Vec<EnumMember>, Vec<ListDirective>)> {
|
|
let mut members = Vec::new();
|
|
let mut directives = Vec::new();
|
|
self.take_list_directives(&mut directives, 0);
|
|
loop {
|
|
if to_eof && self.at_eof() {
|
|
break;
|
|
}
|
|
let start = self.here();
|
|
let mut meta = self.take_meta();
|
|
let Name { text: name, span: name_span } = self.expect_name()?;
|
|
// `ReqPeriResetIdx[0:1]`, `OtbnDmem[16]` — the enum name range of
|
|
// IEEE 1800 §6.19 (`rstmgr_pkg.sv:72`, `chip_env_pkg.sv:88`).
|
|
let range = self.parse_dims()?;
|
|
let mut eq_comments = BinaryComments::default();
|
|
let value = if self.cur().is_sym("=") {
|
|
eq_comments.before = self.take_gap();
|
|
self.bump();
|
|
eq_comments.after = self.take_gap();
|
|
Some(self.parse_expr()?)
|
|
} else {
|
|
None
|
|
};
|
|
let span = self.span_from(start);
|
|
self.take_before_sep(&mut meta, ",");
|
|
let comma = self.eat_sym(",");
|
|
meta.trailing = self.take_trailing();
|
|
members.push(EnumMember {
|
|
meta,
|
|
name,
|
|
name_span,
|
|
range,
|
|
eq_comments: Box::new(eq_comments),
|
|
value,
|
|
comma,
|
|
span,
|
|
});
|
|
let dirs = self.take_list_directives(&mut directives, members.len());
|
|
let at_close = if to_eof { self.at_eof() } else { self.cur().is_sym("}") };
|
|
if (!comma && !dirs.any) || (dirs.any && at_close) {
|
|
break;
|
|
}
|
|
}
|
|
Ok((members, directives))
|
|
}
|
|
|
|
/// `struct|union [packed] [signing] { members }` — the cursor is on the
|
|
/// keyword and stops on the token after the closing `}`. Shared by
|
|
/// `typedef struct ...`, an anonymous struct used as a type in place, and
|
|
/// a struct member whose own type is an inline struct (uart_reg_pkg.sv:30).
|
|
fn parse_struct_type(&mut self) -> PResult<StructType> {
|
|
let kw = self.bump().text;
|
|
let mut header_comments =
|
|
StructHeaderComments { after_kw: self.take_gap(), ..Default::default() };
|
|
// `union tagged [packed] { ... }` (IEEE 1800 §7.3.2): the discriminated
|
|
// union. `tagged` is matched by text rather than reserved, for the
|
|
// reason [`word_at`] gives, and only the *flag* is modelled — the
|
|
// `tagged Valid 5` expression and `case (x) matches` are a pattern
|
|
// grammar of their own and are still a clean parse error.
|
|
let tagged = word_at(self.cur(), "tagged");
|
|
if tagged {
|
|
self.bump();
|
|
header_comments.after_tagged = self.take_gap();
|
|
}
|
|
let packed = self.eat_kw("packed");
|
|
if packed {
|
|
header_comments.after_packed = self.take_gap();
|
|
}
|
|
let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
|
|
let word = self.bump().text;
|
|
header_comments.after_signing = self.take_gap();
|
|
Some(word)
|
|
} else {
|
|
None
|
|
};
|
|
self.expect_sym("{")?;
|
|
let mut members = Vec::new();
|
|
while !self.cur().is_sym("}") && !self.at_eof() {
|
|
let start = self.here();
|
|
let mut meta = self.take_meta();
|
|
let mut qualifiers = Vec::new();
|
|
while self.cur().is_kw("rand") || self.cur().is_kw("randc") {
|
|
let text = self.bump().text;
|
|
qualifiers.push(Qualifier { text, after: self.take_gap() });
|
|
}
|
|
let ty = self.parse_opt_data_type()?;
|
|
let declarators = self.parse_declarators()?;
|
|
self.expect_sym(";")?;
|
|
let span = self.span_from(start);
|
|
meta.trailing = self.take_trailing();
|
|
members.push(StructMember { meta, qualifiers, ty, declarators, span });
|
|
}
|
|
let dangling = self.take_dangling();
|
|
self.expect_sym("}")?;
|
|
Ok(StructType {
|
|
kw,
|
|
header_comments: Box::new(header_comments),
|
|
tagged,
|
|
packed,
|
|
signing,
|
|
members,
|
|
dangling,
|
|
})
|
|
}
|
|
|
|
/// A data type in a position where one is *required* — an enum base type,
|
|
/// a `type` parameter's default. Unlike [`Parser::parse_opt_data_type`],
|
|
/// which only takes an identifier when a declarator name follows it, a
|
|
/// bare `my_type_t` here is the whole type.
|
|
fn parse_type_ref(&mut self) -> PResult<DataType> {
|
|
let ty = self.parse_opt_data_type()?;
|
|
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
|
|
return Ok(ty);
|
|
}
|
|
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);
|
|
}
|
|
let mut ty = DataType { name, ..DataType::default() };
|
|
if self.at_type_params() {
|
|
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
|
|
}
|
|
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
|
|
ty.signing = Some(self.bump().text);
|
|
}
|
|
ty.packed = self.parse_dims()?;
|
|
Ok(ty)
|
|
}
|
|
}
|