Files
lucisv/crates/vlog_parser/src/parser/item.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

743 lines
32 KiB
Rust

//! From the file down to one item.
//!
//! The top-level loop ([`Parser::parse_source_file`]), the item loop every
//! body shares ([`Parser::parse_item`]) and the dispatch from a keyword to
//! the grammar that parses it ([`Parser::parse_keyword_item`]); plus the
//! items that are small enough to live beside the dispatch — packages,
//! imports and exports, DPI, generate regions — and the member-qualifier
//! prefix (`virtual`, `local`, `rand`, …) an item may start with.
use super::directive::{fragment_file, is_prelude};
use super::*;
const GATE_KEYWORDS: &[&str] = &[
"and", "or", "nand", "nor", "xor", "xnor", "not", "buf", "bufif0", "bufif1", "notif0",
"notif1", "pullup", "pulldown", "cmos", "rcmos", "nmos", "pmos", "rnmos", "rpmos", "tran",
"rtran", "tranif0", "tranif1", "rtranif0", "rtranif1",
];
/// The elaboration system tasks: the only `$...` calls that may stand where a
/// module or generate item belongs (IEEE 1800 §20.11). The list is closed —
/// `$display(...)` at module scope is still an error, because it is only legal
/// inside a procedural block.
const ELAB_TASKS: &[&str] = &["$fatal", "$error", "$warning", "$info"];
/// Keywords that may stand *before* the one that names a class member:
/// `virtual function`, `pure virtual task`, `extern function`,
/// `local rand int x`, `protected static function`. They are looked at
/// without being consumed (see [`Parser::member_head`]) so the construct they
/// belong to keeps ownership of them.
pub(super) const MEMBER_QUALIFIERS: &[&str] = &[
"virtual",
"pure",
"extern",
"local",
"protected",
"rand",
"randc",
"static",
"automatic",
"const",
"var",
];
impl<'a> Parser<'a> {
pub(super) fn parse_source_file(&mut self) -> PResult<SourceFile> {
let mut items = Vec::new();
// The first item that carries structure decides what kind of file this
// is. One that parses settles it: this is an item list — a design
// unit, a package, a class body, a run of module items — and nothing
// re-reads it as anything else. One that fails is the only door to
// fragment mode; see [`fragment_file`]. Directives, macro invocations
// and null items do not settle it, because they are legal in *every*
// body, and a fragment routinely opens with one (`` `ifdef `` around
// the enum members it contributes).
let mut prelude_only = true;
while !self.at_eof() {
let start_pos = self.pos;
let start = self.here();
let diags_before = self.diagnostics.len();
match self.parse_item() {
Ok(item) => {
// A tolerant parse that recovered *inside* the item did not
// read it, it patched it — and the strict parse of the same
// bytes failed outright. Both must ask the fragment
// question at the same point or the editor would report
// errors on a file the formatter formats: `if (a) begin x =
// 1; end` is a generate-if whose body holds a statement.
let patched = self.diagnostics.len() > diags_before;
if prelude_only && patched {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
prelude_only &= is_prelude(&item.kind) && !patched;
items.push(item);
}
Err(e) => {
if prelude_only {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
if !self.tolerant {
return Err(e);
}
// Exactly what `item_or_recover` would have done, on the
// cursor the failure left behind — re-running the item to
// get there would move the comments it already drained.
// Asked once: a file that is not a fragment stays one.
prelude_only = false;
let raw = self.recover(start_pos, start, e);
let span = raw.span;
items.push(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span });
}
}
}
let dangling = self.take_dangling();
// The cursor is on the EOF token, whose empty span sits at the end of
// the source, so this covers the whole file.
let span = TextRange::new(0, self.cur().span.end);
Ok(SourceFile {
items,
dangling,
span,
constraint_fallbacks: self.constraint_fallbacks,
covergroups: self.covergroups,
covergroup_fallbacks: self.covergroup_fallbacks,
prop_seq_decls: self.prop_seq_decls,
prop_seq_fallbacks: self.prop_seq_fallbacks,
assertions: self.assertions,
assertion_fallbacks: self.assertion_fallbacks,
fragment: None,
})
}
/// Items nest through generate blocks and package bodies. Gated.
pub(super) fn parse_item(&mut self) -> PResult<Item> {
self.enter()?;
let out = self.parse_item_inner();
self.leave();
out
}
fn parse_item_inner(&mut self) -> PResult<Item> {
// Before the attribute loop: `(* keep *)` is code, not trivia, so it
// belongs inside the item's span.
let start = self.here();
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
let kind = match self.parse_item_kind() {
Ok(kind) => kind,
Err(e) => self.split_conditional_item(&mark, e)?,
};
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Item { meta, kind, span })
}
fn parse_item_kind(&mut self) -> PResult<ItemKind> {
if self.at_macro_item() || self.at_spaced_macro_call() {
return Ok(ItemKind::MacroItem(self.parse_macro_call()?));
}
// A null item. Nothing else in the item grammar starts with `;`, so
// one token settles it — and it is tested here rather than in the
// `TokenKind` match below because punctuation is matched by text
// everywhere in this file. See `ItemKind::Empty`.
if self.cur().is_sym(";") {
self.bump();
return Ok(ItemKind::Empty);
}
let t = self.cur();
match t.kind {
TokenKind::Directive => {
self.note_item_conditional();
Ok(ItemKind::Directive(self.take_raw_text()))
}
TokenKind::Keyword => self.parse_keyword_item(),
TokenKind::Ident if self.at_bind_directive() => self.parse_bind().map(ItemKind::Bind),
// `NoNMI: assume property (...)` and `restrict property (...)`:
// a label, or the non-keyword `restrict`, in front of a
// concurrent assertion.
TokenKind::Ident if self.at_concurrent_assertion() => self.parse_assertion_item(),
TokenKind::Ident => self.parse_ident_item(),
TokenKind::SystemIdent if ELAB_TASKS.contains(&t.text.as_str()) => {
let call = self.parse_expr()?;
self.expect_sym(";")?;
Ok(ItemKind::ElabTask(call))
}
_ => self.error("expected item"),
}
}
/// The item that a keyword at the cursor begins.
///
/// A dispatch table over the item keywords: one arm per keyword, each
/// arm a call into the grammar file that owns the construct. It stays
/// one function on purpose, for the same reason
/// [`Parser::parse_keyword_stmt`] does.
fn parse_keyword_item(&mut self) -> PResult<ItemKind> {
let kw = self.cur().text.clone();
match kw.as_str() {
"module" | "macromodule" => self.parse_module("endmodule").map(ItemKind::Module),
// `interface class` is a class, not an interface (IEEE 1800
// §8.26): its body is a subset of a class body (pure virtual
// method prototypes, parameters, typedefs) and it closes with
// `endclass`, so it *is* a [`ClassDecl`] — the word `interface`
// rides along in [`ClassDecl::prefix`] beside `virtual`, which is
// where every keyword written in front of `class` already lives.
"interface" if !self.nth(1).is_kw("class") => {
self.parse_module("endinterface").map(ItemKind::Module)
}
"interface" => self.parse_class().map(ItemKind::Class),
// A `program` block is a module header over a module body with a
// different closer (IEEE 1800 §24.3) — the same node, the way an
// `interface` already is. Its stricter *legality* rules (no
// `always`, no instantiation of anything but interfaces) are a
// checker's business, not a formatter's.
"program" => self.parse_module("endprogram").map(ItemKind::Module),
"modport" => self.parse_modport().map(ItemKind::Modport),
"clocking" => self.parse_clocking(false).map(ItemKind::Clocking),
"default" if self.nth(1).is_kw("clocking") => {
self.bump();
self.parse_clocking(true).map(ItemKind::Clocking)
}
"default" if self.nth(1).is_kw("disable") => self.parse_default_disable_item(),
"package" => self.parse_package(),
"import" => {
// A string right after `import` is a DPI linkage spec, not a
// package name: `import "DPI-C" function void f();`.
if self.nth(1).kind == TokenKind::String {
return self.parse_dpi_import();
}
let paths = self.parse_import_list()?;
Ok(ItemKind::Import(paths))
}
"export" => self.parse_export().map(ItemKind::Export),
"timeunit" | "timeprecision" => {
let mut parts: Vec<String> = Vec::new();
while !self.cur().is_sym(";") && !self.at_eof() {
parts.push(self.bump().text);
}
self.expect_sym(";")?;
Ok(ItemKind::Timeunit(parts.join(" ")))
}
"typedef" => self.parse_typedef().map(ItemKind::Typedef),
"parameter" | "localparam" => {
let d = self.parse_param_decl()?;
self.expect_sym(";")?;
Ok(ItemKind::ParamDecl(d))
}
"input" | "output" | "inout" => {
let d = self.parse_port_decl()?;
Ok(ItemKind::PortDecl(d))
}
"genvar" => {
self.bump();
let mut names = vec![self.expect_name()?];
while self.eat_sym(",") {
names.push(self.expect_name()?);
}
self.expect_sym(";")?;
Ok(ItemKind::Genvar(names))
}
"assign" => self.parse_cont_assign().map(ItemKind::ContAssign),
"always" | "always_comb" | "always_ff" | "always_latch" => {
let kw = self.bump().text;
let stmt = self.parse_stmt()?;
Ok(ItemKind::Always { kw, stmt })
}
"initial" => {
self.bump();
Ok(ItemKind::Initial(self.parse_stmt()?))
}
"final" => {
self.bump();
Ok(ItemKind::Final(self.parse_stmt()?))
}
"generate" => {
self.bump();
let mut items = Vec::new();
while !self.at_body_end("endgenerate") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endgenerate")?;
Ok(ItemKind::GenerateRegion { items, dangling })
}
// A bare `begin … end` where an item belongs — at module scope or
// straight inside a generate region. It is not a module item
// (IEEE 1800 §23.2.1), so strict mode falls through to the
// default arm and refuses it exactly as it always has. Tolerant
// mode reads it the way every tool that accepts it does — as an
// unnamed generate block — and still records the diagnostic, so
// the file is reported as not parsing cleanly and the formatter
// goes on emitting it unchanged. What is bought is the rest of
// the body: without this the item fails, recovery skips to a sync
// point and everything after the block is lost. The
// `module-begin-block` and `v2001-generate-begin` lints read the
// node.
"begin" if self.tolerant => {
self.record("`begin`/`end` block is not a module item");
self.parse_gen_block().map(|b| ItemKind::GenBlock(Box::new(b)))
}
"if" => self.parse_gen_if().map(ItemKind::GenIf),
"for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))),
"case" => self.parse_gen_case().map(ItemKind::GenCase),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"class" => self.parse_class().map(ItemKind::Class),
"let" => self.parse_let().map(ItemKind::Let),
"constraint" => self.parse_constraint(),
"covergroup" => self.parse_covergroup(),
"assert" | "assume" | "cover" if self.at_concurrent_assertion() => {
self.parse_assertion_item()
}
"property" | "sequence" => self.parse_prop_seq_decl(),
// Vendor and formal collateral, each one an opaque leaf. The
// bodies are grammars of their own — a specify path with its
// `=>`/`*>` connections, a UDP truth table, a checker's assertion
// vocabulary, a config's `design`/`instance`/`liblist` clauses —
// that lucisv models none of, and there is no layout convention
// worth inventing for any of them, so the whole block is copied
// out of the source by span the way a `property` declaration is.
// See `docs/features/vendor-formal-grammar/README.md`.
"specify" => self.parse_opaque_block("endspecify").map(ItemKind::Verbatim),
"primitive" => self.parse_opaque_block("endprimitive").map(ItemKind::Verbatim),
"checker" => self.parse_opaque_block("endchecker").map(ItemKind::Verbatim),
"config" => self.parse_opaque_block("endconfig").map(ItemKind::Verbatim),
// A `table ... endtable` only ever stands inside a `primitive`,
// whose scan already swallows it; this arm is what a stray one —
// or a UDP whose `primitive` line is behind an `` `ifdef `` — gets
// instead of an unsupported-construct error.
"table" => self.parse_opaque_block("endtable").map(ItemKind::Verbatim),
"library" => self.parse_opaque_line().map(ItemKind::Verbatim),
"specparam" => self.parse_specparam(),
"alias" => self.parse_alias(),
// A run of member qualifiers (`virtual`, `local rand`, `static`,
// `pure virtual`, ...) does not say what it qualifies; the first
// keyword past the run does. Nothing is consumed here, so each
// branch parses its own construct from the first qualifier on.
_ if MEMBER_QUALIFIERS.contains(&kw.as_str()) => {
match self.member_head().text.as_str() {
"class" => self.parse_class().map(ItemKind::Class),
"function" => self.parse_function().map(ItemKind::Function),
"task" => self.parse_task().map(ItemKind::Task),
"constraint" => self.parse_constraint(),
"covergroup" => self.parse_covergroup(),
_ => self.parse_data_decl().map(ItemKind::DataDecl),
}
}
"defparam" => {
self.bump();
let mut pairs = Vec::new();
loop {
let lhs = self.parse_expr()?;
self.expect_sym("=")?;
let rhs = self.parse_expr()?;
pairs.push((lhs, rhs));
if !self.eat_sym(",") {
break;
}
}
self.expect_sym(";")?;
Ok(ItemKind::Defparam(pairs))
}
_ if GATE_KEYWORDS.contains(&kw.as_str()) => {
self.parse_gate_instantiation().map(ItemKind::GateInstantiation)
}
// `enum`/`struct`/`union` here is an anonymous aggregate type
// introducing a variable (`enum logic [1:0] {A, B} state;`) — the
// `typedef` spelling is taken by the arm above.
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "signed" | "unsigned" | "enum" | "struct" | "union") =>
{
let d = self.parse_data_decl()?;
Ok(ItemKind::DataDecl(d))
}
_ => self.error(format!("unsupported construct starting with keyword `{kw}`")),
}
}
/// Item starting with an identifier: either a module instantiation or a
/// declaration with a user-defined type.
fn parse_ident_item(&mut self) -> PResult<ItemKind> {
// Skip over a package scope chain for lookahead purposes.
let mut p = self.pos;
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let t1 = self.nth(p + 1 - self.pos);
if t1.is_sym("#") {
// `sub #(.W(8)) u (...);` and `port_t #(int) p;` open the same
// way. What follows the name after the overrides tells them
// apart: an instance has a connection list or an array range,
// a declaration goes straight to `;`, `,` or `=`.
if self.tokens.get(p + 2).is_some_and(|t| t.is_sym("(")) {
let name = self.scan_matching(p + 2, "(", ")");
let after = self.tokens.get(name + 1);
// `[` after the declarator is an instance array range only
// when a connection list follows it; `item #(A, B) q[$];`
// is a declaration whose declarator has an unpacked dim.
let is_instance = after.is_some_and(|t| t.is_sym("("))
|| (after.is_some_and(|t| t.is_sym("[")) && {
let end = self.scan_matching(name + 1, "[", "]");
self.tokens.get(end).is_some_and(|t| t.is_sym("("))
});
if self.tokens.get(name).is_some_and(|t| t.kind == TokenKind::Ident) && !is_instance
{
return self.parse_data_decl().map(ItemKind::DataDecl);
}
}
return self.parse_instantiation().map(ItemKind::Instantiation);
}
if t1.kind == TokenKind::Ident {
let t2 = self.nth(p + 2 - self.pos);
if t2.is_sym("(") {
return self.parse_instantiation().map(ItemKind::Instantiation);
}
if t2.is_sym("[") {
let after = self.scan_matching(p + 2, "[", "]");
if self.tokens.get(after).is_some_and(|t| t.is_sym("(")) {
return self.parse_instantiation().map(ItemKind::Instantiation);
}
}
return self.parse_data_decl().map(ItemKind::DataDecl);
}
if t1.is_sym("[") {
return self.parse_data_decl().map(ItemKind::DataDecl);
}
self.error("expected declaration or instantiation")
}
/// The first token past the run of [`MEMBER_QUALIFIERS`] at the cursor —
/// the one that says what is being declared. Consumes nothing.
fn member_head(&self) -> &Token {
let mut i = self.pos;
while self.tokens[i].kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.tokens[i].text.as_str())
&& i + 1 < self.tokens.len()
{
i += 1;
}
&self.tokens[i]
}
/// Consume the run of [`MEMBER_QUALIFIERS`] at the cursor, in source order.
pub(super) fn take_member_prefix(&mut self) -> Vec<Qualifier> {
let mut out = Vec::new();
while self.cur().kind == TokenKind::Keyword
&& MEMBER_QUALIFIERS.contains(&self.cur().text.as_str())
{
let text = self.bump().text;
// `local /*c*/ static` — the gap after each keyword is that
// keyword's, so two comments in one run stay in their own gaps.
out.push(Qualifier { text, after: self.take_gap() });
}
out
}
fn parse_package(&mut self) -> PResult<ItemKind> {
let kw = self.bump().text;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.at_body_end("endpackage") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("endpackage")?;
let (end_label_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(ItemKind::Package {
kw,
before_name,
name,
name_span,
before_semi,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
})
}
pub(super) fn parse_import_list(&mut self) -> PResult<Vec<ImportPath>> {
self.expect_kw("import")?;
let paths = self.parse_package_paths(false)?;
self.expect_sym(";")?;
Ok(paths)
}
/// The comma-separated `pkg::item` / `pkg::*` list of an `import` or an
/// `export`, without the leading keyword or the closing `;`.
/// `allow_star_pkg` admits `export *::*;`, whose left half is a wildcard
/// too — no `import` spells that.
fn parse_package_paths(&mut self, allow_star_pkg: bool) -> PResult<Vec<ImportPath>> {
let mut paths = Vec::new();
loop {
let star = self.cur().span;
let pkg = if allow_star_pkg && self.cur().is_sym("*") {
self.bump();
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
};
self.expect_sym("::")?;
let star = self.cur().span;
let item = if self.eat_sym("*") {
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
};
paths.push(ImportPath { pkg, item });
if !self.eat_sym(",") {
break;
}
}
Ok(paths)
}
// ------------------------------------------------------------------
// DPI (IEEE 1800 §35.5) and package export (§26.6)
// ------------------------------------------------------------------
/// `import "DPI-C" [context|pure] [c_name =] function|task <prototype>;`.
/// The declaration is a function/task prototype with a linkage prefix, so
/// it becomes an ordinary [`FunctionDecl`] / [`TaskDecl`] carrying that
/// prefix — every consumer that already knows about functions sees one.
fn parse_dpi_import(&mut self) -> PResult<ItemKind> {
self.expect_kw("import")?;
let spec = self.expect_dpi_spec()?;
// `context` is not a reserved word, so it is only the property when an
// `=` does not turn it into the linkage name instead.
let property = if self.cur().is_kw("pure")
|| (self.cur().kind == TokenKind::Ident
&& self.cur().text == "context"
&& !self.nth(1).is_sym("="))
{
Some(self.bump().text)
} else {
None
};
let c_identifier = self.parse_dpi_c_identifier();
let dpi = DpiImport { spec, property, c_identifier };
if self.cur().is_kw("task") {
self.parse_task_decl(Some(dpi)).map(ItemKind::Task)
} else {
self.parse_function_decl(Some(dpi)).map(ItemKind::Function)
}
}
/// `export "DPI-C" [c_name =] function|task name;` or a package re-export
/// `export pkg::item, pkg::*;`.
fn parse_export(&mut self) -> PResult<ExportDecl> {
self.expect_kw("export")?;
if self.cur().kind == TokenKind::String {
let spec = self.expect_dpi_spec()?;
let c_identifier = self.parse_dpi_c_identifier();
if !self.cur().is_kw("function") && !self.cur().is_kw("task") {
return self.error("expected `function` or `task` in a DPI export");
}
let kw = self.bump().text;
let name = self.expect_name()?;
self.expect_sym(";")?;
return Ok(ExportDecl::Dpi(DpiExport { spec, c_identifier, kw, name }));
}
let paths = self.parse_package_paths(true)?;
self.expect_sym(";")?;
Ok(ExportDecl::Package(paths))
}
fn expect_dpi_spec(&mut self) -> PResult<String> {
if self.cur().kind == TokenKind::String {
Ok(self.bump().text)
} else {
self.error("expected a DPI linkage spec string")
}
}
/// The optional `c_name =` that gives the linkage symbol a name of its own.
fn parse_dpi_c_identifier(&mut self) -> Option<Name> {
if self.cur().kind != TokenKind::Ident || !self.nth(1).is_sym("=") {
return None;
}
let span = self.cur().span;
let name = Name { text: self.bump().text, span };
self.bump();
Some(name)
}
// ------------------------------------------------------------------
// Generate constructs
// ------------------------------------------------------------------
/// An `else if` chain recurses here directly, bypassing `parse_item`. Gated.
fn parse_gen_if(&mut self) -> PResult<GenIf> {
self.enter()?;
let out = self.parse_gen_if_inner();
self.leave();
out
}
fn parse_gen_if_inner(&mut self) -> PResult<GenIf> {
let start = self.here();
self.expect_kw("if")?;
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = self.parse_gen_block()?;
let els = if self.cur().is_kw("else") {
let meta = self.take_meta();
self.bump();
if self.cur().is_kw("if") {
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
} else {
let _ = meta;
Some(Box::new(GenElse::Block(self.parse_gen_block()?)))
}
} else {
None
};
Ok(GenIf { cond, then, els, span: self.span_from(start) })
}
fn parse_gen_for(&mut self) -> PResult<GenFor> {
self.expect_kw("for")?;
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let init_genvar = self.eat_kw("genvar");
let after_genvar = if init_genvar { self.take_gap() } else { Vec::new() };
let lhs = self.parse_unary()?;
let mut op_comments = BinaryComments { before: self.gap_before("="), after: Vec::new() };
self.expect_sym("=")?;
op_comments.after = self.take_gap();
let rhs = self.parse_expr()?;
let init =
SimpleAssign { lhs, op: "=".to_string(), op_comments: Box::new(op_comments), rhs };
comments.before_first_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_first_semi = self.take_gap();
let cond = self.parse_expr()?;
comments.before_second_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_second_semi = self.take_gap();
let step = self.parse_for_step()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
let body = self.parse_gen_block()?;
Ok(GenFor {
init,
init_genvar,
after_genvar,
cond,
step,
comments: Box::new(comments),
body,
})
}
fn parse_gen_case(&mut self) -> PResult<GenCase> {
self.expect_kw("case")?;
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
let mut items = Vec::new();
while !self.at_body_end("endcase") {
let start = self.here();
let mut meta = self.take_meta();
let mut before_colon = Vec::new();
let labels = if self.eat_kw("default") {
before_colon = self.gap_before(":");
let _ = self.eat_sym(":");
Vec::new()
} else {
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first, ":")?;
self.expect_sym(":")?;
labels
};
let body = self.parse_gen_block()?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
items.push(GenCaseItem { meta, labels, before_colon, body, span });
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok(GenCase { expr, items, dangling })
}
fn parse_gen_block(&mut self) -> PResult<GenBlock> {
let start = self.here();
if self.cur().is_kw("begin") {
// The gap between whatever came before and the `begin` belongs to
// the block — nothing else was written where it could attach.
let before_kw = self.take_gap();
self.bump();
let before_colon = self.gap_before(":");
let mut after_colon = Vec::new();
let label_name = if self.eat_sym(":") {
after_colon = self.take_gap();
Some(self.expect_name()?)
} else {
None
};
let (label, label_span) = split_label(label_name);
let mut items = Vec::new();
while !self.at_body_end("end") {
items.push(self.item_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_closer("end")?;
let (end_label_comments, end_name) = self.parse_label_with()?;
let (end_label, end_label_span) = split_label(end_name);
Ok(GenBlock {
before_kw,
before_colon,
after_colon,
label,
label_span,
is_block: true,
items,
dangling,
end_label_comments,
end_label,
end_label_span,
span: self.span_from(start),
})
} else {
let item = self.item_or_recover()?;
let span = item.span;
Ok(GenBlock {
before_kw: Vec::new(),
before_colon: Vec::new(),
after_colon: Vec::new(),
label: None,
label_span: None,
end_label_comments: Box::default(),
is_block: false,
items: vec![item],
dangling: Vec::new(),
end_label: None,
end_label_span: None,
span,
})
}
}
}