224 lines
8.6 KiB
Rust
224 lines
8.6 KiB
Rust
//! Error recovery, reached only in tolerant mode.
|
|
//!
|
|
//! The strategy is deliberately one paragraph long: record the error,
|
|
//! skip to a sync token, wrap the skipped text in an error leaf, continue
|
|
//! with the next item or statement. Neither `depth` nor `links` is touched
|
|
//! here — the gated frames released their own levels on the way out, so
|
|
//! recovery resumes at exactly the budget the loop it happened in was
|
|
//! running at. See `docs/features/error-recovery/README.md`.
|
|
|
|
use super::*;
|
|
|
|
/// Keywords that close a construct an enclosing parse loop is waiting for.
|
|
/// Recovery stops *before* them without consuming, so the loop that opened the
|
|
/// construct still gets to close it — that is what keeps an error inside a
|
|
/// generate block from eating the `endgenerate`.
|
|
const SYNC_CLOSERS: &[&str] = &[
|
|
"end",
|
|
"endmodule",
|
|
"endinterface",
|
|
"endprogram",
|
|
"endpackage",
|
|
"endgenerate",
|
|
"endfunction",
|
|
"endtask",
|
|
"endcase",
|
|
"endclass",
|
|
"endclocking",
|
|
"join",
|
|
"join_any",
|
|
"join_none",
|
|
// The vendor/formal closers (`vendor-formal-grammar`, 2026-09-02). Each
|
|
// one closes a block the parser keeps as an opaque leaf, so recovery that
|
|
// runs past a broken item inside a module must stop before them for the
|
|
// same reason it stops before `endgenerate`.
|
|
"endspecify",
|
|
"endprimitive",
|
|
"endtable",
|
|
"endchecker",
|
|
"endconfig",
|
|
];
|
|
|
|
/// Keywords that can only *begin* a construct at file scope. Recovery stops
|
|
/// before them too, so garbage written in front of a module cannot swallow it.
|
|
/// `class` is deliberately absent: unlike a module or a package it nests
|
|
/// (inside a package, and inside another class), so stopping recovery before
|
|
/// one would end the enclosing body at the wrong place.
|
|
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "interface", "program", "package"];
|
|
|
|
/// A `SourceFile` that is one error item covering the whole text — what a
|
|
/// caller gets when the text cannot even be tokenized.
|
|
pub(crate) fn error_file(source: &str) -> SourceFile {
|
|
let span = TextRange::new(0, source.len() as u32);
|
|
let raw = RawText { text: source.to_string(), col: 1, span };
|
|
let item = Item { meta: Meta::default(), kind: ItemKind::Error(raw), span };
|
|
SourceFile {
|
|
items: vec![item],
|
|
dangling: Vec::new(),
|
|
span,
|
|
constraint_fallbacks: 0,
|
|
covergroups: 0,
|
|
covergroup_fallbacks: 0,
|
|
prop_seq_decls: 0,
|
|
prop_seq_fallbacks: 0,
|
|
assertions: 0,
|
|
assertion_fallbacks: 0,
|
|
fragment: None,
|
|
}
|
|
}
|
|
|
|
/// True when `t` closes, or opens, a construct an enclosing parse loop is
|
|
/// responsible for. [`Parser::at_sync_stop`] asks it about the cursor; the
|
|
/// lookaheads that walk raw tokens ahead of the cursor ask it about those.
|
|
pub(super) fn is_sync_stop(t: &Token) -> bool {
|
|
t.kind == TokenKind::Keyword
|
|
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
|
}
|
|
|
|
impl<'a> Parser<'a> {
|
|
/// True when the cursor sits on a token recovery must not consume: it
|
|
/// closes, or opens, a construct an enclosing loop is responsible for.
|
|
pub(super) fn at_sync_stop(&self) -> bool {
|
|
is_sync_stop(self.cur())
|
|
}
|
|
|
|
/// True on any of the `join` keywords that close a `fork`.
|
|
pub(super) fn at_join_kw(&self) -> bool {
|
|
let t = self.cur();
|
|
t.is_kw("join") || t.is_kw("join_any") || t.is_kw("join_none")
|
|
}
|
|
|
|
/// Loop condition for a body that ends at `end_kw`. In tolerant mode any
|
|
/// sync stop ends it too, so an unclosed block stops where the next
|
|
/// construct begins instead of eating the rest of the file.
|
|
pub(super) fn at_body_end(&self, end_kw: &str) -> bool {
|
|
self.at_eof() || self.cur().is_kw(end_kw) || (self.tolerant && self.at_sync_stop())
|
|
}
|
|
|
|
/// Consume a construct's closing keyword. In tolerant mode a missing one
|
|
/// is a diagnostic and the construct is treated as closed where the parser
|
|
/// stopped: mid-edit code has unclosed blocks all the time, and the items
|
|
/// already parsed inside are worth more than the whole file being one
|
|
/// error node.
|
|
pub(super) fn expect_closer(&mut self, kw: &str) -> PResult<()> {
|
|
if self.cur().is_kw(kw) {
|
|
self.skip();
|
|
return Ok(());
|
|
}
|
|
if self.tolerant {
|
|
self.record(format!("expected `{kw}`"));
|
|
return Ok(());
|
|
}
|
|
self.error(format!("expected `{kw}`"))
|
|
}
|
|
|
|
/// Record a diagnostic at the cursor without failing.
|
|
pub(super) fn record(&mut self, message: impl Into<String>) {
|
|
let e = self.make_error(message);
|
|
self.push_diag(e);
|
|
}
|
|
|
|
/// File `err` as a diagnostic. Called while the cursor still sits on the
|
|
/// token the error was raised at, which is where its span comes from.
|
|
pub(super) fn push_diag(&mut self, err: ParseError) {
|
|
let span = self.cur().span;
|
|
self.diagnostics.push(ParseDiagnostic {
|
|
message: err.message,
|
|
line: err.line,
|
|
col: err.col,
|
|
span,
|
|
});
|
|
}
|
|
|
|
/// Skip tokens up to the next sync point: a `;` (consumed — it terminated
|
|
/// the broken construct), a sync-stop keyword (left in place for the
|
|
/// construct it belongs to), or end of file.
|
|
///
|
|
/// Brackets opened while skipping are skipped as a unit, so the `;`s of a
|
|
/// broken `for (i = 0; ...)` header do not end the skip early. A closing
|
|
/// bracket with nothing open is skipped like any other token: recovery
|
|
/// only ever runs in an item or statement list, and no such list sits
|
|
/// inside brackets, so a stray `)` is garbage rather than someone else's
|
|
/// terminator — treating it as one made every leftover `)` of a broken
|
|
/// expression its own error node.
|
|
fn skip_to_sync(&mut self) {
|
|
let mut open = 0u32;
|
|
while !self.at_eof() {
|
|
let t = self.cur();
|
|
if open == 0 {
|
|
if self.at_sync_stop() {
|
|
return;
|
|
}
|
|
if t.is_sym(";") {
|
|
self.skip();
|
|
return;
|
|
}
|
|
}
|
|
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
|
open += 1;
|
|
} else if open > 0 && (t.is_sym(")") || t.is_sym("]") || t.is_sym("}")) {
|
|
open -= 1;
|
|
}
|
|
self.skip();
|
|
}
|
|
}
|
|
|
|
/// Record `err` and skip to a sync point, handing back the skipped source
|
|
/// as a verbatim leaf spanning from `start` (the byte offset of the token
|
|
/// at `start_pos`, where the failed construct began).
|
|
pub(super) fn recover(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText {
|
|
self.push_diag(err);
|
|
if self.pos == start_pos {
|
|
// The failed construct consumed nothing, so skipping might not
|
|
// either; take one token to guarantee the enclosing loop advances.
|
|
self.skip();
|
|
}
|
|
self.skip_to_sync();
|
|
// Comments inside the skipped range are part of the raw text below.
|
|
// Dropping the trivia copies keeps them from reattaching themselves to
|
|
// whatever node comes next.
|
|
let _ = self.take_dangling();
|
|
let span = self.span_from(start);
|
|
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
|
|
RawText { text: self.slice(span), col, span }
|
|
}
|
|
|
|
/// The source text `span` covers.
|
|
pub(super) fn slice(&self, span: TextRange) -> String {
|
|
self.source.get(span.as_range()).unwrap_or_default().to_string()
|
|
}
|
|
|
|
/// Parse one item; in tolerant mode turn a failure into an error leaf.
|
|
pub(super) fn item_or_recover(&mut self) -> PResult<Item> {
|
|
let start_pos = self.pos;
|
|
let start = self.here();
|
|
match self.parse_item() {
|
|
Err(e) if self.tolerant => {
|
|
let raw = self.recover(start_pos, start, e);
|
|
let span = raw.span;
|
|
Ok(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span })
|
|
}
|
|
other => other,
|
|
}
|
|
}
|
|
|
|
/// Parse one statement; in tolerant mode turn a failure into an error leaf.
|
|
pub(super) fn stmt_or_recover(&mut self) -> PResult<Stmt> {
|
|
let start_pos = self.pos;
|
|
let start = self.here();
|
|
match self.parse_stmt() {
|
|
Err(e) if self.tolerant => {
|
|
let raw = self.recover(start_pos, start, e);
|
|
let span = raw.span;
|
|
Ok(Stmt {
|
|
meta: Meta::default(),
|
|
kind: StmtKind::Error(raw),
|
|
before_semi: Vec::new(),
|
|
span,
|
|
})
|
|
}
|
|
other => other,
|
|
}
|
|
}
|
|
}
|