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

415 lines
15 KiB
Rust

//! Statements: the [`Stmt`] node, every [`StmtKind`], timing controls and
//! sensitivity lists, and the pieces of `case`, `for` and `foreach`.
use super::*;
/// One slot of a `foreach`'s loop-variable bracket, with the comments written
/// on either side of it so neither drifts across the `,` that separates two
/// slots.
#[derive(Debug, Clone)]
pub struct ForeachVar {
/// The loop variable. A **skipped** dimension (IEEE 1800 §12.7.3 —
/// `foreach (q[, j])` iterates only the second) is an empty name at the
/// point it was written: it declares nothing and prints as nothing.
pub name: Name,
/// Comments written between the `[` (or the previous `,`) and this slot.
pub before: Vec<Comment>,
/// Comments written between this slot and the `,` or `]` after it.
pub after: Vec<Comment>,
}
#[derive(Debug)]
pub enum SensList {
/// `@*` or `@(*)`, with any comments written next to the `*` so the
/// formatter can print them back in the same place.
Star {
/// Comments between the `@`/`(` and the `*`.
before: Vec<Comment>,
/// Comments between the `*` and the closing `)`.
after: Vec<Comment>,
},
List {
items: Vec<SensItem>,
/// Comments written between the `@` and the `(` (`always @ /*c*/ (`).
after_at: Vec<Comment>,
},
/// `@name` or `@a.b` written without parens; printed back without them —
/// inventing a `( ... )` would be a token-stream change the safety net
/// refuses.
Bare {
expr: Expr,
/// Comments written between the `@` and the name.
after_at: Vec<Comment>,
},
}
#[derive(Debug)]
pub struct SensItem {
/// Comments written around this item: `leading` before it (after the `(`
/// or the separator), `before_sep` between it and the separator that
/// follows — or the closing `)` for the last item.
pub meta: Meta,
/// The separator written before this item; `None` on the first item.
pub sep: Option<SensSep>,
pub edge: Option<String>,
/// Comments written between the edge keyword and the expression
/// (`@(posedge /*c*/ clk)`). Empty when no edge keyword was written.
pub after_edge: Vec<Comment>,
pub expr: Expr,
/// The gating condition of `@(posedge clk iff enable)` — IEEE 1800
/// §9.4.2's optional `iff expression` on one event expression term.
pub iff: Option<Expr>,
}
/// How two event-list items were separated in the source. Both spellings are
/// legal and mean the same thing, but rewriting one as the other changes the
/// token stream, so the formatter reproduces whichever was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SensSep {
/// `@(posedge clk, negedge rst_n)`
Comma,
/// `@(posedge clk or negedge rst_n)`
Or,
}
#[derive(Debug)]
pub struct Stmt {
pub meta: Meta,
pub kind: StmtKind,
/// Comments written in the gap between the statement's last token and the
/// `;` that ends it (`x = 1 /* inclusive */ ;`).
///
/// The statement is the single owner of that gap — the same rule
/// [`ConstraintItem::before_semi`] states for a constraint item — because
/// the `;` is consumed in a dozen places and read in four of them to
/// decide the statement's shape. Always empty for a kind
/// [`StmtKind::takes_semi`] is false for.
pub before_semi: Vec<Comment>,
/// Code extent of the statement, its `(* ... *)` attributes included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum StmtKind {
Block {
/// Comments written in the two gaps of the `begin : name` label.
label_comments: Box<LabelComments>,
label: Option<String>,
/// Byte range of `label`.
label_span: Option<TextRange>,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `end : name`.
end_label_comments: Box<LabelComments>,
/// Label after `end :`.
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
ForkJoin {
/// Comments written in the two gaps of the `fork : name` label.
label_comments: Box<LabelComments>,
label: Option<String>,
/// Byte range of `label`.
label_span: Option<TextRange>,
join_kw: String,
stmts: Vec<Stmt>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `join : name`.
end_label_comments: Box<LabelComments>,
/// Label after `join :` (any join kind).
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
If {
qualifier: Option<String>,
/// Comments written between the `if` keyword and its `(`.
after_kw: Vec<Comment>,
cond: Expr,
then: Box<Stmt>,
/// Comments written between the then-branch and the `else` keyword.
/// They are kept here, not on `els`, because printing them after the
/// keyword moves them across it and the safety net rejects that.
else_comments: Vec<Comment>,
els: Option<Box<Stmt>>,
},
Case {
qualifier: Option<String>,
kw: String,
/// Comments written between the `case` keyword and its `(`.
after_kw: Vec<Comment>,
expr: Expr,
/// True for `case (expr) inside`, whose labels may be `[lo:hi]`
/// value ranges.
inside: bool,
items: Vec<CaseItem>,
dangling: Vec<Comment>,
},
For {
init: Vec<ForInit>,
cond: Option<Expr>,
step: Vec<ForStep>,
/// The seven fixed slots of a `for ( … ; … ; … )` header.
comments: Box<ForComments>,
body: Box<Stmt>,
},
While {
cond: Expr,
body: Box<Stmt>,
},
DoWhile {
body: Box<Stmt>,
cond: Expr,
/// The `while /*a*/ ( /*b*/ cond /*c*/ )` slots. A `do ... while` is
/// the one loop with no body *after* its parentheses, so there is
/// nothing for `Fmt::header_parens` to take a comment back from.
comments: Box<HeaderComments>,
},
Repeat {
count: Expr,
body: Box<Stmt>,
},
Forever {
body: Box<Stmt>,
},
/// `foreach (arr[i, j]) stmt` (IEEE 1800 §12.7.3).
///
/// `target` is the array being iterated, which may be a package-scoped or
/// hierarchical name with index and member selects along the way
/// (`riscv_instr_pkg::supported_isa`, `page_table[i].pte`); `vars` are the
/// names in the *last* bracket group, the only one that declares loop
/// variables.
Foreach {
target: Expr,
vars: Vec<ForeachVar>,
/// Comments written around the loop-variable bracket
/// (`foreach (q /*a*/ [ … ] /*never*/)`) — `before_open`,
/// `after_open` and `before_close` only.
var_comments: Box<SegmentComments>,
/// The `foreach /*a*/ ( /*b*/ … /*c*/ ) /*d*/ body` slots.
comments: Box<HeaderComments>,
body: Box<Stmt>,
},
/// `randcase w1 : stmt; w2 : stmt; endcase` (IEEE 1800 §18.16) — a `case`
/// whose items are weights and which has no selector expression.
RandCase {
items: Vec<CaseItem>,
dangling: Vec<Comment>,
},
/// `wait fork;` — block until every child process finishes
/// (IEEE 1800 §9.6.1). `fork` is a keyword, not an expression, which is
/// why this is not a [`StmtKind::Wait`].
WaitFork,
/// `import pkg::item;` / `import pkg::*;` standing among a block's
/// declarations (IEEE 1800 §13.4.2) — the statement twin of
/// [`ItemKind::Import`].
Import(Vec<ImportPath>),
/// `typedef enum bit {WRITE, READ} rdwr_e;` written inside a
/// function/task body or a `begin` block, scoping the type to that block
/// (IEEE 1800 §6.18) — the statement twin of [`ItemKind::Typedef`], with
/// the same payload and the same layout.
Typedef(Typedef),
/// `name : stmt` — a statement label (IEEE 1800 §9.3.5).
///
/// `begin`/`fork` keep their label inside their own node, because the
/// source writes it *after* the keyword; this is the general prefix form,
/// which any statement may carry.
Labeled {
name: String,
/// Byte range of `name`.
name_span: TextRange,
stmt: Box<Stmt>,
},
/// Blocking/nonblocking/compound assignment.
Assign {
lhs: Expr,
op: String,
/// Comments written between the left-hand side and the operator
/// (`instr[6:0] /* opcode */ = ...;`). Kept here so they print on
/// the operator's left instead of being lost.
op_comments: Vec<Comment>,
/// Comments written between the operator and the right-hand side,
/// kept on the operator's line as a continuous assignment's are.
rhs_comments: Vec<Comment>,
/// Intra-assignment timing control (e.g. `#1`, `@(posedge clk)`).
timing: Option<TimingControl>,
rhs: Expr,
},
/// `force`/`release`/`deassign` statements, raw pieces.
ForceRelease {
kw: String,
lhs: Expr,
rhs: Option<Expr>,
},
/// Procedural timing control: `#10 stmt;`, `@(posedge clk) stmt;`,
/// `#10;`, `@(ev);`
Timing {
control: TimingControl,
stmt: Option<Box<Stmt>>,
},
Wait {
cond: Expr,
stmt: Option<Box<Stmt>>,
},
ExprStmt(Expr),
/// `-> event_name;`
EventTrigger(Expr),
VarDecl(DataDecl),
ParamDecl(ParamDecl),
/// Old-style task/function port declaration: `input [7:0] a;`
PortDecl(PortDecl),
Return {
/// Comments written between `return` and its value.
after_kw: Vec<Comment>,
expr: Option<Expr>,
},
Break,
Continue,
/// `disable blk;`, `disable fork;` — the label or task the statement
/// names, with the range it is written in. A *use*, not a declaration,
/// but it is addressable all the same, so it carries a span like every
/// other name (`disable fork` spans the `fork` keyword).
Disable {
name: String,
name_span: TextRange,
},
Directive(RawText),
/// Macro invocation used as a statement.
MacroStmt(MacroCall),
/// A concurrent assertion written in statement position
/// (`assert property ( ... ) else $error("...");` inside an `initial`),
/// kept byte-for-byte. The statement-level twin of the assertion half of
/// [`ItemKind::Verbatim`]; see `docs/features/assertions/README.md`.
Verbatim(RawText),
/// A concurrent assertion — or an `expect` statement — written in
/// statement position, as a real node. The statement-level twin of
/// [`ItemKind::Assertion`]; a spec the SVA grammar does not recognise
/// falls back to [`StmtKind::Verbatim`] above.
Assertion(Box<AssertionDecl>),
/// Immediate assertion: kept simple — `assert (expr) stmt else stmt;`
Assert {
kw: String,
cond: Expr,
then: Option<Box<Stmt>>,
els: Option<Box<Stmt>>,
},
Null,
/// Source that could not be parsed as a statement, kept verbatim.
///
/// The statement-level twin of [`ItemKind::Error`]: produced only by
/// error-tolerant parsing, never seen by the formatter.
Error(RawText),
}
impl StmtKind {
/// True for the kinds whose own last token is followed by a `;` this
/// statement wrote — the kinds [`Stmt::before_semi`] can be non-empty
/// for.
///
/// A `begin`/`fork` block, an `if`, a `case`, a loop and a labelled
/// statement all end in a *body*, whose own last statement owns whatever
/// `;` stands there; [`StmtKind::Null`] **is** its `;`; a directive, a
/// macro call and a verbatim capture carry their own text. The three
/// shape-deciding kinds — a timing control, a `wait` and an immediate
/// assertion — take one only in the branch that wrote no body, which is
/// exactly the branch the parser read the `;` in.
///
/// One answer, read by the parser (which consumes the `;`) and by the
/// formatter (which writes it back), so the two cannot disagree about who
/// owns the gap in front of it.
pub fn takes_semi(&self) -> bool {
match self {
StmtKind::Assign { .. }
| StmtKind::ExprStmt(_)
| StmtKind::EventTrigger(_)
| StmtKind::ForceRelease { .. }
| StmtKind::VarDecl(_)
| StmtKind::ParamDecl(_)
| StmtKind::PortDecl(_)
| StmtKind::Return { .. }
| StmtKind::Break
| StmtKind::Continue
| StmtKind::Disable { .. }
| StmtKind::WaitFork
| StmtKind::DoWhile { .. } => true,
StmtKind::Timing { stmt, .. } => stmt.is_none(),
StmtKind::Wait { stmt, .. } => stmt.is_none(),
StmtKind::Assert { then, els, .. } => then.is_none() && els.is_none(),
_ => false,
}
}
}
#[derive(Debug)]
pub enum TimingControl {
/// `#expr`
Delay {
/// Comments written between the `#` and the delay value
/// (`# /*c*/ 10`).
after_hash: Vec<Comment>,
expr: Expr,
},
/// `@(...)`, `@*`
Event(SensList),
}
#[derive(Debug)]
pub struct CaseItem {
pub meta: Meta,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
/// Comments written between the last label — or the `default` keyword —
/// and the `:` that ends the label list.
pub before_colon: Vec<Comment>,
pub stmt: Stmt,
/// Code extent of the case item, its body included.
pub span: TextRange,
}
#[derive(Debug)]
pub struct ForInit {
/// Declared type for `for (int i = 0; ...)`.
pub ty: Option<DataType>,
/// Comments written between that type and the name (`for (int /*c*/ i`).
pub before_name: Vec<Comment>,
pub assign: SimpleAssign,
}
#[derive(Debug)]
pub struct SimpleAssign {
pub lhs: Expr,
pub op: String,
/// Comments written on either side of the operator.
pub op_comments: Box<BinaryComments>,
pub rhs: Expr,
}
/// Comments written in the fixed slots of a `for ( init ; cond ; step )`
/// header (IEEE 1800 §12.7.1). Seven punctuation positions, none of which has
/// anything beside it to carry a comment.
#[derive(Debug, Default)]
pub struct ForComments {
/// Between `for` and the `(`.
pub after_kw: Vec<Comment>,
/// Just inside the `(`.
pub after_open: Vec<Comment>,
/// Between the initialisers and the first `;`.
pub before_first_semi: Vec<Comment>,
/// Between the first `;` and the condition.
pub after_first_semi: Vec<Comment>,
/// Between the condition and the second `;`.
pub before_second_semi: Vec<Comment>,
/// Between the second `;` and the step list.
pub after_second_semi: Vec<Comment>,
/// Between the step list and the `)`.
pub before_close: Vec<Comment>,
}
#[derive(Debug)]
pub enum ForStep {
Assign(SimpleAssign),
Expr(Expr),
}