Files
lucisv/crates/vlog_parser/tests/spans.rs
T
lucioandClaude Fable 5 02f68655b5 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]>
2026-08-19 05:23:05 -07:00

653 lines
27 KiB
Rust

//! Span invariants: the token stream tiles the source, and every AST node's
//! span slices back to the construct it came from.
//!
//! This is the token-level half of the `reconstruct(tree) == input` invariant
//! TODO.md §6 asks for. The AST-level half needs a printer that walks the tree
//! emitting spans, which does not exist yet; what is testable today is that no
//! source byte is unreachable from the token stream, and that node spans nest.
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source, tokenize};
/// Sources covering every construct the parser supports, plus the shapes that
/// make spans interesting: multi-byte UTF-8, CRLF, a string across a line
/// break, whitespace inside a number, two comments on one line.
const SOURCES: &[&str] = &[
"",
"\n",
" \n\t\n",
"// just a comment",
"// no trailing newline\nmodule m; endmodule",
"module m;\nendmodule\n",
"module m (input wire a, output logic [7:0] b);\n assign b = {8{a}};\nendmodule\n",
"module m #(parameter int W = 8, localparam W2 = W*2) (\n input clk\n);\nendmodule\n",
"module m (a, b);\n input a;\n output reg b;\n always @(a or b) b <= ~a;\nendmodule\n",
"package p;\n typedef enum logic [1:0] {A = 2'b00, B, C} state_e;\n typedef struct packed {\n logic [3:0] hi;\n logic lo;\n } s_t;\nendpackage : p\n",
"module m;\n initial begin : b\n for (int i = 0; i < 4; i++) begin\n $display(\"%d\", i);\n end\n case (x)\n 2'b00: y = 1;\n default: y = 0;\n endcase\n end\nendmodule\n",
"module m;\n function automatic logic [7:0] f(input logic [7:0] a, int b = 3);\n return a + b[3:0];\n endfunction\n task t; begin @(posedge clk) x <= 1; end endtask\nendmodule\n",
"module m;\n generate\n if (W > 1) begin : g\n sub #(.W(W)) u (.a(a), .b(), .*);\n end else if (W == 1) begin\n wire w;\n end else begin\n wire v;\n end\n endgenerate\nendmodule\n",
"module m;\n for (genvar i = 0; i < 4; i++) begin : loop\n and g1 (o, a, b);\n end\n case (W)\n 1: wire w1;\n default: wire wd;\n endcase\nendmodule\n",
"`timescale 1ns / 1ps\n`define WIDE 8\nmodule m;\n wire [`WIDE-1:0] w;\nendmodule\n",
"module m;\n `ASSERT_INIT(CheckW_A, W > 0)\n `uvm_info(\"id\", \"msg\", UVM_LOW);\n initial `MY_MACRO(a,\n b);\nendmodule\n",
"(* keep = \"true\" *)\nmodule m;\n (* dont_touch *) wire w;\n initial (* x *) x = 1;\nendmodule\n",
// Whitespace inside a sized literal: the one token whose text is not its
// source slice.
"module m;\n localparam A = 8 'h FF;\n localparam B = 'd 10;\nendmodule\n",
// Two comments on one line after a token: they merge into one node.
"module m;\n wire w; /* a */ /* b */\nendmodule\n",
// Comments everywhere.
"// header\n\n// second\nmodule m ( // after paren\n input a // trailing\n);\n /* block\n comment */\n wire w;\n // dangling\nendmodule\n// tail\n",
// Multi-byte UTF-8 in comments and strings.
"// λ αβγ — em dash\nmodule m;\n initial $display(\"λ = %d ünïcode\", x); // träiling ✓\nendmodule\n",
// CRLF.
"module m;\r\n wire w; // comment\r\nendmodule\r\n",
// A string literal that spans a physical line.
"module m;\n initial $display(\"line one\n line two\");\nendmodule\n",
"module m;\n assign y = a inside {[0:3], 4} ? int'(b) + {2{c}} : '{default: 0};\n assign z = pkg::t'(v.field[3:0][2 +: 2]);\nendmodule\n",
];
/// A token or a comment, in source order.
struct Piece {
span: TextRange,
text: String,
/// `None` for a comment.
kind: Option<TokenKind>,
}
/// Every token and every comment the lexer produced, in source order.
fn pieces(src: &str) -> Vec<Piece> {
let mut out = Vec::new();
for t in tokenize(src).expect("lex error") {
for c in &t.leading {
out.push(Piece { span: c.span, text: c.text.clone(), kind: None });
}
if t.kind != TokenKind::Eof {
out.push(Piece { span: t.span, text: t.text.clone(), kind: Some(t.kind) });
}
if let Some(c) = &t.trailing {
out.push(Piece { span: c.span, text: c.text.clone(), kind: None });
}
}
out
}
/// The losslessness invariant, asserted for one source:
///
/// 1. pieces are in source order and never overlap;
/// 2. every byte outside a piece is whitespace;
/// 3. concatenating the pieces and the whitespace between them reproduces the
/// source exactly;
/// 4. each piece's own `text` is its source slice — except for the two
/// normalizations the lexer performs, which may only differ by whitespace.
fn assert_covers_source(src: &str) {
let pieces = pieces(src);
let mut rebuilt = String::new();
let mut at = 0u32;
for p in &pieces {
assert!(p.span.end <= src.len() as u32, "span past the end of {src:?}: {:?}", p.span);
assert!(
p.span.start >= at,
"pieces out of order or overlapping in {src:?}: {:?} after byte {at}",
p.span
);
let gap = &src[at as usize..p.span.start as usize];
assert!(
gap.chars().all(char::is_whitespace),
"non-whitespace {gap:?} is not covered by any token in {src:?}"
);
let slice = &src[p.span.as_range()];
if slice != p.text {
// Two normalizations are allowed to rewrite whitespace: a sized
// literal's tick spacing (`8 'hFF` → `8'hFF`), and the single
// space that joins two same-line trailing comments into one node.
let is_number = p.kind == Some(TokenKind::Number);
let is_comment = p.kind.is_none();
assert!(
is_number || is_comment,
"token text {:?} is not its source slice {slice:?} in {src:?}",
p.text
);
assert_eq!(
despace(slice),
despace(&p.text),
"a {} changed more than whitespace in {src:?}",
if is_number { "number" } else { "comment" }
);
}
rebuilt.push_str(gap);
rebuilt.push_str(slice);
at = p.span.end;
}
rebuilt.push_str(&src[at as usize..]);
assert_eq!(rebuilt, src, "the token stream does not reconstruct the source");
}
fn despace(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace()).collect()
}
#[test]
fn the_token_stream_covers_every_source_byte() {
for src in SOURCES {
assert_covers_source(src);
}
}
#[test]
fn the_token_stream_covers_the_formatter_fixtures() {
// The repo's real Verilog lives next door; lexing it here is the closest
// thing to a corpus this crate has. If the fixtures ever move, this test
// says so rather than quietly passing on nothing.
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../vlog_formatter/tests/fixtures");
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let mut seen = 0;
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 src = std::fs::read_to_string(&path).expect("read fixture");
assert_covers_source(&src);
seen += 1;
}
assert!(seen > 0, "no fixtures found in {}", dir.display());
}
#[test]
fn spans_are_byte_offsets_not_character_counts() {
let src = "// λλλ\nwire w;\n";
let toks = tokenize(src).expect("lex error");
let comment = &toks[0].leading[0];
assert_eq!(&src[comment.span.as_range()], "// λλλ");
assert_eq!(comment.span.len(), 9, "3 ASCII + 6 bytes of λ");
let wire = &toks[0];
assert_eq!(&src[wire.span.as_range()], "wire");
assert_eq!(wire.span.start, 10, "one byte past the newline after a 9-byte comment");
}
#[test]
fn a_trimmed_token_span_stops_where_its_text_does() {
// Trailing whitespace is not part of a line comment or a directive.
let src = "`define A 1 \nwire w; // c \n";
let toks = tokenize(src).expect("lex error");
assert_eq!(&src[toks[0].span.as_range()], "`define A 1");
let comment = toks.iter().find_map(|t| t.trailing.as_ref()).expect("trailing comment");
assert_eq!(&src[comment.span.as_range()], "// c");
}
// ------------------------------------------------------------------
// AST node spans
// ------------------------------------------------------------------
fn slice(src: &str, span: TextRange) -> &str {
&src[span.as_range()]
}
#[test]
fn node_spans_slice_back_to_the_construct() {
let src = "module m;\n wire [1:0] w = a + b;\n always_ff @(posedge clk) q <= d;\nendmodule\n";
let file = parse_source(src).expect("parse error");
assert_eq!(slice(src, file.span), src);
assert_eq!(slice(src, file.items[0].span), src.trim_end());
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(slice(src, m.items[0].span), "wire [1:0] w = a + b;");
assert_eq!(slice(src, m.items[1].span), "always_ff @(posedge clk) q <= d;");
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(slice(src, d.ty.packed[0].span), "[1:0]");
assert_eq!(slice(src, d.declarators[0].span), "w = a + b");
let init = d.declarators[0].init.as_ref().expect("an initializer");
assert_eq!(slice(src, init.span), "a + b");
let ExprKind::Binary { lhs, rhs, .. } = &init.kind else { panic!("expected a binary") };
assert_eq!(slice(src, lhs.span), "a");
assert_eq!(slice(src, rhs.span), "b");
let ItemKind::Always { stmt, .. } = &m.items[1].kind else { panic!("expected an always") };
assert_eq!(slice(src, stmt.span), "@(posedge clk) q <= d;");
}
#[test]
fn a_gen_if_span_slices_back_to_its_text() {
// QA's mutation test showed containment alone doesn't pin GenIf.span's
// content; this slice-check does.
let src = "module m;\nif (A) begin\nwire x;\nend else if (B) begin\nwire y;\nend\nendmodule\n";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::GenIf(gi) = &m.items[0].kind else { panic!("expected a generate if") };
assert_eq!(slice(src, gi.span), "if (A) begin\nwire x;\nend else if (B) begin\nwire y;\nend");
let Some(els) = &gi.els else { panic!("expected an else branch") };
let GenElse::If(_, inner) = &**els else { panic!("expected an else-if") };
assert_eq!(slice(src, inner.span), "if (B) begin\nwire y;\nend");
}
#[test]
fn a_node_span_is_code_only_and_excludes_its_comments() {
let src = "module m;\n // leading\n wire w; // trailing\nendmodule\n";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let decl = &m.items[0];
assert_eq!(slice(src, decl.span), "wire w;");
let leading = &decl.meta.leading[0];
assert_eq!(slice(src, leading.span), "// leading");
assert!(
!decl.span.contains(leading.span.start),
"a leading comment is trivia, not part of the node's span"
);
assert!(leading.span.end < decl.span.start, "the comment's own span locates it");
}
#[test]
fn attribute_instances_are_inside_the_item_span() {
// `(* ... *)` is a real token, not trivia, so it is part of the item.
let src = "module m;\n (* keep *) wire w;\nendmodule\n";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(slice(src, m.items[0].span), "(* keep *) wire w;");
assert_eq!(slice(src, m.items[0].meta.attrs[0].span), "(* keep *)");
}
#[test]
fn a_multi_byte_source_gives_exact_node_spans() {
let src = "module m;\n // ünïcode ✓\n assign y = \"λ\" ;\nendmodule\n";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(slice(src, m.items[0].span), "assign y = \"λ\" ;");
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
assert_eq!(slice(src, a.assigns[0].rhs.span), "\"λ\"");
}
#[test]
fn a_macro_item_span_covers_the_whole_invocation() {
let src = "module m;\n `ASSERT(A,\n x > 0)\n `uvm_info(\"i\", \"m\", LOW);\nendmodule\n";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(slice(src, m.items[0].span), "`ASSERT(A,\n x > 0)");
let ItemKind::MacroItem(call) = &m.items[0].kind else { panic!("expected a macro item") };
assert_eq!(slice(src, call.raw.span), "`ASSERT(A,\n x > 0)");
// The `;` is not part of the raw text but is part of the item.
assert_eq!(slice(src, m.items[1].span), "`uvm_info(\"i\", \"m\", LOW);");
}
#[test]
fn every_node_span_nests_inside_its_parent() {
for src in SOURCES {
let Ok(file) = parse_source(src) else { continue };
for item in &file.items {
check_item(src, item, file.span);
}
}
// And on something that exercises every container at once.
let src = "package p;\n typedef struct packed { logic a; } s_t;\nendpackage\nmodule m #(parameter W = 1) (input a, output b);\n generate for (genvar i = 0; i < W; i++) begin : g\n if (i > 0) begin\n sub u (.x(a), .y());\n end\n end endgenerate\n always @(*) begin\n case (a)\n 1'b0: b = 1;\n default: b = 0;\n endcase\n end\n function f(input int q); return q; endfunction\nendmodule\n";
let file = parse_source(src).expect("parse error");
for item in &file.items {
check_item(src, item, file.span);
}
}
/// The nesting invariant has to survive error recovery too: an error node is
/// an ordinary leaf, so the tree a broken file produces must nest exactly like
/// a good one's. Uses the same exhaustive walker as the test above, which is
/// the point — a new node shape cannot skip it.
#[test]
fn recovered_error_nodes_nest_inside_their_parent() {
let broken = [
"module m;\n wire a\n wire b;\nendmodule\n",
"module m;\n initial begin\n x = 1;\nendmodule\n",
"module m;\n wire [7:\nendmodule\n",
"module m;\n sub u0 (.a(\nendmodule\n",
"module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n",
"module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n",
"module m;\n function int f;\n if (a) ; else\n endfunction\nendmodule\n",
"module m;\n always @(*) case (x)\n 1: y = ;\n default: y = 0;\n endcase\nendmodule\n",
"package p;\n localparam A = ;\n localparam B = 2;\nendpackage\n",
"!!! ???\n",
];
for src in broken {
let (file, diags) = vlog_parser::parse_source_tolerant(src);
assert!(!diags.is_empty(), "expected diagnostics for {src:?}");
for item in &file.items {
check_item(src, item, file.span);
}
}
}
fn assert_inside(src: &str, what: &str, inner: TextRange, outer: TextRange) {
assert!(
outer.start <= inner.start && inner.end <= outer.end,
"{what} {:?} ({:?}) escapes its parent {:?} ({:?})",
inner,
slice(src, inner),
outer,
slice(src, outer),
);
}
fn check_item(src: &str, item: &Item, parent: TextRange) {
assert_inside(src, "item", item.span, parent);
for attr in &item.meta.attrs {
assert_inside(src, "attribute", attr.span, item.span);
}
let here = item.span;
match &item.kind {
ItemKind::Module(m) => {
if let Some(params) = &m.param_ports {
for p in params {
assert_inside(src, "parameter port", p.span, here);
check_opt_expr(src, p.default.as_ref(), p.span);
}
}
match &m.ports {
PortList::Ansi(ports) => {
for p in ports {
assert_inside(src, "port", p.span, here);
}
}
PortList::NonAnsi(ports) => {
for p in ports {
assert_inside(src, "port", p.span, here);
}
}
PortList::None | PortList::Empty => {}
}
for i in &m.items {
check_item(src, i, here);
}
}
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
for i in items {
check_item(src, i, here);
}
}
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
assert_inside(src, "raw text", raw.span, here);
}
ItemKind::Typedef(t) => {
if let TypedefKind::Enum(e) = &t.kind {
for member in &e.members {
assert_inside(src, "enum member", member.span, here);
}
}
if let TypedefKind::Struct(s) = &t.kind {
for member in &s.members {
assert_inside(src, "struct member", member.span, here);
for d in &member.declarators {
assert_inside(src, "declarator", d.span, member.span);
}
}
}
}
ItemKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
ItemKind::DataDecl(d) => check_declarators(src, &d.declarators, here),
ItemKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
ItemKind::ContAssign(a) => {
for pair in &a.assigns {
assert_inside(src, "assignment", pair.span, here);
check_expr(src, &pair.lhs, pair.span);
check_expr(src, &pair.rhs, pair.span);
}
}
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
check_stmt(src, stmt, here);
}
ItemKind::Instantiation(inst) => {
for c in inst.params.iter().flatten() {
assert_inside(src, "parameter override", c.span, here);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
for i in &inst.instances {
assert_inside(src, "instance", i.span, here);
match &i.conns {
Connections::Named(cs) => {
for c in cs {
assert_inside(src, "connection", c.span, i.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
}
Connections::Ordered(cs) => {
for c in cs {
assert_inside(src, "connection", c.span, i.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
}
}
}
}
ItemKind::GateInstantiation(g) => {
for i in &g.instances {
assert_inside(src, "gate instance", i.span, here);
for a in &i.args {
check_expr(src, a, i.span);
}
}
}
ItemKind::GenIf(gi) => check_gen_if(src, gi, here),
ItemKind::GenFor(gf) => {
check_expr(src, &gf.cond, here);
check_gen_block(src, &gf.body, here);
}
ItemKind::GenCase(gc) => {
check_expr(src, &gc.expr, here);
for i in &gc.items {
assert_inside(src, "generate case item", i.span, here);
check_gen_block(src, &i.body, i.span);
}
}
ItemKind::Function(f) => {
for a in &f.args {
assert_inside(src, "argument", a.span, here);
}
for s in &f.stmts {
check_stmt(src, s, here);
}
}
ItemKind::Task(t) => {
for a in &t.args {
assert_inside(src, "argument", a.span, here);
}
for s in &t.stmts {
check_stmt(src, s, here);
}
}
ItemKind::Defparam(pairs) => {
for (lhs, rhs) in pairs {
check_expr(src, lhs, here);
check_expr(src, rhs, here);
}
}
ItemKind::Import(_) | ItemKind::Timeunit(_) | ItemKind::Genvar(_) => {}
// Leaves; only error-tolerant parsing produces the last one, which
// `tests/error_recovery.rs` checks the spans of.
ItemKind::Error(_) => {}
}
}
fn check_gen_if(src: &str, gi: &GenIf, parent: TextRange) {
assert_inside(src, "generate if", gi.span, parent);
check_expr(src, &gi.cond, gi.span);
check_gen_block(src, &gi.then, gi.span);
match gi.els.as_deref() {
Some(GenElse::If(_, inner)) => check_gen_if(src, inner, gi.span),
Some(GenElse::Block(b)) => check_gen_block(src, b, gi.span),
None => {}
}
}
fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) {
assert_inside(src, "generate block", b.span, parent);
for i in &b.items {
check_item(src, i, b.span);
}
}
fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) {
for d in declarators {
assert_inside(src, "declarator", d.span, parent);
check_opt_expr(src, d.init.as_ref(), d.span);
for dim in &d.unpacked {
assert_inside(src, "dimension", dim.span, d.span);
}
}
}
fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
assert_inside(src, "statement", stmt.span, parent);
let here = stmt.span;
match &stmt.kind {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for s in stmts {
check_stmt(src, s, here);
}
}
StmtKind::If { cond, then, els, .. } => {
check_expr(src, cond, here);
check_stmt(src, then, here);
if let Some(e) = els {
check_stmt(src, e, here);
}
}
StmtKind::Case { expr, items, .. } => {
check_expr(src, expr, here);
for i in items {
assert_inside(src, "case item", i.span, here);
for l in &i.labels {
assert_inside(src, "case label", l.span, i.span);
check_expr(src, &l.expr, i.span);
}
check_stmt(src, &i.stmt, i.span);
}
}
StmtKind::For { cond, body, .. } => {
check_opt_expr(src, cond.as_ref(), here);
check_stmt(src, body, here);
}
StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => {
check_expr(src, cond, here);
check_stmt(src, body, here);
}
StmtKind::Repeat { count: e, body } | StmtKind::Foreach { target: e, body, .. } => {
check_expr(src, e, here);
check_stmt(src, body, here);
}
StmtKind::Forever { body } => check_stmt(src, body, here),
StmtKind::Assign { lhs, rhs, .. } => {
check_expr(src, lhs, here);
check_expr(src, rhs, here);
}
StmtKind::ForceRelease { lhs, rhs, .. } => {
check_expr(src, lhs, here);
check_opt_expr(src, rhs.as_ref(), here);
}
StmtKind::Timing { stmt, .. } => {
if let Some(s) = stmt {
check_stmt(src, s, here);
}
}
StmtKind::Wait { cond, stmt } => {
check_expr(src, cond, here);
if let Some(s) = stmt {
check_stmt(src, s, here);
}
}
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here),
StmtKind::Directive(raw) | StmtKind::MacroStmt(MacroCall { raw, .. }) => {
assert_inside(src, "raw text", raw.span, here);
}
StmtKind::Assert { cond, then, els, .. } => {
check_expr(src, cond, here);
for s in then.iter().chain(els.iter()) {
check_stmt(src, s, here);
}
}
StmtKind::Break
| StmtKind::Continue
| StmtKind::Disable(_)
| StmtKind::Null
| StmtKind::Error(_) => {}
}
}
fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) {
if let Some(e) = e {
check_expr(src, e, parent);
}
}
fn check_expr(src: &str, e: &Expr, parent: TextRange) {
assert_inside(src, "expression", e.span, parent);
let here = e.span;
match &e.kind {
ExprKind::Unary { expr, .. }
| ExprKind::Postfix { expr, .. }
| ExprKind::Cast { expr, .. }
| ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here),
ExprKind::Binary { lhs, rhs, .. } => {
check_expr(src, lhs, here);
check_expr(src, rhs, here);
}
ExprKind::Ternary { cond, then, els, .. } => {
check_expr(src, cond, here);
check_expr(src, then, here);
check_expr(src, els, here);
}
ExprKind::Call { callee, args } => {
check_expr(src, callee, here);
for a in args {
assert_inside(src, "argument", a.span, here);
check_expr(src, &a.expr, here);
}
}
ExprKind::Index { base, index } => {
check_expr(src, base, here);
check_expr(src, index, here);
}
ExprKind::Range { base, msb, lsb, .. } => {
check_expr(src, base, here);
check_expr(src, msb, here);
check_expr(src, lsb, here);
}
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => check_expr(src, base, here),
ExprKind::Concat(items) | ExprKind::Inside { ranges: items, .. } => {
for i in items {
assert_inside(src, "element", i.span, here);
check_expr(src, &i.expr, here);
}
}
ExprKind::Repl { count, inner } => {
check_expr(src, count, here);
for i in inner {
check_expr(src, i, here);
}
}
ExprKind::AssignPattern(items) => {
for i in items {
assert_inside(src, "element", i.span, here);
check_opt_expr(src, i.key.as_ref(), here);
check_expr(src, &i.value, here);
}
}
ExprKind::ValueRange { lo, hi } => {
check_expr(src, lo, here);
check_expr(src, hi, here);
}
ExprKind::MinTypMax { min, typ, max } => {
check_expr(src, min, here);
check_expr(src, typ, here);
check_expr(src, max, here);
}
ExprKind::Type(ty) => {
for d in &ty.packed {
assert_inside(src, "dimension", d.span, here);
}
}
ExprKind::Ident(_) | ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) => {}
}
}