Files
lucisv/crates/vlog_parser/src/ast/mod.rs
T
lucioandClaude Fable 5.1 a30dda167a Small items, round 3: a bare begin block recovered as a generate block, the half-typed #( override lookahead, atomic in-place writes
TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25
and the §1 atomic-writes item.

36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end`
at module scope or straight inside a generate region is parsed as an
unnamed generate block with a diagnostic at the keyword, so the items
inside and after it survive; strict mode is untouched. Consumers walk
its items; `module-begin-block`, `v2001-generate-begin` and
`mismatched-labels` read the node. The formatter's `gen_block` is split
by a pure extraction into `begin_block`. One server test that parsed a
3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE.

36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead
in `parse_connection`: an unclosed `.NAME(` whose value would swallow
the next instance as a call fails the element instead; `recover_element`
takes the bracket the element stopped on before skipping so the skip
stays at the list's level. The balanced-parens spelling stays greedy.

36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename,
permissions preserved, symlink target replaced, read-only target
refused as `fs::write` refused it; used by format, `check --fix` and
the cache.

Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in
their QA logs; the §27 P6 line and the sva-bodies README checkbox
annotated as delivered by §29), topo §2.9-24/25 struck.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00

549 lines
23 KiB
Rust

//! AST for the supported Verilog/SystemVerilog subset.
//!
//! Nodes that begin a line carry a [`Meta`] with leading comments, an
//! optional trailing comment, and a blank-line-before flag so the formatter
//! can reproduce vertical structure the way ruff's formatter does.
//!
//! Spans: a node's `span` is its **code extent** — from the first to the last
//! token of the construct itself. Attached comments are *not* part of it and
//! carry their own spans on [`Comment`]; attribute instances `(* ... *)` are
//! real tokens and *are* inside it. See `docs/features/spans/README.md` for
//! which node types carry a span and why the rest do not.
//!
//! Names: a node that declares a name keeps the name as a `String` and the
//! byte range of the identifier that spells it in a sibling field —
//! `name_span` for the declared name, `label_span` / `end_label_span` /
//! `module_span` for the other names a node can carry — so
//! `src[name_span] == name`. Where a node holds a *list* of names the two are
//! bundled into a [`Name`] instead, because parallel `Vec`s cannot be kept in
//! step by construction. See `docs/features/name-spans/README.md`.
//!
//! Layout: this file holds the file and item spine — [`SourceFile`],
//! [`Item`], [`ItemKind`] and the small items' payloads — and the leaf types
//! every node shares ([`Meta`], [`Name`], [`RawText`], [`Qualifier`]). The
//! node types are grouped by grammar domain in sibling files and re-exported
//! here, so every type is `vlog_parser::ast::Name` regardless of which file
//! defines it:
//!
//! | file | holds |
//! |---|---|
//! | `module` | module/interface/program, ports, instantiations, `assign`, gates, `bind`, generate, modports, clocking |
//! | `decl` | data types, dimensions, declarations, `typedef`/`enum`/`struct`, function/task/`let` |
//! | `stmt` | [`Stmt`], [`StmtKind`], timing controls, sensitivity lists |
//! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots |
//! | `class`, `covergroup` | classes and constraints; covergroups |
//! | `sva` | assertions, `property`/`sequence`, the property-expression tree |
use crate::span::TextRange;
use crate::token::Comment;
mod class;
mod covergroup;
mod decl;
mod expr;
mod module;
mod stmt;
mod sva;
pub use class::*;
pub use covergroup::*;
pub use decl::*;
pub use expr::*;
pub use module::*;
pub use stmt::*;
pub use sva::*;
/// A name as written, together with the byte range it occupies:
/// `src[span] == text`.
///
/// Used where a node holds a *list* of names; a node with a single name keeps
/// it as a `String` plus a sibling `name_span`.
#[derive(Debug, Clone)]
pub struct Name {
pub text: String,
pub span: TextRange,
}
/// One `pkg::` / `cls::` segment written in front of an out-of-body
/// definition's name, with the comments written in its two gaps.
///
/// The chain is kept as segments rather than joined into a `String` so that
/// (a) a comment written beside a `::` has a slot, and (b) an escaped
/// segment's terminating space survives — `\my-pkg ::\state-t` is three
/// tokens and `\my-pkg::\state-t` is one (`docs/topo.md` §2.9-21).
#[derive(Debug, Clone)]
pub struct ScopeSeg {
pub name: Name,
/// Comments written between this segment and the `::` after it.
pub before_sep: Vec<Comment>,
/// Comments written between that `::` and whatever follows it.
pub after_sep: Vec<Comment>,
}
/// The `a::b::` prefix a [`ScopeSeg`] chain spells, joined for the consumers
/// that want one string (the binder's out-of-body home, hover text).
///
/// An escaped segment keeps the whitespace that terminates it, for the reason
/// [`ScopeSeg`] gives; nothing else adds any.
pub fn scope_path(segs: &[ScopeSeg]) -> String {
let mut out = String::new();
for seg in segs {
out.push_str(&seg.name.text);
if seg.name.text.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) {
out.push(' ');
}
out.push_str("::");
}
out.pop();
out.pop();
out
}
/// Comments written in the two gaps of a `keyword : name` label — the `end`,
/// `endfunction`, `endgroup`, `begin` … footers and headers that carry one.
#[derive(Debug, Clone, Default)]
pub struct LabelComments {
/// Between the keyword and the `:`.
pub before_colon: Vec<Comment>,
/// Between the `:` and the name.
pub after_colon: Vec<Comment>,
}
impl LabelComments {
/// True when nothing was written in either gap — the common case.
pub fn is_empty(&self) -> bool {
self.before_colon.is_empty() && self.after_colon.is_empty()
}
}
/// One keyword of a qualifier run, with the comments written between it and
/// whatever follows it (`local /*c*/ static /*c*/ function`).
///
/// Kept per keyword rather than as one bucket for the run, because two
/// comments in different gaps of the same run are two different token
/// streams and the safety net compares them.
#[derive(Debug, Clone)]
pub struct Qualifier {
pub text: String,
/// Comments written after this keyword and before the next one — or
/// before whatever ends the run.
pub after: Vec<Comment>,
}
impl Qualifier {
/// A qualifier with nothing written after it, for the sites that build a
/// run rather than reading one from source.
pub fn plain(text: impl Into<String>) -> Self {
Qualifier { text: text.into(), after: Vec::new() }
}
}
#[derive(Debug, Clone, Default)]
pub struct Meta {
pub leading: Vec<Comment>,
/// The comment written *after* the node and the separator that closes it
/// (`,` or `;`), on the same line. Several are merged into one, joined by
/// a space; the merged value keeps the first one's position and spans
/// from the first byte of the first to the last byte of the last.
pub trailing: Option<Comment>,
/// Comments written *between* the node and the separator that follows it
/// (`element /* c */,`). They print on the node's side of the separator,
/// which is where the source put them — printing them after it moves a
/// comment across a token and the safety net rejects the output. Empty
/// for a node no separator follows.
pub before_sep: Vec<Comment>,
pub blank_before: bool,
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
pub attrs: Vec<RawText>,
}
/// Source text passed through verbatim: a compiler directive or an attribute
/// instance. `col` is the 1-based column it started in, which is what lets the
/// formatter re-indent continuation lines of a multi-line one without drifting
/// further right on every pass.
#[derive(Debug, Clone)]
pub struct RawText {
pub text: String,
pub col: u32,
/// Byte extent of the passed-through token.
pub span: TextRange,
}
/// One element of a header list: the element as written, or — in a tolerant
/// parse only — the text of one that did not parse.
///
/// The five header lists (a module's ports and parameter ports, a
/// subroutine's formals, an instance's named and ordered connections) share
/// this one wrapper rather than each growing a two-variant enum of its own:
/// the shape is the same in all of them, and one type means one place says
/// what an error element is. [`crate::parse`] never builds an
/// [`ListElem::Error`] — the strict parser fails on the typo instead — so a
/// consumer of a strictly parsed tree sees only [`ListElem::Ok`]. A consumer
/// of [`crate::parse_tolerant`]'s tree must decide what to do with the other
/// variant, which is the point of making it a variant; see
/// `docs/features/header-recovery/README.md`.
#[derive(Debug)]
pub enum ListElem<T> {
/// An element that parsed.
Ok(T),
/// Text a tolerant parse could not read as an element, kept verbatim.
Error(RawText),
}
impl<T> ListElem<T> {
/// The element, or `None` for an error element — the filter a consumer
/// that only wants the well-formed elements reads the list through.
pub fn ok(&self) -> Option<&T> {
match self {
ListElem::Ok(v) => Some(v),
ListElem::Error(_) => None,
}
}
/// The element as a mutable reference, or `None` for an error element:
/// what the parser's list loops hang a separator's comments on.
pub fn ok_mut(&mut self) -> Option<&mut T> {
match self {
ListElem::Ok(v) => Some(v),
ListElem::Error(_) => None,
}
}
/// The skipped text of an error element, or `None` for one that parsed.
pub fn error(&self) -> Option<&RawText> {
match self {
ListElem::Ok(_) => None,
ListElem::Error(raw) => Some(raw),
}
}
/// True for an element a tolerant parse recovered from.
pub fn is_error(&self) -> bool {
matches!(self, ListElem::Error(_))
}
}
/// A compiler directive written *between* the elements of a port,
/// parameter-port, enum-member, parameter-override or instance-connection
/// list (`` `ifdef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
/// `` `undef``, `` `include``) — or a standalone macro invocation standing in
/// the same place, which is passed through the same way.
///
/// It is kept in a vector *beside* the elements rather than folded into one
/// enum with them: the element vectors are read by `vlog_semantic` and
/// `vlog_linter`, and a directive is not a port. `before` is what puts the
/// two back into source order. lucisv does not evaluate the condition — both
/// arms' elements are ordinary elements of the one list, exactly as an
/// `` `ifdef`` at item position already works.
#[derive(Debug, Clone)]
pub struct ListDirective {
/// The directive line, verbatim.
pub raw: RawText,
/// Comments written before the directive (`leading`) and the one written
/// after it on the same line (`trailing`).
pub meta: Meta,
/// Index of the element this directive was written before;
/// `elements.len()` when it stands after the last one. Several directives
/// at the same index keep their source order in the vector.
pub before: usize,
/// True when the `,` separating the surrounding elements was written
/// *after* this directive (`` `ifdef X`` ⏎ `, parameter string P = ""`),
/// which is how a conditional list tail stays legal in both arms.
pub comma: bool,
}
/// A macro invocation standing where a module item or a statement belongs
/// (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) ``). Its arguments are token soup
/// handed to a preprocessor we do not run, so the whole invocation is kept as
/// verbatim source text — same treatment as a compiler directive.
#[derive(Debug)]
pub struct MacroCall {
/// The invocation from the backtick through the closing `)`, verbatim.
pub raw: RawText,
/// True if a `;` followed it in the source. Both spellings occur in real
/// RTL, so the formatter reproduces whichever one was written.
pub semi: bool,
}
#[derive(Debug)]
pub struct SourceFile {
pub items: Vec<Item>,
/// Comments at the very end of the file.
pub dangling: Vec<Comment>,
/// The whole source text: `0..len`.
pub span: TextRange,
/// How many `constraint` bodies — declarations and `randomize() with`
/// blocks alike — did not fit the constraint grammar and were captured
/// verbatim instead. Purely diagnostic: it says how much of the real
/// world round 1 of `constraint-bodies` still passes through opaquely,
/// and nothing in the tree depends on it. See
/// `docs/features/constraint-bodies/README.md`.
pub constraint_fallbacks: u32,
/// How many `covergroup` declarations were parsed into a
/// [`ItemKind::Covergroup`], and how many did not fit the covergroup
/// grammar and were captured verbatim instead. The pair is the census
/// `docs/features/covergroup-bodies/README.md` reports: diagnostic only,
/// and nothing in the tree depends on either.
pub covergroups: u32,
pub covergroup_fallbacks: u32,
/// How many `property`/`sequence` declarations and concurrent assertions
/// were parsed into real nodes, and how many did not fit the SVA grammar
/// and were captured verbatim instead. The pair is the census
/// `docs/features/sva-bodies/README.md` reports: diagnostic only, and
/// nothing in the tree depends on any of the four.
pub prop_seq_decls: u32,
pub prop_seq_fallbacks: u32,
pub assertions: u32,
pub assertion_fallbacks: u32,
/// Set when the file is not an item list at all but a **fragment**: the
/// bare middle of some larger construct's body, written to be
/// `` `include``d at exactly that point. `items` is empty whenever this is
/// `Some`, and vice versa. See `docs/features/fragment-mode/README.md`.
pub fragment: Option<Fragment>,
}
/// A whole file that is a piece of a body rather than a list of items.
///
/// Only the three shapes that do not already parse at file scope are here: a
/// class-body fragment and a module-item fragment are ordinary [`Item`] lists
/// and stay in [`SourceFile::items`], because the file-scope item loop is the
/// same loop a class and a module body run.
#[derive(Debug)]
pub enum Fragment {
/// The middle of a procedural block: `if (x) y <= 1;`, `foo();`.
Statements(Vec<Stmt>),
/// The middle of an `enum { ... }` member list: `CUSTOM_1,`.
EnumMembers {
members: Vec<EnumMember>,
/// `` `ifdef``-style directives written between members, exactly as
/// [`EnumType::directives`] records them.
directives: Vec<ListDirective>,
},
/// The middle of a `covergroup ... endgroup` body: `cp_a: coverpoint a;`.
CoverItems(Vec<CoverItem>),
}
#[derive(Debug)]
pub struct Item {
pub meta: Meta,
pub kind: ItemKind,
/// Code extent of the item, its `(* ... *)` attributes included.
pub span: TextRange,
}
#[derive(Debug)]
pub enum ItemKind {
Module(Module),
Package {
kw: String,
/// Comments written between `package` and the name.
before_name: Vec<Comment>,
name: String,
/// Byte range of `name`.
name_span: TextRange,
/// Comments written between the name and the header's `;`.
before_semi: Vec<Comment>,
items: Vec<Item>,
dangling: Vec<Comment>,
/// Comments written in the two gaps of `endpackage : p`.
end_label_comments: Box<LabelComments>,
/// Label after `endpackage :`.
end_label: Option<String>,
/// Byte range of `end_label`.
end_label_span: Option<TextRange>,
},
Directive(RawText),
/// Macro invocation used as a module item.
MacroItem(MacroCall),
/// An elaboration system task standing where a module or generate item
/// belongs: `$error("...");`, `$fatal(1, "...");` (IEEE 1800 §20.11).
/// The payload is the ordinary system-task-call expression — only the
/// position is special.
ElabTask(Expr),
Import(Vec<ImportPath>),
/// `export "DPI-C" function f;` or `export pkg::*;`.
Export(ExportDecl),
Timeunit(String),
Typedef(Typedef),
ParamDecl(ParamDecl),
DataDecl(DataDecl),
/// Non-ANSI port declaration at module scope: `input [7:0] data;`
PortDecl(PortDecl),
ContAssign(ContAssign),
/// The body statement carries any `@(...)`/`#delay` timing control.
Always {
kw: String,
stmt: Stmt,
},
Initial(Stmt),
Final(Stmt),
Instantiation(Instantiation),
GateInstantiation(GateInstantiation),
/// `bind <target> [: <instances>] <instantiation>` (IEEE 1800 §23.11).
Bind(BindDirective),
Genvar(Vec<Name>),
GenerateRegion {
items: Vec<Item>,
dangling: Vec<Comment>,
},
GenIf(GenIf),
/// A bare `begin … end` written where an item belongs — at module scope
/// or straight inside `generate … endgenerate`. Not a legal module item
/// (IEEE 1800 §23.2.1); tools that accept it read it as an unnamed
/// generate block, which is the node kept here. Only error-tolerant
/// parsing produces it, always beside a diagnostic at the `begin`, so the
/// formatter — which refuses any file with a diagnostic — never prints
/// one. The `module-begin-block` and `v2001-generate-begin` lints are
/// what report it. Boxed for the same reason [`ItemKind::GenFor`] is.
GenBlock(Box<GenBlock>),
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
/// step and a block, which together are twice the next-largest item.
GenFor(Box<GenFor>),
GenCase(GenCase),
Function(FunctionDecl),
Task(TaskDecl),
/// `let name(ports) = expr;` (IEEE 1800 §11.12).
Let(LetDecl),
/// A `class` / `virtual class` declaration and its body.
Class(ClassDecl),
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). One
/// declaration may name several modports, so the payload is a list.
Modport(Vec<ModportDecl>),
/// `clocking cb @(posedge clk); ... endclocking` and the `default`
/// spellings of it (IEEE 1800 §14).
Clocking(ClockingDecl),
/// `constraint c { ... }`, its `constraint C::c { ... }` out-of-block
/// form, and the `constraint c;` prototype (IEEE 1800 §18.5).
///
/// A body the constraint grammar does not recognise never reaches this
/// variant: [`Parser::parse_constraint`](crate::parser::Parser) rewinds
/// and produces the [`ItemKind::Verbatim`] leaf constraints have been
/// since the `classes` round, byte for byte. See
/// `docs/features/constraint-bodies/README.md`.
Constraint(ConstraintDecl),
/// `covergroup g ... endgroup` and everything inside it (IEEE 1800 §19.3).
///
/// A body the covergroup grammar does not recognise never reaches this
/// variant: [`Parser::parse_covergroup`](crate::parser::Parser) rewinds
/// and produces the [`ItemKind::Verbatim`] leaf covergroups had before
/// this round, byte for byte. See
/// `docs/features/covergroup-bodies/README.md`.
Covergroup(Box<CovergroupDecl>),
/// `property p; … endproperty` and `sequence s; … endsequence`
/// (IEEE 1800 §16.8, §16.12).
PropSeqDecl(Box<PropSeqDecl>),
/// `[label :] assert|assume|cover|restrict property ( … ) action_block`
/// and `cover sequence ( … ) …` (IEEE 1800 §16.14).
Assertion(Box<AssertionDecl>),
/// `default disable iff ( expression_or_dist ) ;` — the standing
/// `disable iff` clause of every concurrent assertion in the scope
/// (IEEE 1800 §16.15).
DefaultDisable(Box<DisableIff>),
/// A block lucisv deliberately does not model, kept byte-for-byte:
/// a concurrent assertion
/// (`assert property ( ... );`), a `property`/`sequence` declaration —
/// and a `constraint` or a `covergroup` whose body did not fit the
/// grammar. See `docs/features/classes/README.md`,
/// `docs/features/assertions/README.md`,
/// `docs/features/constraint-bodies/README.md`,
/// `docs/features/covergroup-bodies/README.md` and
/// `docs/features/sva-bodies/README.md` for why each one is verbatim.
Verbatim(RawText),
Defparam(Vec<(Expr, Expr)>),
/// `alias a = b = c;` (IEEE 1800 §10.11): one bidirectional connection
/// between two or more net lvalues. The `=`s are separators — no term is
/// the value of any other — so the terms are a flat list.
Alias(Vec<Expr>),
/// A **null item**: a lone `;` standing where an item belongs
/// (IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;`
/// and `class_item ::= … | ;`). Legal and meaningless in every item
/// scope, and written constantly after `endgenerate`, after a generate
/// block's `end` and after `endmodule`. The span is the `;` itself; the
/// `empty-item` lint is what tells the user about it.
///
/// The `;` after `endfunction`/`endtask` is *not* one of these: it is
/// consumed inside the declaration and recorded as
/// [`FunctionDecl::end_semi`] / [`TaskDecl::end_semi`], which predates
/// this variant.
Empty,
/// Source that could not be parsed as an item, kept verbatim.
///
/// Only error-tolerant parsing
/// (`vlog_parser::parse_source_tolerant`) ever produces this; the
/// strict entry point fails on the first error instead, so the formatter
/// never sees one. See `docs/features/error-recovery/README.md`.
Error(RawText),
}
/// One `pkg::item` (or `pkg::*`) path of an `import`, each half with its own
/// range — a language server resolves the package and the imported name
/// separately.
#[derive(Debug, Clone)]
pub struct ImportPath {
pub pkg: Name,
/// The imported name, or `*` for a wildcard (whose span is the `*`).
pub item: Name,
}
impl ImportPath {
/// The path as it is written: `pkg::item`.
pub fn text(&self) -> String {
format!("{}::{}", self.pkg.text, self.item.text)
}
}
/// The `import "DPI-C" [context|pure] [c_name =]` prefix that makes a function
/// or task prototype a DPI import (IEEE 1800 §35.5). A DPI import *is* a
/// prototype, so it is modelled as [`FunctionDecl`] / [`TaskDecl`] with this
/// hung off it rather than as an item kind of its own.
#[derive(Debug, Clone)]
pub struct DpiImport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The DPI import property, when written: `context` or `pure`.
pub property: Option<String>,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
}
/// An `export` item: a DPI export or a package re-export.
#[derive(Debug)]
pub enum ExportDecl {
/// `export "DPI-C" [c_name =] function|task name;` (IEEE 1800 §35.5.4).
Dpi(DpiExport),
/// `export pkg::item, pkg::*;` (IEEE 1800 §26.6). The LRM's `export *::*;`
/// is one path whose package half is `*` as well.
Package(Vec<ImportPath>),
}
/// One `export "DPI-C" ... ;` declaration.
#[derive(Debug)]
pub struct DpiExport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
/// `function` or `task`.
pub kw: String,
/// The exported SystemVerilog task or function name.
pub name: Name,
}
/// The sizes the comment-slots round pinned, so the next slot added inline
/// fails here rather than as a stack overflow in a debug-build test that
/// only runs with the corpus checked out (docs/features/comment-slots).
/// `Expr` is walked recursively; every expression-level comment struct is
/// boxed to keep it at its pre-round size.
#[cfg(all(test, target_pointer_width = "64"))]
mod size_pins {
use super::*;
use std::mem::size_of;
#[test]
fn expr_stmt_and_stmt_kind_stay_within_their_pinned_sizes() {
assert!(size_of::<Expr>() <= 96, "Expr is {} bytes: box the new field", size_of::<Expr>());
assert!(size_of::<StmtKind>() <= 392, "StmtKind is {} bytes", size_of::<StmtKind>());
assert!(size_of::<Stmt>() <= 552, "Stmt is {} bytes", size_of::<Stmt>());
}
}