Files
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

1114 lines
49 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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::parser::PARSE_STACK_SIZE;
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"),
("module-scope begin block", "module m;\n begin\n wire a;\n end\n wire b;\nendmodule\n"),
("override runs into the next instance", "module m;\n sub #(.W(8), .D(\n u0 (.a(x));\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
}
/// The error elements of one header list, as the same (span, text) pairs an
/// error item or statement contributes: an element a tolerant parse could not
/// read is an error node like any other, and every count in this file is of
/// *all* of them.
fn walk_list<T>(list: &[ListElem<T>], out: &mut Vec<(vlog_parser::TextRange, String)>) {
for raw in list.iter().filter_map(ListElem::error) {
out.push((raw.span, raw.text.clone()));
}
}
fn walk_ports(ports: &PortList, out: &mut Vec<(vlog_parser::TextRange, String)>) {
match ports {
PortList::Ansi(ports) => walk_list(ports, out),
PortList::NonAnsi(ports) => walk_list(ports, out),
PortList::None | PortList::Empty => {}
}
}
fn walk_conns(conns: &Connections, out: &mut Vec<(vlog_parser::TextRange, String)>) {
match conns {
Connections::Named(conns) => walk_list(conns, out),
Connections::Ordered(conns) => walk_list(conns, out),
}
}
/// The leaf a recovered statement header leaves where its condition was.
fn walk_expr(expr: &Expr, out: &mut Vec<(vlog_parser::TextRange, String)>) {
if let ExprKind::Error(r) = &expr.kind {
out.push((r.span, r.text.clone()));
}
}
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) => {
walk_list(m.param_ports.as_deref().unwrap_or(&[]), out);
walk_ports(&m.ports, out);
m.items.iter().for_each(|i| walk_item(i, out));
}
ItemKind::Instantiation(i) => {
walk_list(i.params.as_deref().unwrap_or(&[]), out);
i.instances.iter().for_each(|inst| walk_conns(&inst.conns, out));
}
ItemKind::Class(c) => {
walk_list(c.param_ports.as_deref().unwrap_or(&[]), out);
c.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::GenBlock(b) => b.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) => {
walk_list(&f.args, out);
f.stmts.iter().for_each(|s| walk_stmt(s, out));
}
ItemKind::Task(t) => {
walk_list(&t.args, out);
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 { cond, then, els, .. } => {
walk_expr(cond, out);
walk_stmt(then, out);
els.iter().for_each(|s| walk_stmt(s, out));
}
StmtKind::Case { expr, items, .. } => {
walk_expr(expr, out);
items.iter().for_each(|i| walk_stmt(&i.stmt, out));
}
StmtKind::For { cond, body, .. } => {
cond.iter().for_each(|c| walk_expr(c, out));
walk_stmt(body, out);
}
StmtKind::While { cond, body } | StmtKind::DoWhile { cond, body, .. } => {
walk_expr(cond, out);
walk_stmt(body, out);
}
StmtKind::Repeat { count, body } => {
walk_expr(count, out);
walk_stmt(body, out);
}
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");
}
/// The out-of-block constraint cascade, pinned as a regression
/// (`docs/features/out-of-class-constraints/README.md`).
///
/// Before the fix, `constraint C::name { ... }` failed one token into the
/// header (`expected `{` (found "::")`); the recovery loop then resynchronized
/// inside the constraint body, and every out-of-block item after it produced
/// its own diagnostics. On the real corpus that turned one construct into 322
/// diagnostics in `cip_base_vseq.sv` and 274 in `hmac_base_vseq.sv` — a buffer
/// an editor cannot show usefully. This fixture is that shape in miniature:
/// with the fix it must be silent, not merely quieter.
#[test]
fn out_of_block_constraints_do_not_cascade() {
let src = "\
class my_seq;
rand int num_trans;
rand int delay;
extern constraint num_trans_c;
extern constraint delay_c;
extern function void configure();
endclass : my_seq
constraint my_seq::num_trans_c {
num_trans inside {[1:20]};
solve num_trans before delay;
}
constraint my_seq::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
}
function void my_seq::configure();
num_trans = 1;
endfunction : my_seq
";
let (_, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "out-of-block constraints still report: {diags:?}");
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
}
/// The mop-up round's nine shapes, all in one buffer: the strict parser
/// accepts them, so the tolerant parser must report nothing at all. A gap
/// that still failed here would be worse than a plain refusal — an editor
/// would show the diagnostic on every keystroke.
///
/// See `docs/features/testbench-mopup/README.md`.
#[test]
fn the_mopup_shapes_report_nothing_in_tolerant_mode() {
let src = "\
package p;
typedef enum logic [1:0] {ReqPeriResetIdx[0:1], ReqMainPwrResetIdx} reset_idx_e;
typedef struct {
rand bit cpol;
randc bit [3:0] csnlead;
} cfg_t;
endpackage
module tb;
virtual spi_if.tb tb_sif = sif.tb;
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u_fifo_exc_if (.clk_i);
initial begin
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
typedef bit data_result[];
foreach (cfg.mem_bkdr_util_h[, bank]) begin
q.push_back(mem_item_t'{addr, mask});
end
end
endmodule
";
let (_, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "a mop-up shape still reports: {diags:?}");
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
}
// ----------------------------------------------------------------------
// 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());
}
/// **Inverted by header recovery (TODO §32).** Until 2026-09-03 the unclosed
/// `(` swallowed everything up to the next `;` and the whole instantiation was
/// one `ItemKind::Error`, `wire w;` included. Now the instantiation keeps its
/// name and the connection that was typed, the half-typed one is an error
/// *element*, and the declaration under it is an item of the module again.
#[test]
fn a_half_typed_instantiation_costs_one_connection() {
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, "{diags:?}");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation, got {}", kind_name(&m.items[0]))
};
assert_eq!(inst.module, "sub");
assert_eq!(inst.instances[0].name, "u0");
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
assert_eq!(conns.len(), 1);
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
// The line under the broken connection is the module's again, not part of
// the list: `wire w;` is a sibling item.
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
assert_eq!(error_nodes(&file).len(), 1);
}
/// The QA shape of 2026-09-02 (`docs/features/header-recovery/README.md`):
/// a half-typed `#(` override whose value would read as the next instance.
/// Nothing inside the list fails on its own — `u0 (.a(x), .b(y))` is a legal
/// call with named arguments — so before §36.2 the greedy parse swallowed the
/// instance and the whole instantiation collapsed into one error item that ate
/// the `endmodule` too. It now costs the one override.
#[test]
fn a_half_typed_override_does_not_swallow_the_next_instance() {
let src = "module m;\n sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(&src[diags[0].span.as_range()], "(", "the diagnostic points at the unclosed `(`");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 1, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("{}", kind_name(&m.items[0]))
};
let params = inst.params.as_ref().expect("an override list");
assert_eq!(params.len(), 2);
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("WIDTH"));
assert_eq!(params[1].error().map(|r| r.text.as_str()), Some(".DEPTH("));
assert_eq!(inst.instances.len(), 1);
assert_eq!(inst.instances[0].name, "u0");
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
assert_eq!(conns.len(), 2, "both connections of the instance survive");
// The `endmodule` was consumed by the module, not by the error: one
// diagnostic above already says so, and the module's span ends at it.
assert_eq!(&src[m.items[0].span.as_range()], "sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));");
}
/// The same lookahead covers the connection list. `u1` cannot be a second
/// instance of `sub` — no comma was written — so it becomes an item of the
/// module, which is one error node instead of the whole rest of the body.
#[test]
fn a_half_typed_connection_does_not_swallow_the_next_instance() {
let src = "module m;\n sub u0 (.a(\n u1 (.b(y));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "{diags:?}");
assert_eq!(&src[diags[0].span.as_range()], "(");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("{}", kind_name(&m.items[0]))
};
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
assert_eq!(conns.len(), 1);
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
assert_eq!(error_nodes(&file).len(), 2, "the connection and the orphaned `u1 (...)`");
}
/// The ambiguous shape stays ambiguous. With the parentheses balancing, the
/// value *closes* — the lookahead says nothing is wrong and the greedy parse
/// wins, exactly as before §36.2. Pinned so nobody "fixes" it: the parser
/// cannot know whether the author meant a call or a forgotten `)`.
#[test]
fn a_connection_value_whose_parens_balance_is_still_read_greedily() {
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "{diags:?}");
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 1);
let ItemKind::Error(raw) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
assert_eq!(raw.text, "sub #(.D(\n u0 (.a(x)));");
}
/// A legal value written over three lines — whose middle line opens with an
/// identifier followed by `(`, the very shape the lookahead hunts for — parses
/// identically in both modes, because the value closes.
#[test]
fn a_legal_multi_line_connection_value_is_untouched() {
let src = "module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "{diags:?}");
assert!(parse_source(src).is_ok(), "and strict mode reads it too");
let m = module_named(&file, "m");
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("{}", kind_name(&m.items[0]))
};
let params = inst.params.as_ref().expect("an override list");
assert_eq!(params.len(), 1);
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("DEPTH"));
}
// ----------------------------------------------------------------------
// Header recovery (TODO §32): one test per shape, with exact counts
// ----------------------------------------------------------------------
/// (a) The QA shape this round was written for: a parameter with no value.
/// One diagnostic, one item, and a module that still holds its body.
#[test]
fn a_half_typed_parameter_costs_one_parameter() {
let src = "module m #(parameter W = , parameter X = 4) (input a); wire ok; endmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(file.items.len(), 1, "{:?}", file.items.iter().map(kind_name).collect::<Vec<_>>());
let m = module_named(&file, "m");
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 2);
assert_eq!(params[0].error().map(|r| r.text.as_str()), Some("parameter W ="));
assert_eq!(params[1].ok().map(|p| p.name.as_str()), Some("X"));
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
assert_eq!(ports.len(), 1);
assert_eq!(ports[0].ok().map(|p| p.name.as_str()), Some("a"));
assert_eq!(m.items.len(), 1, "the body survives the header");
assert!(matches!(&m.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[0]));
}
/// (b) The missing comma of a port half typed on the line above: the list
/// reads on to the ports after it, and says once that the `,` is missing.
#[test]
fn a_missing_comma_in_a_port_list_keeps_the_ports_after_it() {
let src = "module m (input logic a, inp\n output b);\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert!(diags[0].message.starts_with("expected `,`"), "{}", diags[0]);
let PortList::Ansi(ports) = &module_named(&file, "m").ports else { panic!("ANSI ports") };
let names: Vec<&str> = ports.iter().filter_map(|p| p.ok()).map(|p| p.name.as_str()).collect();
assert_eq!(names, ["a", "inp", "b"], "the port after the typo survives");
assert_eq!(error_nodes(&file).len(), 0, "a missing comma costs no element");
}
/// (c) A parameter list truncated at end of file — the mid-edit state itself.
/// The module keeps the parameter that was typed; the two diagnostics are the
/// unclosed `)` and the unclosed module, one each.
#[test]
fn a_parameter_list_truncated_at_eof_keeps_its_module() {
let src = "module m #(parameter W = 8,\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "{diags:?}");
assert!(diags[0].message.starts_with("expected `)`"), "{}", diags[0]);
assert!(diags[1].message.starts_with("expected `endmodule`"), "{}", diags[1]);
let m = module_named(&file, "m");
let params = m.param_ports.as_ref().expect("a parameter port list");
assert_eq!(params.len(), 1);
assert_eq!(params[0].ok().map(|p| p.name.as_str()), Some("W"));
}
/// (d) The `for` header the error-recovery README documented as costing two
/// diagnostics: the `;`s inside it are invisible to the skip now, so it costs
/// one, and the loop keeps its body.
#[test]
fn a_half_typed_for_header_keeps_the_loop_and_its_body() {
let src = "module m;\n initial begin\n for (i = 0; i < ; i = i + 1) x = 1;\n y = 2;\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 2, "the statement after the loop is untouched");
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
let Some(Expr { kind: ExprKind::Error(raw), .. }) = cond else {
panic!("expected an error condition")
};
assert_eq!(raw.text, "i = 0; i < ; i = i + 1");
assert!(matches!(body.kind, StmtKind::Assign { .. }), "the body is the `x = 1;`");
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }));
}
/// (d′) The same header truncated mid-condition, where the block ends right
/// under it: the loop survives with an empty body rather than eating the
/// `end` its block is waiting for.
#[test]
fn a_for_header_truncated_mid_condition_does_not_eat_the_end() {
let src = "module m;\n initial begin\n for (int i = 0; i <\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 1);
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
assert!(matches!(cond, Some(Expr { kind: ExprKind::Error(_), .. })));
let StmtKind::Error(raw) = &body.kind else { panic!("expected an empty body") };
assert_eq!(raw.text, "", "nothing was typed there, and nothing is invented");
}
/// (f) A formal list left open, with the body under it: the function and the
/// module around it both survive.
#[test]
fn a_half_typed_formal_list_keeps_its_function() {
let src = "module m;\n function int f(input int a,\n f = a;\n endfunction\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 1);
let ItemKind::Function(f) = &m.items[0].kind else {
panic!("expected a function, got {}", kind_name(&m.items[0]))
};
assert_eq!(f.name, "f");
assert_eq!(f.args.first().and_then(|a| a.ok()).map(|a| a.name.as_str()), Some("a"));
}
/// (g) A condition left open, with the statements under it: the `if` keeps
/// its shape and its then-branch.
#[test]
fn a_half_typed_if_condition_keeps_its_branch() {
let src =
"module m;\n initial begin\n if (a &&\n x = 1;\n y = 2;\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert_eq!(stmts.len(), 1);
let StmtKind::If { cond, then, els, .. } = &stmts[0].kind else { panic!("expected an if") };
assert!(matches!(cond.kind, ExprKind::Error(_)), "{:?}", cond.kind);
assert!(els.is_none());
assert!(matches!(then.kind, StmtKind::Assign { .. }), "the branch is the `y = 2;`");
}
/// The other statement headers recover through the same helper, so one test
/// covers them: each keeps its node, its body and exactly one diagnostic.
#[test]
fn the_other_statement_headers_recover_the_same_way() {
let shapes: &[(&str, &str)] = &[
("while", "module m;\n initial begin\n while (a &&\n x = 1;\n end\nendmodule\n"),
("repeat", "module m;\n initial begin\n repeat (a &&\n x = 1;\n end\nendmodule\n"),
("case", "module m;\n initial begin\n case (a &&\n x = 1;\n endcase\n end\nendmodule\n"),
];
for (name, src) in shapes {
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{name}: {diags:?}");
let m = module_named(&file, "m");
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("{name}: expected initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("{name}: expected a block") };
let kind = &stmts[0].kind;
let cond = match kind {
StmtKind::While { cond, .. } => cond,
StmtKind::Repeat { count, .. } => count,
StmtKind::Case { expr, .. } => expr,
other => panic!("{name}: {:?}", std::mem::discriminant(other)),
};
assert!(matches!(cond.kind, ExprKind::Error(_)), "{name}: {:?}", cond.kind);
}
}
/// The whole point, stated once: a broken header no longer costs the module.
/// This is the shape the error-recovery README's QA finding described — three
/// items and two diagnostics — measured again here as one and one.
#[test]
fn a_broken_header_no_longer_distorts_the_tree() {
let src = "module m #(parameter W = , parameter X = 4) (input a);\n wire ok;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(file.items.len(), 1, "the body no longer re-parses at file scope");
let m = module_named(&file, "m");
assert!(m.end_label.is_none() && !m.items.is_empty());
// And no orphaned `endmodule` behind it.
assert!(!file.items.iter().any(|i| matches!(i.kind, ItemKind::Error(_))));
}
#[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(_)));
}
// ----------------------------------------------------------------------
// A bare `begin … end` where an item belongs (TODO §36.1)
// ----------------------------------------------------------------------
/// The block a `begin` opens at module scope is kept, with its items and with
/// everything written after it. It is still an error — one diagnostic, at the
/// keyword — so the formatter goes on refusing the file; what changed is that
/// recovery no longer throws the rest of the module away.
#[test]
fn a_module_scope_begin_block_keeps_its_items_and_the_items_after_it() {
let src = "module m;\n begin\n wire a;\n end\n assign b = 1;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(&src[diags[0].span.as_range()], "begin");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
assert!(b.is_block);
assert_eq!(b.label, None);
assert_eq!(b.items.len(), 1);
assert!(matches!(&b.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&b.items[0]));
assert!(matches!(&m.items[1].kind, ItemKind::ContAssign(_)), "{}", kind_name(&m.items[1]));
assert!(error_nodes(&file).is_empty(), "the block is a node, not a leaf");
}
/// The same one scope in: `generate begin … end endgenerate`. The region keeps
/// its `endgenerate` and the module keeps the items after it.
#[test]
fn a_generate_region_begin_block_keeps_its_items_and_the_items_after_it() {
let src = "module m;\n generate\n begin : g\n wire a;\n end\n \
endgenerate\n wire ok;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
assert_eq!(&src[diags[0].span.as_range()], "begin");
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
panic!("{}", kind_name(&m.items[0]))
};
assert_eq!(items.len(), 1);
let ItemKind::GenBlock(b) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
assert_eq!(b.label.as_deref(), Some("g"));
assert_eq!(b.items.len(), 1);
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
}
/// Strict mode is untouched: both shapes are still a hard parse error, which
/// is what keeps every corpus file byte-identical.
#[test]
fn strict_mode_still_refuses_a_bare_begin_block() {
for src in [
"module m;\n begin\n wire a;\n end\nendmodule\n",
"module m;\n generate\n begin\n wire a;\n end\n endgenerate\nendmodule\n",
] {
let err = parse_source(src).expect_err("strict mode must refuse a bare `begin`");
assert!(err.to_string().contains("begin"), "{err}");
}
}
/// `end : label` on the recovered block lands in `end_label`, the way it does
/// on any other generate block.
#[test]
fn a_bare_begin_block_keeps_its_end_label() {
let src = "module m;\n begin : b\n wire a;\n end : b\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 1, "{diags:?}");
let m = module_named(&file, "m");
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
assert_eq!(b.label.as_deref(), Some("b"));
assert_eq!(b.end_label.as_deref(), Some("b"));
let label_span = b.end_label_span.expect("an end-label span");
assert_eq!(&src[label_span.as_range()], "b");
}
/// A block inside a block recovers the same way, once per keyword, and both
/// blocks keep what was written in them.
#[test]
fn a_begin_block_nested_in_another_recovers_the_same_way() {
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "{diags:?}");
for d in &diags {
assert_eq!(&src[d.span.as_range()], "begin");
}
let m = module_named(&file, "m");
assert_eq!(m.items.len(), 1);
let ItemKind::GenBlock(outer) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
assert_eq!(outer.items.len(), 1);
let ItemKind::GenBlock(inner) = &outer.items[0].kind else {
panic!("{}", kind_name(&outer.items[0]))
};
assert!(matches!(&inner.items[0].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(PARSE_STACK_SIZE)
.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(PARSE_STACK_SIZE)
.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);
}
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com