Add error-recovery and format-fences (jointly: entangled in format.rs)
error-recovery (vlog_parser): parse_source_tolerant never fails —
errors become positioned ParseDiagnostics and ItemKind::Error /
StmtKind::Error leaves (raw text + span, nesting invariant intact),
with recovery at documented sync tokens, bracket-balanced skipping,
and stray-closer collapse. Strict parse_source is byte-identical in
behavior (shared grammar, tolerant flag). Guarantees tested:
tolerant==strict on 500 valid sources; depth/links budgets neither
reset nor leak across recovery (mutation-tested); no panic across
27k+ truncation cuts, every single-char fixture deletion, 1MB of
semicolons (500k recoveries, 344ms). The future LSP parses mid-edit
code; the formatter still refuses on the first error.
format-fences (vlog_formatter): // verilog_format: off|on and
// vfmt: off|on emit fenced item ranges as exact source bytes via
spans (Doc::Verbatim), Verible-style item-level regions per scope,
unmatched off to end of scope, byte-exact including indentation and
idempotent at every join (24 adversarial probes). ~2000 corpus fence
injections: zero region byte changes, zero new verification
failures. verify.rs untouched; with no fences output is
byte-identical (corpus TSV md5 unchanged).
Also surfaced and queued in TODO: comment-in-list refusals
(112/1868 injection trials) and the double-blank leading-comment
nit — the next comments round.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{error-recovery,format-fences}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
901a78ccb2
commit
02f68655b5
16 files changed
+3069
-70
No files matched your search
@@ -12,6 +12,10 @@
|
||||
//! number of tokens per level brackets itself with [`Parser::enter`] /
|
||||
//! [`Parser::leave`], turning nesting past [`MAX_NESTING_DEPTH`] into an
|
||||
//! ordinary [`ParseError`].
|
||||
//!
|
||||
//! Error tolerance: [`parse`] stops at the first error, which is what the
|
||||
//! formatter needs. [`parse_tolerant`] shares this same grammar code but
|
||||
//! recovers instead — see `docs/features/error-recovery/README.md`.
|
||||
|
||||
use crate::ast::*;
|
||||
use crate::span::TextRange;
|
||||
@@ -32,6 +36,26 @@ impl std::fmt::Display for ParseError {
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
/// An error [`parse_tolerant`] recovered from, in the same words a
|
||||
/// [`ParseError`] would have used plus the byte range it points at.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParseDiagnostic {
|
||||
/// What went wrong, e.g. ``expected `;` (found "endmodule")``.
|
||||
pub message: String,
|
||||
/// 1-based line of the token the parser gave up on.
|
||||
pub line: u32,
|
||||
/// 1-based column (in bytes) of that token.
|
||||
pub col: u32,
|
||||
/// Byte extent of that token; empty at end of file.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ParseDiagnostic {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}:{}: {}", self.line, self.col, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
type PResult<T> = Result<T, ParseError>;
|
||||
|
||||
const TYPE_KEYWORDS: &[&str] = &[
|
||||
@@ -62,6 +86,27 @@ const GATE_KEYWORDS: &[&str] = &[
|
||||
"rtran", "tranif0", "tranif1", "rtranif0", "rtranif1",
|
||||
];
|
||||
|
||||
/// 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",
|
||||
"endpackage",
|
||||
"endgenerate",
|
||||
"endfunction",
|
||||
"endtask",
|
||||
"endcase",
|
||||
"join",
|
||||
"join_any",
|
||||
"join_none",
|
||||
];
|
||||
|
||||
/// 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.
|
||||
const SYNC_OPENERS: &[&str] = &["module", "macromodule", "package"];
|
||||
|
||||
const ASSIGN_OPS: &[&str] =
|
||||
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
|
||||
|
||||
@@ -94,7 +139,7 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
|
||||
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
|
||||
pub const MAX_CHAIN_LENGTH: u32 = 256;
|
||||
|
||||
pub struct Parser {
|
||||
pub struct Parser<'a> {
|
||||
tokens: Vec<Token>,
|
||||
pos: usize,
|
||||
pending_leading: Vec<Comment>,
|
||||
@@ -103,21 +148,69 @@ pub struct Parser {
|
||||
depth: u32,
|
||||
/// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`].
|
||||
links: u32,
|
||||
/// Recover from errors instead of returning them; see [`parse_tolerant`].
|
||||
tolerant: bool,
|
||||
/// The text the tokens were lexed from. Read only by recovery, to copy a
|
||||
/// skipped range into an error node, so strict mode passes `""`.
|
||||
source: &'a str,
|
||||
/// Errors recovered from, in source order. Always empty in strict mode.
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
/// Parse a token stream, stopping at the first error.
|
||||
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
|
||||
let mut p = Parser {
|
||||
tokens,
|
||||
pos: 0,
|
||||
pending_leading: Vec::new(),
|
||||
pending_trailing: Vec::new(),
|
||||
depth: 0,
|
||||
links: 0,
|
||||
};
|
||||
p.parse_source_file()
|
||||
Parser::new(tokens, "", false).parse_source_file()
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
/// Parse a token stream that may be broken, recording errors instead of
|
||||
/// failing.
|
||||
///
|
||||
/// The unparsable parts of the file become [`ItemKind::Error`] /
|
||||
/// [`StmtKind::Error`] leaves holding the source text they cover, so the tree
|
||||
/// still spans the whole file. `source` must be the exact text `tokens` were
|
||||
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
|
||||
/// the diagnostics are empty.
|
||||
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
|
||||
let mut p = Parser::new(tokens, source, true);
|
||||
match p.parse_source_file() {
|
||||
Ok(file) => (file, p.diagnostics),
|
||||
// Unreachable in practice: every error path inside a file body is
|
||||
// recovered. Rather than assert that, fall back to one error item
|
||||
// covering the file, which is what a lex-level failure gets too.
|
||||
Err(e) => {
|
||||
let span = TextRange::new(0, source.len() as u32);
|
||||
let diag = ParseDiagnostic { message: e.message, line: e.line, col: e.col, span };
|
||||
let mut diagnostics = p.diagnostics;
|
||||
diagnostics.push(diag);
|
||||
(error_file(source), diagnostics)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
fn new(tokens: Vec<Token>, source: &'a str, tolerant: bool) -> Self {
|
||||
Parser {
|
||||
tokens,
|
||||
pos: 0,
|
||||
pending_leading: Vec::new(),
|
||||
pending_trailing: Vec::new(),
|
||||
depth: 0,
|
||||
links: 0,
|
||||
tolerant,
|
||||
source,
|
||||
diagnostics: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cur(&self) -> &Token {
|
||||
&self.tokens[self.pos]
|
||||
}
|
||||
@@ -174,6 +267,160 @@ impl Parser {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Error recovery
|
||||
//
|
||||
// Only ever reached when `tolerant` is set. 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/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.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
fn at_sync_stop(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
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.
|
||||
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.
|
||||
fn expect_closer(&mut self, kw: &str) -> PResult<()> {
|
||||
if self.cur().is_kw(kw) {
|
||||
self.bump();
|
||||
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.
|
||||
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.
|
||||
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.bump();
|
||||
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.bump();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
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.bump();
|
||||
}
|
||||
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. Empty in strict mode, which never
|
||||
/// recovers and is therefore never given the source.
|
||||
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.
|
||||
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.
|
||||
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), span })
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Spans
|
||||
//
|
||||
@@ -211,13 +458,18 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn error<T>(&self, message: impl Into<String>) -> PResult<T> {
|
||||
Err(self.make_error(message))
|
||||
}
|
||||
|
||||
/// The error the parser would report at the cursor right now.
|
||||
fn make_error(&self, message: impl Into<String>) -> ParseError {
|
||||
let t = self.cur();
|
||||
let shown = if t.kind == TokenKind::Eof { "<eof>" } else { t.text.as_str() };
|
||||
Err(ParseError {
|
||||
ParseError {
|
||||
line: t.line,
|
||||
col: t.col,
|
||||
message: format!("{} (found {:?})", message.into(), shown),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_sym(&mut self, sym: &str) -> PResult<Token> {
|
||||
@@ -442,7 +694,7 @@ impl Parser {
|
||||
fn parse_source_file(&mut self) -> PResult<SourceFile> {
|
||||
let mut items = Vec::new();
|
||||
while !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
// The cursor is on the EOF token, whose empty span sits at the end of
|
||||
@@ -543,11 +795,11 @@ impl Parser {
|
||||
"generate" => {
|
||||
self.bump();
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endgenerate") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endgenerate") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endgenerate")?;
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
@@ -623,11 +875,11 @@ impl Parser {
|
||||
let name = self.expect_ident()?;
|
||||
self.expect_sym(";")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endpackage") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endpackage") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endpackage")?;
|
||||
self.expect_closer("endpackage")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(ItemKind::Package { kw, name, items, dangling, end_label })
|
||||
}
|
||||
@@ -685,11 +937,11 @@ impl Parser {
|
||||
let (ports, port_dangling) = self.parse_port_list()?;
|
||||
self.expect_sym(";")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endmodule") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("endmodule") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endmodule")?;
|
||||
self.expect_closer("endmodule")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(Module {
|
||||
kw,
|
||||
@@ -1369,7 +1621,7 @@ impl Parser {
|
||||
let expr = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endcase") && !self.at_eof() {
|
||||
while !self.at_body_end("endcase") {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let labels = if self.eat_kw("default") {
|
||||
@@ -1387,7 +1639,7 @@ impl Parser {
|
||||
items.push(GenCaseItem { meta, labels, body, span });
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endcase")?;
|
||||
self.expect_closer("endcase")?;
|
||||
Ok(GenCase { expr, items, dangling })
|
||||
}
|
||||
|
||||
@@ -1397,11 +1649,11 @@ impl Parser {
|
||||
self.bump();
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("end") && !self.at_eof() {
|
||||
items.push(self.parse_item()?);
|
||||
while !self.at_body_end("end") {
|
||||
items.push(self.item_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
self.expect_closer("end")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(GenBlock {
|
||||
label,
|
||||
@@ -1412,7 +1664,7 @@ impl Parser {
|
||||
span: self.span_from(start),
|
||||
})
|
||||
} else {
|
||||
let item = self.parse_item()?;
|
||||
let item = self.item_or_recover()?;
|
||||
let span = item.span;
|
||||
Ok(GenBlock {
|
||||
label: None,
|
||||
@@ -1512,11 +1764,11 @@ impl Parser {
|
||||
end_kw: &str,
|
||||
) -> PResult<(Vec<Stmt>, Vec<Comment>, Option<String>)> {
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_kw(end_kw) && !self.at_eof() {
|
||||
stmts.push(self.parse_stmt()?);
|
||||
while !self.at_body_end(end_kw) {
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw(end_kw)?;
|
||||
self.expect_closer(end_kw)?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok((stmts, dangling, end_label))
|
||||
}
|
||||
@@ -1593,11 +1845,11 @@ impl Parser {
|
||||
self.bump();
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_kw("end") && !self.at_eof() {
|
||||
stmts.push(self.parse_stmt()?);
|
||||
while !self.at_body_end("end") {
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
self.expect_closer("end")?;
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::Block { label, stmts, dangling, end_label })
|
||||
}
|
||||
@@ -1606,14 +1858,18 @@ impl Parser {
|
||||
let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let mut stmts = Vec::new();
|
||||
while !self.at_eof()
|
||||
&& !(self.cur().is_kw("join")
|
||||
|| self.cur().is_kw("join_any")
|
||||
|| self.cur().is_kw("join_none"))
|
||||
&& !self.at_join_kw()
|
||||
&& !(self.tolerant && self.at_sync_stop())
|
||||
{
|
||||
stmts.push(self.parse_stmt()?);
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
let join_kw = self.bump().text;
|
||||
let join_kw = if self.tolerant && !self.at_join_kw() {
|
||||
self.record("expected `join`");
|
||||
"join".to_string()
|
||||
} else {
|
||||
self.bump().text
|
||||
};
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label })
|
||||
}
|
||||
@@ -1836,7 +2092,7 @@ impl Parser {
|
||||
self.expect_sym(")")?;
|
||||
// `case (x) inside` is not supported; plain case kinds only.
|
||||
let mut items = Vec::new();
|
||||
while !self.cur().is_kw("endcase") && !self.at_eof() {
|
||||
while !self.at_body_end("endcase") {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let labels = if self.eat_kw("default") {
|
||||
@@ -1848,7 +2104,7 @@ impl Parser {
|
||||
self.expect_sym(":")?;
|
||||
labels
|
||||
};
|
||||
let stmt = self.parse_stmt()?;
|
||||
let stmt = self.stmt_or_recover()?;
|
||||
let span = self.span_from(start);
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
@@ -1856,7 +2112,7 @@ impl Parser {
|
||||
items.push(CaseItem { meta, labels, stmt, span });
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endcase")?;
|
||||
self.expect_closer("endcase")?;
|
||||
Ok(StmtKind::Case { qualifier, kw, expr, items, dangling })
|
||||
}
|
||||
|
||||
@@ -2818,4 +3074,35 @@ mod tests {
|
||||
assert_eq!(comments.before.len(), 1, "one comment before the operator");
|
||||
assert_eq!(comments.after.len(), 1, "one comment after the operator");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Error recovery
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// White-box version of the handshake in
|
||||
/// `docs/features/recursion-limit/README.md`: recovery neither leaks nor
|
||||
/// resets the two budgets, so both counters are back at zero once a file
|
||||
/// full of recovered errors has been parsed.
|
||||
#[test]
|
||||
fn both_budgets_are_balanced_after_recovering() {
|
||||
let src = "module m;\n wire a\n assign x = ((1 +;\n initial begin\n y = ;\n end\n bad ) ) ;\nendmodule\n@#!\nmodule n;\n wire b\nendmodule\n";
|
||||
let mut p = Parser::new(tokenize(src).expect("lex error"), src, true);
|
||||
p.parse_source_file().expect("tolerant parsing never fails");
|
||||
assert!(!p.diagnostics.is_empty(), "the source is broken on purpose");
|
||||
assert_eq!(p.depth, 0, "nesting budget left open after recovery");
|
||||
assert_eq!(p.links, 0, "chain budget left open after recovery");
|
||||
}
|
||||
|
||||
/// The strict entry point keeps its contract: it fails at the *first*
|
||||
/// error, with the same message tolerant mode files as its first
|
||||
/// diagnostic.
|
||||
#[test]
|
||||
fn strict_parsing_still_stops_at_the_first_error() {
|
||||
let src = "module m;\n wire a\n wire b;\n wire c\nendmodule\n";
|
||||
let err = parse(tokenize(src).expect("lex error")).expect_err("strict must refuse");
|
||||
let (_, diags) = crate::parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "tolerant mode reports both");
|
||||
assert_eq!(err.message, diags[0].message);
|
||||
assert_eq!((err.line, err.col), (diags[0].line, diags[0].col));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user