//! Error recovery *inside* a header — its bracketed lists and the parentheses //! of a statement header — reached only in tolerant mode. //! //! `recover.rs` recovers in item and statement **lists**, which means a typo //! anywhere inside a header escapes to the nearest enclosing one and takes the //! whole module, function or statement with it. This file is the second, much //! smaller answer: a list element that does not parse becomes an //! [`ListElem::Error`], a statement header's condition that does not parse //! becomes an [`ExprKind::Error`], and the construct around it keeps its name, //! the elements that were typed and its body. //! //! Two rules make the skipping predictable, and both are list-local: //! //! * the bracket counter is **seeded from the list's own open bracket** — //! already consumed by the caller — so the `;`s inside a `for (…; …; …)` //! header are invisible and no skip can run past the bracket that closes //! the list it is in. An element that gave up standing *on* a bracket //! opened one it never closed, so that bracket is taken before the skip //! starts rather than counted as a level of its own (see //! [`Parser::recover_element`]); //! * a **line change** stops a skip. It is the one line-based rule in the //! parser, and it is what makes `module m (input logic a, inp⏎ output b);` //! cost one port instead of the rest of the list. //! //! See `docs/features/header-recovery/README.md`. use super::directive::{closes_conditional, continues_conditional, opens_conditional}; use super::recover::is_sync_stop; use super::*; impl<'a> Parser<'a> { /// True where a bracketed header list may end: on its own closing /// bracket, on a `;` (the header was abandoned), at end of file, or on a /// keyword an enclosing construct owns. /// /// Read only in tolerant mode, and only with the list's brackets balanced, /// so a `)` here is the list's own. pub(super) fn at_list_end(&self) -> bool { let t = self.cur(); self.at_eof() || t.is_sym(")") || t.is_sym(";") || self.at_sync_stop() } /// 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, /// 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(")")); } 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 /// failure into an error element holding the text skipped to the next /// element boundary. Strict mode propagates the error unchanged. pub(super) fn element_or_recover( &mut self, parse: impl FnOnce(&mut Self) -> PResult, ) -> PResult> { let start_pos = self.pos; let start = self.here(); match parse(self) { Ok(value) => Ok(ListElem::Ok(value)), Err(e) if self.tolerant && !self.at_conditional_directive() => { Ok(ListElem::Error(self.recover_element(start_pos, start, e))) } Err(e) => Err(e), } } /// One entry of a port or parameter connection list, the unfinished ones /// included (`docs/features/port-entry-grace/README.md`). /// /// A `.` with no name after it yet — `.a(x), .` ⏎ `.b(y)` — is the entry /// someone is typing. In tolerant mode it becomes an error element of its /// own, holding just the `.`, with its one diagnostic on the `.`: the /// generic recovery would report the token *after* it, which belongs to /// the next entry, and its skip would swallow a `.b(y)` written on the /// same line. Strict mode, and every other entry, is /// [`Parser::element_or_recover`] over [`Parser::parse_connection`]. pub(super) fn connection_or_recover(&mut self) -> PResult> { if self.tolerant && self.at_lone_dot() { return Ok(ListElem::Error(self.take_lone_dot())); } self.element_or_recover(|p| p.parse_connection()) } /// True on a `.` that no name can follow: the next token ends the entry /// (`,` `)` `;`), ends the file or an enclosing construct, or — on a later /// line — is a keyword or the `.` of the next entry. A keyword or a `.` on /// the same line (`.input(x)`, `..z (p)`) is left to the generic recovery, /// whose skip takes the whole `.input(x)` / `..z (p)` with it: one error /// element, which is what `lucisv_mcp`'s refusal names (`qa_f1.rs`). fn at_lone_dot(&self) -> bool { if !self.cur().is_sym(".") { return false; } let next = self.nth(1); let later_line = next.line != self.cur().line; next.kind == TokenKind::Eof || next.is_sym(",") || next.is_sym(")") || next.is_sym(";") || is_sync_stop(next) || (later_line && (next.kind == TokenKind::Keyword || next.is_sym("."))) } /// Record the lone `.` at the cursor and take it as an error element. /// The comments written before it are left pending, so the next entry /// picks them up rather than the error leaf swallowing them. fn take_lone_dot(&mut self) -> RawText { let dot = self.cur(); let (span, col) = (dot.span, dot.col); self.diagnostics.push(ParseDiagnostic { message: "expected a name after `.`".to_string(), line: dot.line, col, span, }); self.skip(); RawText { text: self.slice(span), col, span } } /// [`Parser::list_ends`] for a connection list, which reads one shape on. /// /// After an entry that had to be recovered, a missing `,` normally ends /// the list — what follows belongs to the enclosing construct. In a /// connection list a `.` there is the next connection instead: the entry /// above was abandoned mid-typing (`.po(` ⏎ `.b(y)`), and the list reads /// on. No second diagnostic: the recovered entry already has one, and it /// is the news. Strict mode never recovers, so this is `list_ends` there. pub(super) fn connection_list_ends( &mut self, start: usize, comma: bool, dirs_any: bool, recovered: bool, ) -> bool { let next_entry = self.cur().is_sym("."); if self.tolerant && recovered && !comma && !dirs_any && self.pos != start && next_entry { return false; } self.list_ends(start, comma, dirs_any, recovered) } /// In tolerant mode, report a connection list's `,` that only the closing /// `)` follows — `.b(y),)`, the separator typed before the next entry. /// Strict mode fails there on the empty entry; tolerant mode used to end /// the list on the `)` without a word. The diagnostic sits on the `,`. /// Called right after the `,` was consumed, so it is the token behind the /// cursor. pub(super) fn note_trailing_comma(&mut self, comma: bool) { if !(self.tolerant && comma && self.cur().is_sym(")")) { return; } let Some(sep) = self.pos.checked_sub(1).and_then(|i| self.tokens.get(i)) else { return }; let diag = ParseDiagnostic { message: "expected a connection after `,`".to_string(), line: sep.line, col: sep.col, span: sep.span, }; self.diagnostics.push(diag); } /// True when the `(` at the cursor — the one that opens a connection's /// value — was left open mid-typing: still open at the end of its line, /// the next line starting something new (a `.` entry, a `)`, a `;`, a /// keyword, or end of file), **and** the bracket never closes the way a /// value's does. /// /// The last clause is what keeps every file the strict parser reads /// untouched: in a valid list a value's matching `)` is followed by a /// `,`, the list's `)`, or a directive, so `.po(top` ⏎ `.sig)` — a legal /// path continued on the next line — is read as written. The line clause /// keeps the pinned ambiguous shape `.D(` ⏎ `u0 (.a(x)));` greedy /// (`docs/features/header-recovery/README.md`): an identifier opening the /// next line is [`Parser::value_runs_into_next_instance`]'s question. /// Tolerant mode only; the walk ends at the first `;` or construct keyword /// outside the value, so it is bounded by the item. pub(super) fn value_left_open(&self) -> bool { let open = self.pos; let line = self.cur().line; let mut depth = 0u32; let mut i = open + 1; while let Some(t) = self.tokens.get(i) { if t.line != line || t.kind == TokenKind::Eof { break; } if is_open_bracket(t) { depth += 1; } else if is_close_bracket(t) { if depth == 0 { return false; } depth -= 1; } i += 1; } let Some(next) = self.tokens.get(i) else { return false }; let starts_new = next.kind == TokenKind::Eof || next.kind == TokenKind::Keyword || next.is_sym(".") || next.is_sym(")") || next.is_sym(";"); starts_new && !self.value_closes(open) } /// Whether the bracket at token `open` is closed by a `)` that a valid /// connection list could have written next: anything but a `;`, end of /// file, a construct keyword, a `.` or a plain identifier after it. A /// `;` or construct keyword reached first, outside any bracket the value /// opened, means it is never closed at all. fn value_closes(&self, open: usize) -> bool { let mut depth = 0u32; let mut i = open + 1; while let Some(t) = self.tokens.get(i) { if t.kind == TokenKind::Eof { return false; } if is_open_bracket(t) { depth += 1; } else if is_close_bracket(t) { if depth == 0 { return self.tokens.get(i + 1).is_some_and(|after| !ends_a_value_badly(after)); } depth -= 1; } else if depth == 0 && (t.is_sym(";") || is_sync_stop(t)) { return false; } i += 1; } false } /// True on a token that opens a bracket. fn at_open_bracket(&self) -> bool { is_open_bracket(self.cur()) } /// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` / /// `` `endif ``: a directive that opens, continues or closes a /// conditional-compilation region. /// /// 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 !self.recovered_since(mark) { self.record("expected `)`"); } return Ok(()); } self.error("expected `)`") } /// Consume `sym` after a header that already recovered from an error: its /// diagnostic is the one about this header, so a `;` or bracket missing /// behind it is taken silently rather than reported twice or — worse — /// failing the whole header and losing the body. /// /// Without a recovery, and in strict mode, this *is* /// [`Parser::expect_sym`]. pub(super) fn expect_after_recovery(&mut self, sym: &str, recovered: bool) -> PResult<()> { if recovered && self.tolerant { let _ = self.eat_sym(sym); return Ok(()); } 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 { 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. /// /// In tolerant mode a failure — or a condition the `)` does not follow — /// becomes one [`ExprKind::Error`] covering the text skipped up to the /// header's own `)`, so the statement keeps its body and the file keeps /// one diagnostic. In strict mode this is [`Parser::parse_expr`], and the /// caller's `expect_sym(")")` reports the missing bracket as before. pub(super) fn cond_or_recover(&mut self) -> PResult { if !self.tolerant { return self.parse_expr(); } let start_pos = self.pos; let start = self.here(); match self.parse_expr() { Ok(e) if self.cur().is_sym(")") => Ok(e), Ok(_) => { let err = self.make_error("expected `)`"); Ok(self.error_expr(start_pos, start, err)) } Err(e) => Ok(self.error_expr(start_pos, start, e)), } } /// Record `err` and skip the rest of a statement header's brackets, /// handing back the skipped source as one [`ExprKind::Error`] node. /// /// Called by [`Parser::cond_or_recover`] and by the `for` header, which /// recovers as a whole: its three sections are one bracket, so the error /// node stands where its condition would. pub(super) fn error_expr(&mut self, start_pos: usize, start: u32, err: ParseError) -> Expr { self.push_diag(err); if self.pos == start_pos && !self.cur().is_sym(")") { // The header consumed nothing and the skip below may not either; // take one token so the statement cannot be re-read forever. self.skip(); } self.skip_inside_brackets(true); // As in `recover`: comments inside the skipped range are bytes of the // raw text now, and the trivia copies would otherwise reattach // themselves to whatever node comes next. let _ = self.take_dangling(); let span = self.recovered_span(start_pos, start); let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1); Expr { kind: ExprKind::Error(RawText { text: self.slice(span), col, span }), span } } /// Record `err` and skip the remains of a broken list element, handing /// back the skipped source as a verbatim leaf spanning from `start`. fn recover_element(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText { self.push_diag(err); if self.pos == start_pos && !self.at_list_end() && !self.cur().is_sym(",") { // Nothing was consumed and nothing below will be: the list loop // neither ends here nor eats a separator, so take one token to // guarantee it advances. self.skip(); } else if self.at_open_bracket() { // The element gave up standing *on* a bracket, which is therefore // one it opened and never closed — the `(` of a half-typed // `.DEPTH(` (see `Parser::value_runs_into_next_instance`). That // bracket is part of the broken element, not a level the skip has // to balance: counting it would put the skip one level below the // list, where the line-change rule is not read, and the rest of // the body would be swallowed looking for a `)` that was never // written. Taken here, the skip starts inside it at the list's own // level and stops at the next line as it does everywhere else. self.skip(); } self.skip_inside_brackets(false); let _ = self.take_dangling(); let span = self.recovered_span(start_pos, start); let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1); RawText { text: self.slice(span), col, span } } /// The extent a recovery covers: from `start` through the last token it /// took, or the empty range at `start` when it took none (the sync point /// was already under the cursor). fn recovered_span(&self, start_pos: usize, start: u32) -> TextRange { if self.pos == start_pos { TextRange::empty(start) } else { self.span_from(start) } } /// Skip forward inside a bracket the caller already consumed, stopping /// *before* the token that ends the skip. /// /// The counter starts at one — the list's own open bracket — so a closing /// bracket at that level is the list's own and ends the skip, and nothing /// nested inside can be mistaken for it. At that level the skip also stops /// at a `,` (the next element's separator), at a keyword an enclosing /// construct owns, and at the first token of a new line. A `;` ends it too /// unless `through_semis` is set, which is what lets a `for` header — the /// one bracket with `;`s of its own inside it — recover as a whole. fn skip_inside_brackets(&mut self, through_semis: bool) { let mut open = 1u32; let mut line = self.prev_line(); while !self.at_eof() { if open == 1 && self.at_element_sync(line, through_semis) { return; } let t = self.cur(); let opens = t.is_sym("(") || t.is_sym("[") || t.is_sym("{"); let closes = t.is_sym(")") || t.is_sym("]") || t.is_sym("}"); line = t.line; if opens { open += 1; } else if closes { open -= 1; } self.skip(); } } /// True on a token that ends a skip at the list's own bracket level: /// `line` is the line the last token belonging to the broken element was /// written on, so a token on any other line starts something new. fn at_element_sync(&self, line: u32, through_semis: bool) -> bool { let t = self.cur(); if t.is_sym(";") { return !through_semis; } t.line != line || t.is_sym(",") || t.is_sym(")") || t.is_sym("]") || t.is_sym("}") || self.at_sync_stop() } /// The line the last consumed token was written on — the line a skip /// measures "a new line" against. At the very first token there is none, /// so the cursor's own line stands in. fn prev_line(&self) -> u32 { match self.pos.checked_sub(1) { Some(i) => self.tokens[i].line, None => self.cur().line, } } } /// True on a `(`, `[` or `{`. fn is_open_bracket(t: &Token) -> bool { t.is_sym("(") || t.is_sym("[") || t.is_sym("{") } /// True on a `)`, `]` or `}`. fn is_close_bracket(t: &Token) -> bool { t.is_sym(")") || t.is_sym("]") || t.is_sym("}") } /// True on a token no valid connection list writes right after a value's /// closing `)`: the list was never closed (`;`, end of file, a construct /// keyword), or the next connection follows with no `,` (`.`, or a plain /// identifier — a macro invocation is a directive's business and allowed). fn ends_a_value_badly(t: &Token) -> bool { t.kind == TokenKind::Eof || t.is_sym(";") || t.is_sym(".") || is_sync_stop(t) || (t.kind == TokenKind::Ident && !t.is_macro()) }