Files
lucisv/crates/vlog_parser/src/ast/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

587 lines
23 KiB
Rust

//! Data types, dimensions and the declarations that carry them: variables and
//! nets, parameters, typedefs, enums and structs, and function/task/let
//! declarations with their port lists.
use super::*;
/// A data type: keyword or user-defined name, plus signing and packed dims.
/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole
/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`.
/// [`DataType::name_span`] says where it is written and
/// [`DataType::segments`] splits it.
#[derive(Debug, Clone, Default)]
pub struct DataType {
/// The `virtual` / `virtual interface` prefix of a virtual interface type
/// reference, as written (IEEE 1800 §25.9): `virtual clk_rst_if`,
/// `virtual interface bus_if`. Legal in every type position — a typedef's
/// base type, a task/function argument, a variable declaration.
///
/// A *declaration* keeps it in [`DataDecl::qualifiers`] instead, where the
/// rest of the member qualifiers already live; this field carries the
/// positions that have no qualifier list of their own.
///
/// A one-byte enum rather than the text, for the same reason `extra` is
/// boxed: every `Expr` carries a `DataType` through [`ExprKind::Type`],
/// so a rare field must not widen the common case.
pub virt: Option<VirtualKw>,
pub name: String,
/// Where [`DataType::name`] is written. Read it through
/// [`DataType::name_span`], which pairs it with the name's own length.
///
/// Four bytes rather than a whole [`TextRange`] because they fit in the
/// padding this struct already has: an eight-byte span pushes `DataType`
/// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the
/// 96-byte pin in `size_pins`.
pub(crate) name_start: u32,
/// The rare tail of a type: parameterization or an anonymous aggregate
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
/// [`DataType::inline`].
///
/// Boxed — and the two spellings share the one box — to keep `DataType`,
/// and through [`ExprKind::Type`] every `Expr`, small.
pub extra: Option<Box<TypeExtra>>,
pub signing: Option<String>,
pub packed: Vec<Dim>,
}
impl DataType {
pub fn is_implicit(&self) -> bool {
self.virt.is_none()
&& self.name.is_empty()
&& self.extra.is_none()
&& self.signing.is_none()
&& self.packed.is_empty()
}
/// The `#( ... )` of a parameterized type reference, if one was written.
pub fn params(&self) -> Option<&RawText> {
match self.extra.as_deref() {
Some(TypeExtra::Params(p)) => Some(p),
_ => None,
}
}
/// The anonymous aggregate that *is* this type, if one was written.
pub fn inline(&self) -> Option<&TypeExtra> {
match self.extra.as_deref() {
Some(e @ (TypeExtra::Enum(_) | TypeExtra::Struct(_))) => Some(e),
_ => None,
}
}
/// The byte range [`DataType::name`] occupies: `src[name_span] == name`
/// for every name the source spells the way the AST joined it, which is
/// every name but the pathological spacings [`DataType::segments`]
/// documents. An implicit type has no name, so this is the empty range at
/// the position a name would have been written — the same convention an
/// unnamed DPI formal's `name_span` uses.
pub fn name_span(&self) -> TextRange {
TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32))
}
/// The `::`- and `.`-separated segments of the name — `pkg`, `item` of
/// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range
/// it occupies.
///
/// Derived from [`DataType::name_span`] and the name's own text: the
/// construct is never rescanned. So a source that spells the name
/// differently from the way the parser joined it — an escaped segment
/// terminated by a newline rather than a space, a `bus_if . mp` written
/// apart — hands back ranges that do not slice back to their segment.
/// A caller that must not mislocate checks the slice and drops the
/// segment; `vlog_semantic`'s binder does.
pub fn segments(&self) -> impl Iterator<Item = (&str, TextRange)> + '_ {
let base = self.name_start;
let mut rest = Some((0usize, self.name.as_str()));
std::iter::from_fn(move || {
let (at, text) = rest.take()?;
let (seg, tail) = match separator(text) {
Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))),
None => (text, None),
};
rest = tail;
let start = base.saturating_add(at as u32);
Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32))))
})
.filter(|(seg, _): &(&str, TextRange)| !seg.is_empty())
}
}
/// Where the first `::`/`.` that separates two name segments starts, and how
/// many bytes it is.
///
/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments,
/// not three), so one that leads the text runs to its terminating whitespace —
/// which the parser keeps in the joined name (§29) — before the search for a
/// separator begins.
fn separator(text: &str) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut i = 0;
if bytes.first() == Some(&b'\\') {
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
// The terminator belongs to the segment; anything else is a separator.
i = (i + 1).min(bytes.len());
}
while i < bytes.len() {
match bytes[i] {
b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)),
b'.' => return Some((i, 1)),
_ => i += 1,
}
}
None
}
/// What a type carries beyond its name, signing and packed dimensions. A type
/// never has two of these at once — an anonymous aggregate has no name to
/// parameterize — so they share one box on [`DataType`].
#[derive(Debug, Clone)]
pub enum TypeExtra {
/// The `#( ... )` of a parameterized type reference, verbatim:
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so lucisv
/// reproduces them as written instead of modelling a second grammar.
Params(RawText),
/// An anonymous enum standing where a type name would:
/// `enum logic [1:0] {IDLE, STOP} state;`.
Enum(EnumType),
/// An anonymous struct or union standing where a type name would:
/// `struct packed { ... } s;`.
Struct(StructType),
}
/// How a virtual interface type reference is spelled. The `interface` keyword
/// is optional (IEEE 1800 §25.9) and both spellings occur, so which one was
/// written is recorded and printed back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VirtualKw {
/// `virtual bus_if h;`
Bare,
/// `virtual interface bus_if h;`
Interface,
}
impl VirtualKw {
/// The prefix as it is written, `interface` keyword included.
pub fn text(self) -> &'static str {
match self {
VirtualKw::Bare => "virtual",
VirtualKw::Interface => "virtual interface",
}
}
}
/// A dimension: `[expr]`, `[a:b]`, `[]`, or `[*]`.
#[derive(Debug, Clone)]
pub struct Dim {
pub kind: DimKind,
/// Comments written in the dimension's own slots — before the `[`, just
/// inside it, around the `:` and before the `]`. Boxed for the reason
/// [`SegmentComments`] gives.
pub comments: Box<SegmentComments>,
/// Code extent including the brackets.
pub span: TextRange,
}
/// What stands between a dimension's brackets.
#[derive(Debug, Clone)]
pub enum DimKind {
/// `[expr]` or `[a:b]` — also `[$]`, `[$:N]` (a bare `$` is an ordinary
/// expression) and `[string]` / `[key_t]` (a type or name used as an
/// associative-array key parses as an expression).
Range { a: Expr, b: Option<Expr> },
/// `[]` — a dynamic array.
Dynamic,
/// `[*]` — a wildcard-keyed associative array.
Wildcard,
}
#[derive(Debug)]
pub struct Typedef {
/// Comments written between the `typedef` keyword and the base type
/// (`typedef /*c*/ struct packed { … } w_t;`).
pub after_kw: Vec<Comment>,
/// Comments written between the base type and the new type's name
/// (`… } /*c*/ w_t;`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written between the name and the `;`.
pub before_semi: Vec<Comment>,
pub kind: TypedefKind,
}
#[derive(Debug)]
pub enum TypedefKind {
Alias(DataType),
Enum(EnumType),
Struct(StructType),
/// A forward declaration: `typedef class my_class;`
ForwardClass,
}
#[derive(Debug, Clone)]
pub struct EnumType {
/// Comments written between the `enum` keyword and its base type
/// (`enum /*c*/ logic [1:0] { … }`).
pub after_kw: Vec<Comment>,
pub base: Option<DataType>,
/// Comments written between the base type and the `{`.
pub before_open: Vec<Comment>,
pub members: Vec<EnumMember>,
/// Directives written between the members, in source order.
pub directives: Vec<ListDirective>,
pub dangling: Vec<Comment>,
}
#[derive(Debug, Clone)]
pub struct EnumMember {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// The enum name range of IEEE 1800 §6.19 — `Name[N]` or `Name[hi:lo]`,
/// which declares a run of sequentially-valued members. One dimension is
/// all the LRM allows; it is kept as an ordinary [`Dim`] so the existing
/// dimension parser and printer serve it, and it is printed back tight
/// against the name because it is part of the name, not a layout choice.
pub range: Vec<Dim>,
/// Comments written on either side of the `=` of a member's value
/// (`B /*c*/ = /*c*/ 2`).
pub eq_comments: Box<BinaryComments>,
pub value: Option<Expr>,
/// True when a `,` followed this element in the source; see
/// [`NonAnsiPort::comma`].
pub comma: bool,
/// Code extent of the member.
pub span: TextRange,
}
#[derive(Debug, Clone)]
pub struct StructType {
/// "struct" or "union"
pub kw: String,
/// Comments written between each word of the `struct packed signed`
/// header run and the next, and between the last of them and the `{`.
/// One entry per gap, in source order: after the keyword, after
/// `tagged`, after `packed`, after the signing word.
pub header_comments: Box<StructHeaderComments>,
/// The `tagged` of `union tagged { ... }` (IEEE 1800 §7.3.2) — a
/// discriminated union. Carried and printed; lucisv models no tag
/// semantics, and the `tagged Valid 5` expression form that goes with it
/// is a pattern grammar the parser still rejects.
pub tagged: bool,
pub packed: bool,
pub signing: Option<String>,
pub members: Vec<StructMember>,
pub dangling: Vec<Comment>,
}
#[derive(Debug, Clone)]
pub struct StructMember {
pub meta: Meta,
/// `rand` / `randc` written before the member's type. The LRM allows the
/// randomization qualifiers only on a class property, but vendor tools
/// accept them on a plain struct member and real code uses them
/// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no
/// randomization semantics, so the words are simply carried and printed.
pub qualifiers: Vec<Qualifier>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
/// Code extent of the member, its `;` included.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ParamDecl {
/// `parameter` or `localparam`
pub kw: String,
/// Comments written between that keyword and the type
/// (`localparam /*c*/ int N = 4;`).
pub after_kw: Vec<Comment>,
/// A type parameter: `localparam type payload_t = logic [7:0];`. The
/// declarator's `init` is then an [`ExprKind::Type`], not a value.
pub is_type: bool,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
/// A net delay and the side of the data type it was written on.
///
/// IEEE 1800 §6.7 puts `delay3` *after* the type —
/// `wire [31:0] #0.1 x = y;`, which is how
/// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it — while the spelling
/// the rest of the corpus uses puts it between the net keyword and the type.
/// Both are read, never both at once, and printed back where they were
/// written: moving a delay across the type reorders tokens, which
/// `verify.rs` rightly refuses.
#[derive(Debug)]
pub struct NetDelay {
/// Comments written between whatever precedes the delay and its `#`:
/// the `/* c */` of `wire /* c */ #5 w;` and of
/// `wire [7:0] /* c */ #1 w;`. Without a slot here the comment would be
/// printed one node later and `verify.rs` would refuse the file.
pub before_hash: Vec<Comment>,
/// Comments written between the `#` and the delay value — the delay's
/// other gap, and the one the gap fuzzer asks about the moment the
/// first one has an owner.
pub after_hash: Vec<Comment>,
/// The delay itself: the `5` of `wire #5 w;`.
pub expr: Expr,
/// True when it stood between the data type and the declarators.
pub after_type: bool,
}
#[derive(Debug)]
pub struct DataDecl {
/// Net type (`wire`, `tri`, ...) if any.
pub net: Option<String>,
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
/// `wire [31:0] #0.1 x = y;`.
pub delay: Option<NetDelay>,
/// Qualifiers written before the type, in source order: `var`,
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
/// virtual-interface property.
pub qualifiers: Vec<Qualifier>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
#[derive(Debug)]
pub struct PortDecl {
pub dir: String,
pub net: Option<String>,
pub ty: DataType,
pub declarators: Vec<Declarator>,
}
#[derive(Debug, Clone)]
pub struct Declarator {
pub meta: Meta,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of an initialiser.
pub eq_comments: Box<BinaryComments>,
/// `=` for variables; net declarations also use this for the initial
/// continuous assignment.
pub init: Option<Expr>,
/// Code extent of the declarator.
pub span: TextRange,
}
#[derive(Debug)]
pub struct FunctionDecl {
/// `Some` when this is a DPI import — `import "DPI-C" function ...;` —
/// which is a prototype with a linkage prefix.
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `function` keyword, in
/// source order: `virtual`, `local`, `protected`, `static`, `pure`,
/// `extern`. Empty outside a class body.
pub prefix: Vec<Qualifier>,
/// Comments written between the `function` keyword and whatever follows
/// it (`function /*c*/ void f()`).
pub after_kw: Vec<Comment>,
pub qualifiers: Vec<Qualifier>,
/// True for a body-less prototype — `extern function ...;`,
/// `pure virtual function ...;` or a DPI import — which has no
/// `endfunction`.
pub is_prototype: bool,
/// The `my_class::` written before the name when an `extern` method is
/// *defined* outside its class body. Kept apart from `name` so
/// `src[name_span] == name` still holds for the method's own name.
pub scope: Vec<ScopeSeg>,
pub ret: Option<DataType>,
/// Comments written between the return type (or the keyword run) and the
/// method's name (`function void /*c*/ f()`).
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for old-style `function f;` declarations without a port list.
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an argument list with no argument to carry
/// them (`function void f( /*c*/ );`).
pub args_dangling: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endfunction : f`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endfunction :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// True when a `;` was written after the footer (`endfunction : f;`) — a
/// null class item (IEEE 1800 A.1.9), reproduced where it was written so
/// the token stream is unchanged.
pub end_semi: bool,
}
#[derive(Debug)]
pub struct TaskDecl {
/// `Some` when this is a DPI import; see [`FunctionDecl::dpi`].
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `task` keyword; see
/// [`FunctionDecl::prefix`].
pub prefix: Vec<Qualifier>,
/// Comments written between the `task` keyword and what follows it.
pub after_kw: Vec<Comment>,
pub qualifiers: Vec<Qualifier>,
/// True for a body-less prototype; see [`FunctionDecl::is_prototype`].
pub is_prototype: bool,
/// Out-of-body definition scope; see [`FunctionDecl::scope`].
pub scope: Vec<ScopeSeg>,
/// Comments written between the keyword run and the task's name.
pub before_name: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for old-style `task t;` declarations without a port list.
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an empty argument list; see
/// [`FunctionDecl::args_dangling`].
pub args_dangling: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
pub stmts: Vec<Stmt>,
pub dangling: Vec<Comment>,
/// Comments written in the two gaps of `endtask : t`.
pub end_label_comments: Box<LabelComments>,
/// Label after `endtask :`.
pub end_label: Option<String>,
/// Byte range of `end_label`.
pub end_label_span: Option<TextRange>,
/// True when a `;` was written after the footer; see
/// [`FunctionDecl::end_semi`].
pub end_semi: bool,
}
/// A `let` declaration: `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12).
///
/// A `let` port is the same `[type] name [= default]` a task/function port is
/// minus the direction keyword, so the ports reuse [`TfArg`] rather than
/// growing a near-identical node of their own.
#[derive(Debug)]
pub struct LetDecl {
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False for the port-less spelling `let x = expr;` — an empty `()` was
/// written when this is true and [`LetDecl::ports`] is empty.
pub has_parens: bool,
pub ports: Vec<ListElem<TfArg>>,
pub value: Expr,
}
#[derive(Debug)]
pub struct TfArg {
pub meta: Meta,
pub dir: Option<String>,
/// Comments written between the `const` and the `ref` of a `const ref`
/// direction (IEEE 1800 §13.5.2) — the one direction spelled with two
/// keywords, and so the one with a gap inside itself. Always empty for
/// every other direction.
pub after_const: Vec<Comment>,
/// Comments written between the direction keyword and the type
/// (`input /*c*/ logic`). Empty when no direction was written.
pub after_dir: Vec<Comment>,
pub ty: DataType,
/// Comments written between the type and the argument's name
/// (`bit [3:0] /*c*/ a`).
pub before_name: Vec<Comment>,
/// The formal's name, **empty** when it was written without one: a DPI
/// import prototype's formal, which IEEE 1800 §35.5.5 lets name only its
/// type (`import "DPI-C" function int f(int, chandle);`). Nothing else in
/// the language may. This is the crate's empty-name convention — the
/// `foreach (arr[, j])` loop variable is its other user — so
/// `name_span` is then the empty range just past the type, `Binder::declare`
/// ignores the name, and the formatter prints the type alone.
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
pub unpacked: Vec<Dim>,
/// Comments written on either side of the `=` of a default value.
pub eq_comments: Box<BinaryComments>,
pub default: Option<Expr>,
/// Code extent of the argument declaration.
pub span: TextRange,
}
/// A task/function port list: its arguments, plus the comments written inside
/// a pair of parentheses that hold no argument to carry them (`f( /*c*/ )`).
#[derive(Debug, Default)]
pub struct TfPorts {
pub args: Vec<ListElem<TfArg>>,
pub dangling: Vec<Comment>,
}
/// Which of the two subroutine keywords a header was written with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TfKind {
/// `function` — has a return type.
Function,
/// `task` — has none.
Task,
}
impl TfKind {
/// The keyword this kind is written with.
pub fn keyword(self) -> &'static str {
match self {
TfKind::Function => "function",
TfKind::Task => "task",
}
}
}
/// A subroutine **header**: the keyword through the closing `)` of the port
/// list, with no `;`, no body and no footer.
///
/// It is the whole of a `modport` method prototype (IEEE 1800 §25.5.4,
/// `method_prototype`), which is why it is a node; and it is what the parser
/// reads for a real [`FunctionDecl`] or [`TaskDecl`] too, spreading it across
/// their own fields afterwards, so the two spellings cannot drift apart.
#[derive(Debug)]
pub struct TfPrototype {
pub kind: TfKind,
/// Comments written between the keyword and what follows it
/// (`task /*c*/ drive(...)`).
pub after_kw: Vec<Comment>,
/// `automatic` / `static`. A modport prototype never writes one; the field
/// is here because the same parse reads a real declaration's header.
pub qualifiers: Vec<Qualifier>,
/// The return type. Always `None` for a task, and for a function whose
/// return type was left implicit.
pub ret: Option<DataType>,
/// Comments written between the return type (or the keyword run) and the
/// name (`function void /*c*/ f()`).
pub before_name: Vec<Comment>,
/// The `my_class::` of an out-of-body definition; empty on a prototype.
pub scope: Vec<ScopeSeg>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// False when no `()` was written at all.
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an argument list with no argument to carry
/// them (`task drive( /*c*/ )`).
pub args_dangling: Vec<Comment>,
}