Files
lucisv/crates/vlog_parser/src/parser/decl.rs
T
lucioandClaude Fable 5.1 4d59e80568
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
Type-name spans on the AST; vlog_semantic/src/scan.rs retired
TODO §47 (docs/features/type-name-spans). Closes topo §2.9-2.

`DataType` carries `name_start` (a `u32` in its existing padding, so
`Expr` stays at its 96-byte pin) and derives `name_span()` and
`segments()` — the `::`/`.` split from the span's own text, with a
leading escaped identifier read to its terminator first. Five parser
construction sites set it; an implicit type gets the empty range at the
position its name would have had. `StmtKind::Disable { name, name_span }`.
The binder walks `ty.segments()` and verifies every segment's range
against the source before recording it (`exact_or_empty`); a segment that
does not read back is recorded with the empty range, never dropped, so
the census's `unplaced` counter is the alarm a join regression would
move (review rework of QA's MEDIUM). `scan.rs` deleted; `bind_data_type`
lost its `window` and ten call sites their window arithmetic.

Census unchanged in every field (860 files, 27 486 symbols, 103 870
references, 1 197 unresolved, 0 unplaced); 0 of 860 corpus files differ;
200/200 opentitan definition/hover/typeDefinition answers identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 09:24:19 -05:00

500 lines
22 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> {
/// A type with nothing written for it, spanning the empty range at the
/// cursor: what a `parameter type T` and an implicit `input [7:0] x`
/// both carry. Distinct from [`DataType::default`] only in that its
/// `name_span` points at the source rather than at offset zero.
pub(super) fn implicit_type(&self) -> DataType {
DataType { name_start: self.here(), ..DataType::default() }
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
// An implicit type writes no name at all, so its `name_span` is the
// empty range where a name would have gone: right here, before
// anything of the type has been consumed.
let mut ty = self.implicit_type();
// `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_start = self.here();
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() {
let head = self.parse_modport_port_type()?;
ty.name = head.name;
ty.name_start = head.name_start;
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_start = self.here();
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 (name, span) = self.parse_scoped_name()?;
ty.name = name;
ty.name_start = span.start;
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 { self.implicit_type() } 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 before = self.parse_net_delay(net.is_some(), false)?;
// 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()?
};
// IEEE 1800 §6.7 writes the delay *here*, after the data type
// (`wire [31:0] #0.1 x = y;`, `pulp_riscv_dbg/tb/unused/SimDTM.sv:38`);
// everything else in the corpus writes it before. Either is read and
// printed back where it stood, but a declaration with one on each
// side is not a shape the LRM has.
let after = self.parse_net_delay(net.is_some(), true)?;
let delay = match (before, after) {
(Some(_), Some(_)) => {
return self.error("a net delay is written before or after the type, not both")
}
(before, after) => before.or(after),
};
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
}
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
/// `#(1:2:3)`. Only a net declaration may carry one, so `is_net` gates
/// the whole read — a `#` anywhere else belongs to whoever comes next.
fn parse_net_delay(&mut self, is_net: bool, after_type: bool) -> PResult<Option<NetDelay>> {
if !is_net || !self.cur().is_sym("#") {
return Ok(None);
}
// The `#` is written, so the gap in front of it is the delay's own:
// `wire /* c */ #5 w;`. Taken only here — when the read does not
// happen the gap belongs to whatever comes next.
let before_hash = self.take_gap();
self.bump();
let after_hash = self.take_gap();
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
}
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 (name, span) = self.parse_scoped_name()?;
let mut ty = DataType { name, name_start: span.start, ..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)
}
}