class-semantics: classes are first-class in vlog_semantic -- class
scopes and symbols, member/method/prototype binding, this.x
(nearest-class-only), super.x, cls::x with lexical unit heads,
out-of-body cls::method bound into the class's scope with the extern
prototype as the definition (rule 10), and the honest
InheritedCandidate{base, paths} shape: a member miss in an extending
class records what the unknown base might supply (import paths
included) and is never chased, not even in-file -- the future
inheritance round's worklist, measured at 1303 candidates. Unit-name
misses stay ExternalCandidate (QA-found, lead-ruled: bases supply
members, not package names; +170 recovered navigations, pinned).
Workspace index gains classes as units (246) and their members
(11399). scan.rs migrated to parser name-spans: 26 call sites down
to the 2 documented consumers. 114044 spans, 0 unplaced, 0 panics;
UVM code now has hover/definition/references/outline.
lexer-cleanup: the three filed gaps -- @(* ) lexes via a
starts_attribute backoff (an attribute cannot begin with `)`; real
attributes pinned, no misfire on legal expressions), a leading BOM
is accepted as a named losslessness exception (mid-file BOM errors
clearly; 20k-case position fuzz clean), and non-ASCII lex errors now
decode the full character AND surface through vfmt check's error
slot (exit 2, matching format, text-rule findings still reported --
the silent-pass hole closed). The macro space-before-paren item is
parked with a QA-hardened analysis: the reading depends on a
definition vfmt cannot see, any fixed answer is provably wrong for
one population, and today's behavior fails safe.
827 workspace tests. Dev: 2 Fable agents; QA: 2 Opus agents; reviews
in docs/features/{class-semantics,lexer-cleanup}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
608 lines
25 KiB
Rust
608 lines
25 KiB
Rust
//! Error-tolerant parsing: `parse_source_tolerant` never fails, agrees with
|
|
//! the strict parser on every file that parses, and keeps the rest of a broken
|
|
//! file addressable. See `docs/features/error-recovery/README.md`.
|
|
//!
|
|
//! The four guarantees this file pins:
|
|
//!
|
|
//! 1. on a valid file the tolerant tree is *the same tree* and the diagnostics
|
|
//! are empty (`tolerant_parse_equals_strict_parse_on_valid_sources`);
|
|
//! 2. every diagnostic points inside the file, and every error node's text is
|
|
//! its own source slice (`diagnostics_and_error_nodes_stay_inside_the_file`;
|
|
//! the span *nesting* half lives in `spans.rs`, which reuses its exhaustive
|
|
//! walker on recovered trees);
|
|
//! 3. recovery does not reset the depth/chain budgets — a file full of
|
|
//! recovered-from deep expressions cannot accumulate
|
|
//! (`recovery_does_not_leak_the_nesting_budget`);
|
|
//! 4. tolerant parsing never panics on arbitrary input, smoke-tested over
|
|
//! every byte prefix of every fixture (`truncating_a_file_anywhere_...`).
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use vlog_parser::ast::*;
|
|
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Sources
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn workspace_file(rel: &str) -> PathBuf {
|
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(rel)
|
|
}
|
|
|
|
/// Every `.sv`/`.v` fixture the formatter tests against.
|
|
fn fixtures() -> Vec<(String, String)> {
|
|
let dir = workspace_file("vlog_formatter/tests/fixtures");
|
|
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
|
let mut out = Vec::new();
|
|
for entry in entries {
|
|
let path = entry.expect("dir entry").path();
|
|
if !matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("v")) {
|
|
continue;
|
|
}
|
|
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
|
|
out.push((path.display().to_string(), text));
|
|
}
|
|
assert!(out.len() >= 4, "expected the formatter fixtures next door, found {}", out.len());
|
|
out
|
|
}
|
|
|
|
/// Every input *and* every expected output in `tests/cases/*.cases`. The file
|
|
/// format is `====`-separated cases, `#` header lines, input, `----`, expected
|
|
/// (`docs/features/case-tables/README.md`); both halves are Verilog, so both
|
|
/// are useful sources here.
|
|
fn case_table_sources() -> Vec<(String, String)> {
|
|
let dir = workspace_file("vlog_formatter/tests/cases");
|
|
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
|
let mut out = Vec::new();
|
|
for entry in entries {
|
|
let path = entry.expect("dir entry").path();
|
|
if path.extension().and_then(|e| e.to_str()) != Some("cases") {
|
|
continue;
|
|
}
|
|
let name = path.display().to_string();
|
|
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
|
|
let mut block: Vec<&str> = Vec::new();
|
|
for line in text.lines().chain(std::iter::once("====")) {
|
|
if line.trim_end() != "====" {
|
|
block.push(line);
|
|
continue;
|
|
}
|
|
let body: Vec<&str> = block
|
|
.iter()
|
|
.skip_while(|l| l.starts_with('#') || l.trim().is_empty())
|
|
.copied()
|
|
.collect();
|
|
if let Some(sep) = body.iter().position(|l| l.trim_end() == "----") {
|
|
out.push((name.clone(), join(&body[..sep])));
|
|
out.push((name.clone(), join(&body[sep + 1..])));
|
|
}
|
|
block.clear();
|
|
}
|
|
}
|
|
assert!(out.len() > 100, "expected the formatter case tables, found {}", out.len());
|
|
out
|
|
}
|
|
|
|
fn join(lines: &[&str]) -> String {
|
|
let mut s = lines.join("\n");
|
|
if !s.is_empty() {
|
|
s.push('\n');
|
|
}
|
|
s
|
|
}
|
|
|
|
/// Mid-edit shapes, named. Each is a snapshot of a buffer someone is typing in.
|
|
const BROKEN: &[(&str, &str)] = &[
|
|
("missing semicolon", "module m;\n wire a\n wire b;\nendmodule\n"),
|
|
("unclosed begin", "module m;\n initial begin\n x = 1;\nendmodule\n"),
|
|
("unclosed module", "module m;\n wire a;\n"),
|
|
("half-typed declaration", "module m;\n wire [7:\nendmodule\n"),
|
|
("half-typed instantiation", "module m;\n sub u0 (.a(\nendmodule\n"),
|
|
("garbage between modules", "module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n"),
|
|
("error in generate", "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n"),
|
|
("all garbage", "!!! ???\n"),
|
|
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
|
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
|
("empty file", ""),
|
|
];
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Helpers
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn module_named<'a>(file: &'a SourceFile, name: &str) -> &'a Module {
|
|
for item in &file.items {
|
|
if let ItemKind::Module(m) = &item.kind {
|
|
if m.name == name {
|
|
return m;
|
|
}
|
|
}
|
|
}
|
|
panic!("no module {name:?} in {:?}", file.items.iter().map(kind_name).collect::<Vec<_>>());
|
|
}
|
|
|
|
fn kind_name(item: &Item) -> String {
|
|
match &item.kind {
|
|
ItemKind::Module(m) => format!("module {}", m.name),
|
|
ItemKind::Error(r) => format!("error {:?}", r.text),
|
|
other => format!("{:?}", std::mem::discriminant(other)),
|
|
}
|
|
}
|
|
|
|
/// Every error node in the tree, outermost first, as (span, text) pairs.
|
|
fn error_nodes(file: &SourceFile) -> Vec<(vlog_parser::TextRange, String)> {
|
|
let mut out = Vec::new();
|
|
for item in &file.items {
|
|
walk_item(item, &mut out);
|
|
}
|
|
out
|
|
}
|
|
|
|
fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
|
match &item.kind {
|
|
ItemKind::Error(r) => out.push((r.span, r.text.clone())),
|
|
ItemKind::Module(m) => m.items.iter().for_each(|i| walk_item(i, out)),
|
|
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
|
items.iter().for_each(|i| walk_item(i, out))
|
|
}
|
|
ItemKind::GenIf(g) => walk_gen_if(g, out),
|
|
ItemKind::GenFor(g) => g.body.items.iter().for_each(|i| walk_item(i, out)),
|
|
ItemKind::GenCase(g) => {
|
|
g.items.iter().flat_map(|i| i.body.items.iter()).for_each(|i| walk_item(i, out))
|
|
}
|
|
ItemKind::Initial(s) | ItemKind::Final(s) | ItemKind::Always { stmt: s, .. } => {
|
|
walk_stmt(s, out)
|
|
}
|
|
ItemKind::Function(f) => f.stmts.iter().for_each(|s| walk_stmt(s, out)),
|
|
ItemKind::Task(t) => t.stmts.iter().for_each(|s| walk_stmt(s, out)),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn walk_gen_if(g: &GenIf, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
|
g.then.items.iter().for_each(|i| walk_item(i, out));
|
|
match g.els.as_deref() {
|
|
Some(GenElse::If(_, inner)) => walk_gen_if(inner, out),
|
|
Some(GenElse::Block(b)) => b.items.iter().for_each(|i| walk_item(i, out)),
|
|
None => {}
|
|
}
|
|
}
|
|
|
|
fn walk_stmt(stmt: &Stmt, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
|
match &stmt.kind {
|
|
StmtKind::Error(r) => out.push((r.span, r.text.clone())),
|
|
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
|
stmts.iter().for_each(|s| walk_stmt(s, out))
|
|
}
|
|
StmtKind::If { then, els, .. } => {
|
|
walk_stmt(then, out);
|
|
els.iter().for_each(|s| walk_stmt(s, out));
|
|
}
|
|
StmtKind::Case { items, .. } => items.iter().for_each(|i| walk_stmt(&i.stmt, out)),
|
|
StmtKind::For { body, .. }
|
|
| StmtKind::While { body, .. }
|
|
| StmtKind::DoWhile { body, .. }
|
|
| StmtKind::Repeat { body, .. }
|
|
| StmtKind::Forever { body }
|
|
| StmtKind::Foreach { body, .. } => walk_stmt(body, out),
|
|
StmtKind::Timing { stmt, .. } | StmtKind::Wait { stmt, .. } => {
|
|
stmt.iter().for_each(|s| walk_stmt(s, out))
|
|
}
|
|
StmtKind::Assert { then, els, .. } => {
|
|
then.iter().chain(els.iter()).for_each(|s| walk_stmt(s, out))
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn assert_diagnostics_fit(src: &str, diags: &[ParseDiagnostic]) {
|
|
for d in diags {
|
|
assert!(
|
|
d.span.end as usize <= src.len(),
|
|
"diagnostic {d} span {:?} runs past the file ({} bytes)",
|
|
d.span,
|
|
src.len()
|
|
);
|
|
assert!(d.span.start <= d.span.end, "inverted span in {d}");
|
|
assert!(d.line >= 1 && d.col >= 1, "diagnostic without a position: {d}");
|
|
assert!(src.is_char_boundary(d.span.start as usize), "span start splits a character: {d}");
|
|
assert!(src.is_char_boundary(d.span.end as usize), "span end splits a character: {d}");
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Guarantee 1: a valid file parses to the very same tree
|
|
// ----------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn tolerant_parse_equals_strict_parse_on_valid_sources() {
|
|
let mut sources = fixtures();
|
|
sources.extend(case_table_sources());
|
|
let mut valid = 0;
|
|
let mut invalid = 0;
|
|
for (name, src) in &sources {
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
match parse_source(src) {
|
|
Ok(strict) => {
|
|
assert!(diags.is_empty(), "{name}: valid source got diagnostics: {diags:?}");
|
|
assert_eq!(
|
|
format!("{strict:?}"),
|
|
format!("{file:?}"),
|
|
"{name}: tolerant tree differs from the strict one"
|
|
);
|
|
valid += 1;
|
|
}
|
|
Err(_) => {
|
|
// The `.cases` tables carry a few `#SKIP` cases of syntax the
|
|
// parser does not support yet; those must report, not agree.
|
|
assert!(
|
|
!diags.is_empty(),
|
|
"{name}: strict parse failed but tolerant found nothing"
|
|
);
|
|
assert_diagnostics_fit(src, &diags);
|
|
invalid += 1;
|
|
}
|
|
}
|
|
}
|
|
assert!(valid > 200, "test would be vacuous: only {valid} valid sources");
|
|
println!("{valid} valid sources agreed with the strict parser, {invalid} reported errors");
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Guarantee 2: diagnostics and error nodes stay inside the file
|
|
// ----------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn diagnostics_and_error_nodes_stay_inside_the_file() {
|
|
for (name, src) in BROKEN {
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(
|
|
file.span.as_range(),
|
|
0..src.len(),
|
|
"{name}: the file node must span the whole text"
|
|
);
|
|
if src.is_empty() {
|
|
assert!(diags.is_empty(), "{name}: an empty file is not an error");
|
|
continue;
|
|
}
|
|
assert!(!diags.is_empty(), "{name}: expected at least one diagnostic");
|
|
assert_diagnostics_fit(src, &diags);
|
|
for (span, text) in error_nodes(&file) {
|
|
assert!(
|
|
span.end as usize <= src.len(),
|
|
"{name}: error node {span:?} runs past the end"
|
|
);
|
|
assert_eq!(
|
|
text,
|
|
&src[span.as_range()],
|
|
"{name}: an error node's text must be its own source slice"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_diagnostics_span_is_the_token_its_line_col_names() {
|
|
// The span and the line:col are two views of the same token, so an editor
|
|
// that highlights the span and a terminal that prints the position agree.
|
|
for (name, src) in BROKEN {
|
|
let (_, diags) = parse_source_tolerant(src);
|
|
let index = vlog_parser::LineIndex::new(src);
|
|
for d in &diags {
|
|
let Some(offset) = index.offset(d.line, d.col) else {
|
|
panic!("{name}: diagnostic position out of range: {d}");
|
|
};
|
|
assert_eq!(offset, d.span.start, "{name}: {d} span {:?} is elsewhere", d.span);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// The mid-edit shapes, one assertion set each
|
|
// ----------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn a_missing_semicolon_is_recovered_at_the_next_one() {
|
|
let src = "module m;\n wire a\n wire b;\n wire c;\nendmodule\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
assert!(diags[0].message.contains("expected `;`"), "{}", diags[0]);
|
|
let m = module_named(&file, "m");
|
|
// The broken declaration and the one that follows it land in the error
|
|
// node — the sync token is the next `;`, not the next line. `wire c;`
|
|
// parses normally, which is the point: the file did not become garbage.
|
|
assert_eq!(m.items.len(), 2);
|
|
assert!(matches!(&m.items[0].kind, ItemKind::Error(r) if r.text == "wire a\n wire b;"));
|
|
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
|
}
|
|
|
|
#[test]
|
|
fn an_unclosed_begin_keeps_the_statements_inside_it() {
|
|
let src = "module m;\n initial begin\n x = 1;\n y = 2;\nendmodule\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
assert!(diags[0].message.contains("expected `end`"), "{}", diags[0]);
|
|
let m = module_named(&file, "m");
|
|
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("{:?}", kind_name(&m.items[0])) };
|
|
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("not a block") };
|
|
assert_eq!(stmts.len(), 2, "both assignments survive the missing `end`");
|
|
// The `endmodule` was left for the module to close with.
|
|
assert!(error_nodes(&file).is_empty(), "nothing was skipped");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unclosed_module_keeps_its_items() {
|
|
let src = "module m;\n wire a;\n wire b;\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
assert!(diags[0].message.contains("expected `endmodule`"), "{}", diags[0]);
|
|
assert_eq!(module_named(&file, "m").items.len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn a_half_typed_declaration_is_one_error_node() {
|
|
let src = "module m;\n wire [7:\nendmodule\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
let m = module_named(&file, "m");
|
|
assert_eq!(m.items.len(), 1);
|
|
assert!(matches!(&m.items[0].kind, ItemKind::Error(r) if r.text == "wire [7:"));
|
|
// Recovery stopped *before* `endmodule`, so the module still closed.
|
|
assert!(m.end_label.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_half_typed_instantiation_is_one_error_node() {
|
|
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);
|
|
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!(error_nodes(&file).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn garbage_between_two_modules_leaves_both_intact() {
|
|
for garbage in ["@#!", "foo bar baz", "???", "wire", "end", "* ) ]"] {
|
|
let src = format!(
|
|
"module a;\n wire x;\nendmodule\n{garbage}\nmodule b;\n wire w;\n wire v;\nendmodule\n"
|
|
);
|
|
let (file, diags) = parse_source_tolerant(&src);
|
|
assert!(!diags.is_empty(), "{garbage:?}: expected a diagnostic");
|
|
assert_diagnostics_fit(&src, &diags);
|
|
assert_eq!(module_named(&file, "a").items.len(), 1, "{garbage:?}: module a lost items");
|
|
assert_eq!(module_named(&file, "b").items.len(), 2, "{garbage:?}: module b lost items");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
|
let src = "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
let m = module_named(&file, "m");
|
|
assert_eq!(m.items.len(), 2, "the generate region and the item after it both survive");
|
|
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
|
panic!("{}", kind_name(&m.items[0]))
|
|
};
|
|
let ItemKind::GenIf(g) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
|
assert!(matches!(&g.then.items[0].kind, ItemKind::Error(r) if r.text == "wire ;"));
|
|
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_of_only_garbage_is_one_error_item() {
|
|
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(file.items.len(), 1, "{src:?}");
|
|
assert_eq!(diags.len(), 1, "{src:?}");
|
|
let ItemKind::Error(r) = &file.items[0].kind else { panic!("{src:?}: not an error item") };
|
|
assert_eq!(r.text, src.trim_end(), "{src:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_lex_error_makes_the_whole_file_one_error_item() {
|
|
// The lexer is all-or-nothing, so there is no partial tree to offer.
|
|
for src in ["module m;\n initial $display(\"abc);\nendmodule\n", "module m;\n/* nope\n"] {
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1, "{src:?}");
|
|
assert_diagnostics_fit(src, &diags);
|
|
assert_eq!(file.items.len(), 1, "{src:?}");
|
|
let ItemKind::Error(r) = &file.items[0].kind else { panic!("{src:?}: not an error item") };
|
|
assert_eq!(r.text, src, "{src:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_error_inside_a_function_or_task_body_keeps_the_rest() {
|
|
let src = "module m;\n function int f;\n q = ;\n return 1;\n endfunction\n wire ok;\nendmodule\n";
|
|
let (file, diags) = parse_source_tolerant(src);
|
|
assert_eq!(diags.len(), 1);
|
|
let m = module_named(&file, "m");
|
|
assert_eq!(m.items.len(), 2);
|
|
let ItemKind::Function(f) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
|
assert_eq!(f.stmts.len(), 2, "the error statement and the `return` after it");
|
|
assert!(matches!(&f.stmts[0].kind, StmtKind::Error(_)));
|
|
assert!(matches!(&f.stmts[1].kind, StmtKind::Return(_)));
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Guarantee 3: recovery does not touch the depth / chain budgets
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Both budgets are released by the gated frames themselves on the way out of
|
|
/// an error, so recovery must neither reset them nor let them accumulate. 100
|
|
/// broken deep expressions in a row is the shape that shows either mistake:
|
|
/// leaking half the depth of each would trip `nesting too deep` well before
|
|
/// the hundredth.
|
|
#[test]
|
|
fn recovery_does_not_leak_the_nesting_budget() {
|
|
let depth = 25;
|
|
let one = format!(" assign x = {}1 + {};\n", "(".repeat(depth), ")".repeat(depth));
|
|
let src = format!("module m;\n{}endmodule\n", one.repeat(100));
|
|
let (file, diags) = parse_source_tolerant(&src);
|
|
assert_eq!(diags.len(), 100, "one diagnostic per broken expression");
|
|
for d in &diags {
|
|
assert!(!d.message.contains("too deep"), "budget accumulated across recoveries: {d}");
|
|
assert!(!d.message.contains("too long"), "chain budget accumulated: {d}");
|
|
}
|
|
// All 100 recovered as items of the module, and the module still closed.
|
|
assert_eq!(module_named(&file, "m").items.len(), 100);
|
|
assert_eq!(error_nodes(&file).len(), 100);
|
|
}
|
|
|
|
/// The complement: the limits still fire in tolerant mode, they are reported
|
|
/// as an ordinary diagnostic, and the file keeps parsing afterwards.
|
|
#[test]
|
|
fn the_depth_limit_still_fires_and_is_recovered_from() {
|
|
// Deep input costs stack; the shipped binary parses on the main thread,
|
|
// test threads get 2 MiB. Same trick the parser's own boundary tests use.
|
|
let src = format!(
|
|
"module m;\n assign x = {}1{};\n wire ok;\nendmodule\n",
|
|
"(".repeat(400),
|
|
")".repeat(400)
|
|
);
|
|
let (file, diags) = std::thread::Builder::new()
|
|
.stack_size(16 * 1024 * 1024)
|
|
.spawn(move || {
|
|
let (f, d) = parse_source_tolerant(&src);
|
|
(format!("{:?}", f.items.iter().map(kind_name).collect::<Vec<_>>()), d)
|
|
})
|
|
.expect("spawn parser thread")
|
|
.join()
|
|
.expect("parser thread crashed");
|
|
assert_eq!(diags.len(), 1, "{diags:?}");
|
|
assert!(diags[0].message.contains("nesting too deep"), "{}", diags[0]);
|
|
assert!(file.contains("module m"), "{file}");
|
|
}
|
|
|
|
/// The other direction of the same handshake: recovery must not *reset* the
|
|
/// budget either. A broken statement 55 blocks deep, followed by 20 more
|
|
/// blocks, is over the limit — unless recovery zeroed the counter, in which
|
|
/// case the inner 20 would sail through.
|
|
#[test]
|
|
fn recovery_does_not_reset_the_nesting_budget() {
|
|
let outer = 55;
|
|
let inner = 20;
|
|
let src = format!(
|
|
"module m;\ninitial\n{}x = ;\n{}y = 1;\n{}{}\nendmodule\n",
|
|
"begin\n".repeat(outer),
|
|
"begin\n".repeat(inner),
|
|
"end\n".repeat(inner),
|
|
"end\n".repeat(outer),
|
|
);
|
|
let diags = std::thread::Builder::new()
|
|
.stack_size(16 * 1024 * 1024)
|
|
.spawn(move || parse_source_tolerant(&src).1)
|
|
.expect("spawn parser thread")
|
|
.join()
|
|
.expect("parser thread crashed");
|
|
assert!(
|
|
diags.iter().any(|d| d.message.contains("nesting too deep")),
|
|
"the depth counter was reset by recovery: {diags:?}"
|
|
);
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// Guarantee 4: no input panics, no input hangs
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Mid-edit code is truncated code: every prefix of a real file is a buffer
|
|
/// someone had on screen at some point. Every byte position is tried, which
|
|
/// includes every token boundary; the assertions are the invariants that must
|
|
/// hold for *any* input, so this doubles as a fuzz smoke test.
|
|
#[test]
|
|
fn truncating_a_file_anywhere_never_panics() {
|
|
let mut checked = 0usize;
|
|
for (name, src) in fixtures() {
|
|
for cut in 0..=src.len() {
|
|
if !src.is_char_boundary(cut) {
|
|
continue;
|
|
}
|
|
let prefix = &src[..cut];
|
|
let (file, diags) = parse_source_tolerant(prefix);
|
|
assert_eq!(
|
|
file.span.as_range(),
|
|
0..prefix.len(),
|
|
"{name} cut at {cut}: file span must cover the prefix"
|
|
);
|
|
assert_diagnostics_fit(prefix, &diags);
|
|
for (span, text) in error_nodes(&file) {
|
|
assert_eq!(text, &prefix[span.as_range()], "{name} cut at {cut}");
|
|
}
|
|
checked += 1;
|
|
}
|
|
}
|
|
assert!(checked > 4000, "expected thousands of prefixes, got {checked}");
|
|
println!("{checked} byte prefixes of the fixtures parsed");
|
|
}
|
|
|
|
/// A BOM'd buffer truncated anywhere: the BOM is skipped like whitespace, so
|
|
/// every prefix must obey the same invariants a plain file's prefixes do —
|
|
/// including the prefix that is nothing but the BOM itself.
|
|
#[test]
|
|
fn truncating_a_bom_prefixed_file_never_panics() {
|
|
let src = "\u{feff}module m;\n wire w;\n always @(* ) y = a;\nendmodule\n";
|
|
for cut in 0..=src.len() {
|
|
if !src.is_char_boundary(cut) {
|
|
continue;
|
|
}
|
|
let prefix = &src[..cut];
|
|
let (file, diags) = parse_source_tolerant(prefix);
|
|
assert_eq!(file.span.as_range(), 0..prefix.len(), "cut at {cut}");
|
|
assert_diagnostics_fit(prefix, &diags);
|
|
for (span, text) in error_nodes(&file) {
|
|
assert_eq!(text, &prefix[span.as_range()], "cut at {cut}");
|
|
}
|
|
}
|
|
// A BOM anywhere else stays a lex error, which tolerant parsing turns
|
|
// into one diagnostic and one file-wide error item like any other.
|
|
let (file, diags) = parse_source_tolerant("module m;\u{feff}\nendmodule\n");
|
|
assert_eq!(diags.len(), 1);
|
|
assert!(diags[0].message.contains("byte order mark"), "unexpected: {}", diags[0].message);
|
|
assert!(matches!(file.items[0].kind, ItemKind::Error(_)));
|
|
}
|
|
|
|
/// Token-boundary truncation of the small case-table sources: same idea,
|
|
/// different (much wider) set of constructs.
|
|
#[test]
|
|
fn truncating_a_case_table_source_never_panics() {
|
|
let mut checked = 0usize;
|
|
for (name, src) in case_table_sources() {
|
|
let Ok(tokens) = vlog_parser::tokenize(&src) else { continue };
|
|
let cuts = tokens.iter().map(|t| t.span.end as usize).chain(std::iter::once(src.len()));
|
|
for cut in cuts {
|
|
if !src.is_char_boundary(cut) {
|
|
continue;
|
|
}
|
|
let (file, diags) = parse_source_tolerant(&src[..cut]);
|
|
assert_eq!(file.span.as_range(), 0..cut, "{name} cut at {cut}");
|
|
assert_diagnostics_fit(&src[..cut], &diags);
|
|
checked += 1;
|
|
}
|
|
}
|
|
assert!(checked > 1000, "expected thousands of prefixes, got {checked}");
|
|
println!("{checked} token-boundary prefixes of the case tables parsed");
|
|
}
|
|
|
|
/// Deleting one byte anywhere is the other half of "mid-edit": a stray
|
|
/// backspace. Same invariants, and in particular no hang.
|
|
#[test]
|
|
fn deleting_any_single_character_never_panics() {
|
|
for (name, src) in fixtures() {
|
|
for cut in 0..src.len() {
|
|
if !src.is_char_boundary(cut) {
|
|
continue;
|
|
}
|
|
let mut broken = src.clone();
|
|
let _ = broken.remove(cut);
|
|
let (file, diags) = parse_source_tolerant(&broken);
|
|
assert_eq!(file.span.as_range(), 0..broken.len(), "{name} minus byte {cut}");
|
|
assert_diagnostics_fit(&broken, &diags);
|
|
}
|
|
}
|
|
}
|