343 lines
16 KiB
Rust
343 lines
16 KiB
Rust
//! 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::*;
|
|
|
|
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<T>(
|
|
&mut self,
|
|
parse: impl FnOnce(&mut Self) -> PResult<T>,
|
|
) -> PResult<ListElem<T>> {
|
|
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),
|
|
}
|
|
}
|
|
|
|
/// 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<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.
|
|
///
|
|
/// 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<Expr> {
|
|
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 }
|
|
}
|
|
|
|
/// True on a token that opens a bracket.
|
|
fn at_open_bracket(&self) -> bool {
|
|
let t = self.cur();
|
|
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
|
}
|
|
|
|
/// 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,
|
|
}
|
|
}
|
|
}
|