WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run

Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-03 18:28:33 -07:00
1 parent 6a15594ae8
commit f1d44a2a0c
12 files changed
+639 -82

No files matched your search

-23
View File
@@ -91,18 +91,6 @@ pub enum PortList {
NonAnsi(Vec<ListElem<NonAnsiPort>>),
}
impl PortList {
/// True when a tolerant parse recovered from an error inside this list.
/// Always false on a tree [`crate::parse`] built.
pub fn has_error(&self) -> bool {
match self {
PortList::None | PortList::Empty => false,
PortList::Ansi(ports) => ports.iter().any(ListElem::is_error),
PortList::NonAnsi(ports) => ports.iter().any(ListElem::is_error),
}
}
}
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
/// `name_span`: the port *is* its name, so `span` already is that range.
#[derive(Debug)]
@@ -256,17 +244,6 @@ pub enum Connections {
Named(Vec<ListElem<Connection>>),
}
impl Connections {
/// True when a tolerant parse recovered from an error inside this list.
/// Always false on a tree [`crate::parse`] built.
pub fn has_error(&self) -> bool {
match self {
Connections::Ordered(conns) => conns.iter().any(ListElem::is_error),
Connections::Named(conns) => conns.iter().any(ListElem::is_error),
}
}
}
#[derive(Debug)]
pub struct OrderedConn {
pub meta: Meta,
+5 -2
View File
@@ -97,11 +97,14 @@ impl<'a> Parser<'a> {
self.bump();
after_hash = self.take_gap();
self.expect_sym("(")?;
let mark = self.diags_mark();
let mut list = Vec::new();
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
let at = self.pos;
list.push(self.element_or_recover(|p| p.parse_connection())?);
let recovered = list.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
@@ -113,7 +116,7 @@ impl<'a> Parser<'a> {
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -124,7 +127,7 @@ impl<'a> Parser<'a> {
&mut param_directives,
n,
);
self.close_list(list.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
params = Some(list);
}
Ok(ClassExtends {
+22 -6
View File
@@ -256,6 +256,7 @@ impl<'a> Parser<'a> {
Self::push_scope_segment(&mut module, &segment);
}
let module_span = self.span_from(module_start);
let mark = self.diags_mark();
let param_comments = self.take_before_open("#");
let mut params = None;
let mut after_hash = Vec::new();
@@ -268,7 +269,9 @@ impl<'a> Parser<'a> {
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
let at = self.pos;
list.push(self.element_or_recover(|p| p.parse_connection())?);
let recovered = list.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
@@ -285,7 +288,7 @@ impl<'a> Parser<'a> {
// the list, and after a directive only the closing bracket
// does — an `` `ifdef`` arm may end without a comma and
// still be followed by an `` `else`` arm.
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -297,7 +300,7 @@ impl<'a> Parser<'a> {
&mut param_directives,
n,
);
self.close_list(list.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
params = Some(list);
}
let mut instances = Vec::new();
@@ -308,9 +311,10 @@ impl<'a> Parser<'a> {
let dims = self.parse_dims()?;
let conn_comments = self.take_before_open("(");
self.expect_sym("(")?;
let conn_mark = self.diags_mark();
let mut conn_directives = Vec::new();
let conns = self.parse_connections(&mut conn_directives)?;
self.close_list(conns.has_error())?;
self.close_list(conn_mark)?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
@@ -332,7 +336,12 @@ impl<'a> Parser<'a> {
}
}
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
// As in a module header (`Parser::parse_module`): once something in
// this instantiation has been reported, a missing `;` is part of the
// same typo, and the item is worth more than a second message. It is
// what leaves the `wire w;` under a half-typed `sub u (.a(` an item of
// the module.
self.expect_after_recovery(";", self.recovered_since(mark))?;
Ok(Instantiation {
module,
module_span,
@@ -377,7 +386,9 @@ impl<'a> Parser<'a> {
if self.at_named_connection() {
let mut conns = Vec::new();
loop {
let at = self.pos;
conns.push(self.element_or_recover(|p| p.parse_connection())?);
let recovered = conns.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
@@ -389,7 +400,7 @@ impl<'a> Parser<'a> {
}
}
let dirs = self.take_list_directives(directives, conns.len());
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -402,13 +413,18 @@ impl<'a> Parser<'a> {
} else {
let mut conns = Vec::new();
loop {
let at = self.pos;
conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?);
let recovered = conns.last().is_some_and(ListElem::is_error);
let comma = match conns.last() {
Some(ListElem::Ok(last)) => last.comma,
// A positional connection reads its own separator; an
// error element leaves the `,` for the list, as in a
// non-ANSI port list.
_ => self.eat_sym(","),
};
let dirs = self.take_list_directives(directives, conns.len());
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -91,8 +91,9 @@ impl<'a> Parser<'a> {
self.bump();
self.expect_sym("(")?;
let cond = self.cond_or_recover()?;
self.expect_after_recovery(")", cond.is_error())?;
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
let recovered = cond.is_error();
self.expect_after_recovery(")", recovered)?;
Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) })
}
"do" => {
self.bump();
@@ -112,8 +113,9 @@ impl<'a> Parser<'a> {
self.bump();
self.expect_sym("(")?;
let count = self.cond_or_recover()?;
self.expect_after_recovery(")", count.is_error())?;
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
let recovered = count.is_error();
self.expect_after_recovery(")", recovered)?;
Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) })
}
"forever" => {
self.bump();
@@ -296,7 +298,7 @@ impl<'a> Parser<'a> {
comments.before_close = self.gap_before(")");
}
self.expect_after_recovery(")", recovered)?;
let body = Box::new(self.parse_stmt()?);
let body = Box::new(self.body_after_recovery(recovered)?);
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
}
+24 -13
View File
@@ -32,6 +32,7 @@ impl<'a> Parser<'a> {
imports.push(HeaderImport { meta, paths });
}
let param_comments = self.take_before_open("#");
let mark = self.diags_mark();
let ParamPortList {
ports: param_ports,
directives: param_directives,
@@ -41,12 +42,10 @@ impl<'a> Parser<'a> {
let port_comments = self.take_before_open("(");
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
let before_semi = self.gap_before(";");
// A header that already recovered keeps its `;` optional: the missing
// one is part of the typo already reported, and the body behind it is
// what the module is for.
let recovered =
param_ports.iter().flatten().any(|p| p.is_error()) || ports.has_error();
self.expect_after_recovery(";", recovered)?;
// A header that already reported something keeps its `;` optional: the
// missing one is part of the typo already reported, and the body
// behind it is what the module is for.
self.expect_after_recovery(";", self.recovered_since(mark))?;
let mut items = Vec::new();
while !self.at_body_end(end_kw) {
items.push(self.item_or_recover()?);
@@ -326,11 +325,14 @@ impl<'a> Parser<'a> {
self.bump();
out.after_hash = self.take_gap();
self.expect_sym("(")?;
let mark = self.diags_mark();
let mut list = Vec::new();
self.take_list_directives(&mut out.directives, 0);
if !self.cur().is_sym(")") {
loop {
let at = self.pos;
list.push(self.element_or_recover(|p| p.parse_param_port())?);
let recovered = list.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
@@ -348,13 +350,13 @@ impl<'a> Parser<'a> {
// (`` `else``), or the arm may have been the tail of the list.
// In tolerant mode the closing bracket decides on its own; see
// [`Parser::list_ends`].
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
}
out.dangling = self.take_dangling();
self.close_list(list.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
out.ports = Some(list);
Ok(out)
}
@@ -441,6 +443,7 @@ impl<'a> Parser<'a> {
return Ok((PortList::None, Vec::new(), Vec::new()));
}
self.bump();
let mark = self.diags_mark();
// Directives before the first port. Harvested here rather than in the
// loop below because both the ANSI/non-ANSI decision and the
// written-but-empty check read the token after them.
@@ -474,7 +477,9 @@ impl<'a> Parser<'a> {
if ansi {
let mut ports = Vec::new();
loop {
let at = self.pos;
ports.push(self.element_or_recover(|p| p.parse_ansi_port())?);
let recovered = ports.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = ports.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
@@ -486,13 +491,13 @@ impl<'a> Parser<'a> {
}
}
let dirs = self.take_list_directives(&mut directives, ports.len());
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
// Comments on their own lines before the `)` belong inside it.
let dangling = self.take_dangling();
self.close_list(ports.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
// A trailing comment on the closing line belongs to the last
// port — but only when the header did not write a `;` right
// after the `)`. `module m (input a) /*c*/ ;` writes its comment
@@ -509,18 +514,24 @@ impl<'a> Parser<'a> {
} else {
let mut ports = Vec::new();
loop {
let at = self.pos;
ports.push(self.element_or_recover(|p| p.parse_non_ansi_port())?);
let recovered = ports.last().is_some_and(ListElem::is_error);
let comma = match ports.last() {
Some(ListElem::Ok(last)) => last.comma,
_ => false,
// A non-ANSI port reads its own separator, so an error
// element — which never got that far — leaves the `,` for
// the list to take. Leaving it under the cursor was the
// 2026-09-03 runaway: see the work log.
_ => self.eat_sym(","),
};
let dirs = self.take_list_directives(&mut directives, ports.len());
if self.list_ends(comma, dirs.any) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
let dangling = self.take_dangling();
self.close_list(ports.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
Ok((PortList::NonAnsi(ports), dangling, directives))
}
}
+101 -22
View File
@@ -21,6 +21,7 @@
//!
//! See `docs/features/header-recovery/README.md`.
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
use super::*;
impl<'a> Parser<'a> {
@@ -35,21 +36,49 @@ impl<'a> Parser<'a> {
self.at_eof() || t.is_sym(")") || t.is_sym(";") || self.at_sync_stop()
}
/// Whether a header list's loop is over, having just read an element that
/// was (`comma`) or was not followed by a `,`, with `dirs_any` recording
/// whether a compiler directive was harvested after it.
/// Whether a header list's loop is over. `start` is the cursor the
/// iteration began at, `comma` whether a `,` followed the element just
/// read, `dirs_any` whether a compiler directive did, and `recovered`
/// whether that element was an error the list recovered from.
///
/// Strict mode asks exactly what the loops asked before this file
/// existed. Tolerant mode asks the closing bracket instead of the comma: a
/// missing `,` in the middle of a port list would otherwise throw away
/// every port after it. On a list that parses the two agree — the loops
/// all end with the cursor on their `)` — which is what keeps a tolerant
/// parse of a good file identical to a strict one.
pub(super) fn list_ends(&self, comma: bool, dirs_any: bool) -> bool {
if self.tolerant {
return self.at_list_end();
/// Strict mode asks exactly what the loops asked before this file existed,
/// and looks at neither `start` nor `recovered`. Tolerant mode asks four
/// things:
///
/// * **progress**: an iteration that consumed no token ends the list, full
/// stop. This is the termination guarantee, and it is structural rather
/// than argued — no reasoning about what an element parser or a skip did
/// can make one of these loops spin, because the loop itself refuses to
/// go round again on an unmoved cursor. (It *was* argued before, and the
/// argument had a hole: see the work log for 2026-09-03.)
/// * the **closing bracket**, not the comma — a missing `,` in the middle
/// of a port list would otherwise throw away every port after it. On a
/// list that parses, the two agree: every one of these loops ends with
/// the cursor on its own `)`, which is what keeps a tolerant parse of a
/// good file identical to a strict one. Reading on past a missing comma
/// is not silent — it is one diagnostic, recorded here.
/// * after a **recovered** element, the comma decides again: the skip ends
/// at the separator when there is one, so no comma means the list is not
/// there any more and what follows belongs to the enclosing construct.
/// That is what leaves the `wire w;` under a half-typed `sub u (.a(` as
/// an item of the module instead of swallowing it into the list.
pub(super) fn list_ends(
&mut self,
start: usize,
comma: bool,
dirs_any: bool,
recovered: bool,
) -> bool {
if !self.tolerant {
return (!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"));
}
(!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"))
if self.pos == start || self.at_list_end() || (recovered && !comma) {
return true;
}
if !comma && !dirs_any {
self.record("expected `,`");
}
false
}
/// Parse one element of a bracketed header list; in tolerant mode turn a
@@ -63,26 +92,59 @@ impl<'a> Parser<'a> {
let start = self.here();
match parse(self) {
Ok(value) => Ok(ListElem::Ok(value)),
Err(e) if self.tolerant => {
Err(e) if self.tolerant && !self.at_conditional_directive() => {
Ok(ListElem::Error(self.recover_element(start_pos, start, e)))
}
Err(e) => Err(e),
}
}
/// Consume the `)` that closes a header list.
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
/// `` `endif ``: a directive that opens, continues or closes a
/// conditional-compilation region.
///
/// In tolerant mode a missing one is not a failure: with `recovered` set,
/// the element that failed has already said what is wrong and a second
/// message about the same typo would be noise; without it, the missing
/// bracket is itself the news and gets one diagnostic. Strict mode fails
/// with exactly the message [`Parser::expect_sym`] would have used.
pub(super) fn close_list(&mut self, recovered: bool) -> PResult<()> {
/// A list element that failed *there* is one arm of a construct written
/// across the arms of a region — a header split by `` `ifdef `` — and the
/// enclosing item or statement captures the whole of it verbatim
/// (`split.rs`). Balanced directives never reach here at all;
/// `take_list_directives` harvests those between elements. So this error
/// is passed out untouched: recovering it would take that rescue away and
/// give a file the strict parser reads *correctly* a different tree, which
/// is the one thing tolerant mode may never do. Found by
/// `tolerant_parse_equals_strict_parse_on_valid_sources` over
/// `directive_in_statements.cases`; see the work log for 2026-09-03.
fn at_conditional_directive(&self) -> bool {
let t = self.cur();
opens_conditional(t) || continues_conditional(t) || closes_conditional(t)
}
/// How many diagnostics stand recorded — a mark to ask
/// [`Parser::recovered_since`] about later. Always 0 in strict mode, which
/// is what makes every question asked of it answer "no" there.
pub(super) fn diags_mark(&self) -> usize {
self.diagnostics.len()
}
/// Whether anything was reported since `mark`: whether the header being
/// parsed has already told the user what is wrong with it.
pub(super) fn recovered_since(&self, mark: usize) -> bool {
self.diagnostics.len() > mark
}
/// Consume the `)` that closes a header list, `mark` being the diagnostic
/// count when the list began.
///
/// In tolerant mode a missing one is not a failure: where the list already
/// reported something, that message is the one about this typo and a
/// second would be noise; where it did not, the missing bracket is itself
/// the news and gets one diagnostic. Strict mode fails with exactly the
/// message [`Parser::expect_sym`] would have used.
pub(super) fn close_list(&mut self, mark: usize) -> PResult<()> {
if self.eat_sym(")") {
return Ok(());
}
if self.tolerant {
if !recovered {
if !self.recovered_since(mark) {
self.record("expected `)`");
}
return Ok(());
@@ -105,6 +167,23 @@ impl<'a> Parser<'a> {
self.expect_sym(sym).map(|_| ())
}
/// The body of a statement whose header was recovered.
///
/// Where the enclosing block or file has already ended — `for (i = 0; i <`
/// with an `end` under it — there is no statement to read, and reading one
/// would consume the `end` the block is waiting for. The body is then an
/// empty error leaf: a loop with nothing typed in it yet is still a loop,
/// and inventing a `;` would put a token in the tree the source never
/// wrote. Reached only in tolerant mode, and only after a recovery.
pub(super) fn body_after_recovery(&mut self, recovered: bool) -> PResult<Stmt> {
if !(recovered && self.tolerant && (self.at_eof() || self.at_sync_stop())) {
return self.parse_stmt();
}
let span = TextRange::empty(self.here());
let raw = RawText { text: String::new(), col: self.cur().col, span };
Ok(Stmt { meta: Meta::default(), kind: StmtKind::Error(raw), before_semi: Vec::new(), span })
}
/// The condition between the brackets of an `if`, `while`, `repeat`,
/// `case` or `do … while` header, whose `(` the caller has consumed.
///
+3 -2
View File
@@ -162,8 +162,9 @@ impl<'a> Parser<'a> {
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let cond = self.cond_or_recover()?;
self.expect_after_recovery(")", cond.is_error())?;
let then = Box::new(self.parse_stmt()?);
let recovered = cond.is_error();
self.expect_after_recovery(")", recovered)?;
let then = Box::new(self.body_after_recovery(recovered)?);
let mut else_comments = Vec::new();
let els = if self.cur().is_kw("else") {
// Whatever was written in the gap before `else` stays on the
+5 -2
View File
@@ -221,8 +221,11 @@ impl<'a> Parser<'a> {
self.bump();
return Ok(TfPorts { args, dangling });
}
let mark = self.diags_mark();
loop {
let at = self.pos;
args.push(self.element_or_recover(|p| p.parse_tf_arg(allow_unnamed))?);
let recovered = args.last().is_some_and(ListElem::is_error);
let more;
if let Some(ListElem::Ok(last)) = args.last_mut() {
self.take_before_sep(&mut last.meta, ",");
@@ -231,14 +234,14 @@ impl<'a> Parser<'a> {
} else {
more = self.eat_sym(",");
}
if self.list_ends(more, false) {
if self.list_ends(at, more, false, recovered) {
break;
}
}
if let Some(ListElem::Ok(last)) = args.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
self.close_list(args.iter().any(ListElem::is_error))?;
self.close_list(mark)?;
Ok(TfPorts { args, dangling: Vec::new() })
}
+186 -5
View File
@@ -490,18 +490,199 @@ fn a_half_typed_declaration_is_one_error_node() {
assert!(m.end_label.is_none());
}
/// **Inverted by header recovery (TODO §32).** Until 2026-09-03 the unclosed
/// `(` swallowed everything up to the next `;` and the whole instantiation was
/// one `ItemKind::Error`, `wire w;` included. Now the instantiation keeps its
/// name and the connection that was typed, the half-typed one is an error
/// *element*, and the declaration under it is an item of the module again.
#[test]
fn a_half_typed_instantiation_is_one_error_node() {
fn a_half_typed_instantiation_costs_one_connection() {
let src = "module m;\n sub u0 (.a(\n wire w;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
// The unclosed `(` swallows what follows it up to the sync point: a
// bracket the skip did not open ends it, otherwise the `;`.
assert!(matches!(&m.items[0].kind, ItemKind::Error(_)), "{}", kind_name(&m.items[0]));
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation, got {}", kind_name(&m.items[0]))
};
assert_eq!(inst.module, "sub");
assert_eq!(inst.instances[0].name, "u0");
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
assert_eq!(conns.len(), 1);
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
// The line under the broken connection is the module's again, not part of
// the list: `wire w;` is a sibling item.
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
assert_eq!(error_nodes(&file).len(), 1);
}
// ----------------------------------------------------------------------
// Header recovery (TODO §32): one test per shape, with exact counts
// ----------------------------------------------------------------------
/// (a) The QA shape this round was written for: a parameter with no value.
/// One diagnostic, one item, and a module that still holds its body.
#[test]
fn a_half_typed_parameter_costs_one_parameter() {
let src = "module m #(parameter W = , parameter X = 4) (input a); wire ok; endmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(file.items.len(), 1, "{:?}", file.items.iter().map(kind_name).collect::<Vec<_>>());
let m = module_named(&file, "m");
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 2);
assert_eq!(params[0].error().map(|r| r.text.as_str()), Some("parameter W ="));
assert_eq!(params[1].ok().map(|p| p.name.as_str()), Some("X"));
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.len(), 1);
assert_eq!(ports[0].ok().map(|p| p.name.as_str()), Some("a"));
assert_eq!(m.items.len(), 1, "the body survives the header");
assert!(matches!(&m.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[0]));
}
/// (b) The missing comma of a port half typed on the line above: the list
/// reads on to the ports after it, and says once that the `,` is missing.
#[test]
fn a_missing_comma_in_a_port_list_keeps_the_ports_after_it() {
let src = "module m (input logic a, inp\n output b);\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert!(diags[0].message.starts_with("expected `,`"), "{}", diags[0]);
let PortList::Ansi(ports) = &module_named(&file, "m").ports else { panic!("ANSI ports") };
let names: Vec<&str> = ports.iter().filter_map(|p| p.ok()).map(|p| p.name.as_str()).collect();
assert_eq!(names, ["a", "inp", "b"], "the port after the typo survives");
assert_eq!(error_nodes(&file).len(), 0, "a missing comma costs no element");
}
/// (c) A parameter list truncated at end of file — the mid-edit state itself.
/// The module keeps the parameter that was typed; the two diagnostics are the
/// unclosed `)` and the unclosed module, one each.
#[test]
fn a_parameter_list_truncated_at_eof_keeps_its_module() {
let src = "module m #(parameter W = 8,\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "{diags:?}");
assert!(diags[0].message.starts_with("expected `)`"), "{}", diags[0]);
assert!(diags[1].message.starts_with("expected `endmodule`"), "{}", diags[1]);
let m = module_named(&file, "m");
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 1);
assert_eq!(params[0].ok().map(|p| p.name.as_str()), Some("W"));
}
/// (d) The `for` header the error-recovery README documented as costing two
/// diagnostics: the `;`s inside it are invisible to the skip now, so it costs
/// one, and the loop keeps its body.
#[test]
fn a_half_typed_for_header_keeps_the_loop_and_its_body() {
let src = "module m;\n initial begin\n for (i = 0; i < ; i = i + 1) x = 1;\n y = 2;\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 2, "the statement after the loop is untouched");
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
let Some(Expr { kind: ExprKind::Error(raw), .. }) = cond else {
panic!("expected an error condition")
};
assert_eq!(raw.text, "i = 0; i < ; i = i + 1");
assert!(matches!(body.kind, StmtKind::Assign { .. }), "the body is the `x = 1;`");
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }));
}
/// (d′) The same header truncated mid-condition, where the block ends right
/// under it: the loop survives with an empty body rather than eating the
/// `end` its block is waiting for.
#[test]
fn a_for_header_truncated_mid_condition_does_not_eat_the_end() {
let src = "module m;\n initial begin\n for (int i = 0; i <\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 1);
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
assert!(matches!(cond, Some(Expr { kind: ExprKind::Error(_), .. })));
let StmtKind::Error(raw) = &body.kind else { panic!("expected an empty body") };
assert_eq!(raw.text, "", "nothing was typed there, and nothing is invented");
}
/// (f) A formal list left open, with the body under it: the function and the
/// module around it both survive.
#[test]
fn a_half_typed_formal_list_keeps_its_function() {
let src = "module m;\n function int f(input int a,\n f = a;\n endfunction\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 1);
let ItemKind::Function(f) = &m.items[0].kind else {
panic!("expected a function, got {}", kind_name(&m.items[0]))
};
assert_eq!(f.name, "f");
assert_eq!(f.args.first().and_then(|a| a.ok()).map(|a| a.name.as_str()), Some("a"));
}
/// (g) A condition left open, with the statements under it: the `if` keeps
/// its shape and its then-branch.
#[test]
fn a_half_typed_if_condition_keeps_its_branch() {
let src = "module m;\n initial begin\n if (a &&\n x = 1;\n y = 2;\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 1);
let StmtKind::If { cond, then, els, .. } = &stmts[0].kind else { panic!("expected an if") };
assert!(matches!(cond.kind, ExprKind::Error(_)), "{:?}", cond.kind);
assert!(els.is_none());
assert!(matches!(then.kind, StmtKind::Assign { .. }), "the branch is the `y = 2;`");
}
/// The other statement headers recover through the same helper, so one test
/// covers them: each keeps its node, its body and exactly one diagnostic.
#[test]
fn the_other_statement_headers_recover_the_same_way() {
let shapes: &[(&str, &str)] = &[
("while", "module m;\n initial begin\n while (a &&\n x = 1;\n end\nendmodule\n"),
("repeat", "module m;\n initial begin\n repeat (a &&\n x = 1;\n end\nendmodule\n"),
("case", "module m;\n initial begin\n case (a &&\n x = 1;\n endcase\n end\nendmodule\n"),
];
for (name, src) in shapes {
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{name}: {diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("{name}: expected initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("{name}: expected a block") };
let kind = &stmts[0].kind;
let cond = match kind {
StmtKind::While { cond, .. } => cond,
StmtKind::Repeat { count, .. } => count,
StmtKind::Case { expr, .. } => expr,
other => panic!("{name}: {:?}", std::mem::discriminant(other)),
};
assert!(matches!(cond.kind, ExprKind::Error(_)), "{name}: {:?}", cond.kind);
}
}
/// The whole point, stated once: a broken header no longer costs the module.
/// This is the shape the error-recovery README's QA finding described — three
/// items and two diagnostics — measured again here as one and one.
#[test]
fn a_broken_header_no_longer_distorts_the_tree() {
let src = "module m #(parameter W = , parameter X = 4) (input a);\n wire ok;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(file.items.len(), 1, "the body no longer re-parses at file scope");
let m = module_named(&file, "m");
assert!(m.end_label.is_none() && !m.items.is_empty());
// And no orphaned `endmodule` behind it.
assert!(!file.items.iter().any(|i| matches!(i.kind, ItemKind::Error(_))));
}
#[test]
fn garbage_between_two_modules_leaves_both_intact() {
for garbage in ["@#!", "foo bar baz", "???", "wire", "end", "* ) ]"] {