assert/assume/cover/restrict property (...) [action block], optionally labeled, at item and statement position; sequence...endsequence and property...endproperty declarations. Verbatim pass-through like constraint/covergroup; verify.rs untouched, attack tests added. Coverage loop round 1, cluster 4: 699 -> 712 / 820 (85.2% -> 86.8%). Feature README: docs/features/assertions/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
1090 lines
49 KiB
Rust
1090 lines
49 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.
|
|
//!
|
|
//! Name spans are held to a stronger rule than containment: every `name_span`
|
|
//! must slice back to *exactly* the name it claims. That is the property
|
|
//! `vlog_semantic` used to re-derive by scanning source text, and it is what
|
|
//! makes a declared name addressable without the source.
|
|
|
|
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 leading BOM: skipped like whitespace, so it lives in the gap before
|
|
// the first token. Anywhere else it is a lex error.
|
|
"\u{feff}module m;\n wire w;\nendmodule\n",
|
|
"\u{feff}// only a comment\n",
|
|
"\u{feff}",
|
|
// Implicit sensitivity lists spelled with spaces inside the parens: the
|
|
// attribute scan backs off and `(` `*` `)` are three plain tokens.
|
|
"module m;\n always @(* ) y = a;\n always @( * ) z = a;\n always @(*\n ) w = a;\nendmodule\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",
|
|
// Compiler directives between the elements of a header's lists.
|
|
"module m #(\n`ifdef X\n parameter int P = 1,\n`endif\n parameter int Q = 2\n) (\n input a,\n`ifndef Y\n input b,\n`endif\n input c\n);\nendmodule\n",
|
|
// ... and between enum members, next to a macro invocation.
|
|
"typedef enum logic {\n A,\n`include \"more.svh\"\n `LIST_OF(x)\n B\n} e_t;\n",
|
|
// ... and between an instantiation's parameter overrides and connections.
|
|
"module m;\n sub #(\n`ifdef X\n .P(1),\n`endif\n .Q(2)\n ) u (\n .a(x),\n`ifndef Y\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n",
|
|
// A list that is nothing but a directive, in both brackets.
|
|
"module m;\n sub #(\n`include \"config.vh\"\n ) u (\n`ifdef X\n`endif\n );\nendmodule\n",
|
|
// Classes: header parts, qualified members, prototypes, verbatim blocks.
|
|
"virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n",
|
|
"class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n",
|
|
"typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n",
|
|
// Dynamic types: queues, dynamic and associative arrays, `$` indexes,
|
|
// named call arguments, `case ... inside`, a bare event control.
|
|
"class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n",
|
|
"module m;\n typedef bit [3:0] q_t[$];\n task t;\n csr_wr(.ptr(ral.ovrd), .value({a, b}), .flag());\n @hier.tick;\n case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\n endtask\nendmodule\n",
|
|
// DPI imports and exports, plus package re-exports.
|
|
"package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\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];
|
|
// A leading BOM is the one non-whitespace character the lexer skips;
|
|
// it can only ever sit in the very first gap (anywhere else it is a
|
|
// lex error, so it never reaches this walk).
|
|
assert!(
|
|
gap.chars().all(|c| c.is_whitespace() || (c == '\u{feff}' && at == 0)),
|
|
"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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A name span is pinned to its content, not just contained: it must slice
|
|
/// back to exactly the name, and nest inside the node that declares it.
|
|
fn check_name(src: &str, what: &str, name: &str, span: TextRange, parent: TextRange) {
|
|
assert_inside(src, what, span, parent);
|
|
assert_eq!(slice(src, span), name, "the {what} span does not slice back to its name");
|
|
}
|
|
|
|
fn check_opt_name(
|
|
src: &str,
|
|
what: &str,
|
|
name: Option<&String>,
|
|
span: Option<TextRange>,
|
|
parent: TextRange,
|
|
) {
|
|
match (name, span) {
|
|
(Some(n), Some(s)) => check_name(src, what, n, s, parent),
|
|
(None, None) => {}
|
|
_ => panic!("{what}: the name and its span disagree about whether there is one"),
|
|
}
|
|
}
|
|
|
|
fn check_names(src: &str, what: &str, names: &[Name], parent: TextRange) {
|
|
for n in names {
|
|
check_name(src, what, &n.text, n.span, parent);
|
|
}
|
|
}
|
|
|
|
fn check_dpi_import(src: &str, dpi: Option<&DpiImport>, parent: TextRange) {
|
|
if let Some(c) = dpi.and_then(|d| d.c_identifier.as_ref()) {
|
|
check_name(src, "DPI import linkage name", &c.text, c.span, parent);
|
|
}
|
|
}
|
|
|
|
fn check_import_paths(src: &str, paths: &[ImportPath], parent: TextRange) {
|
|
for p in paths {
|
|
check_name(src, "import package", &p.pkg.text, p.pkg.span, parent);
|
|
check_name(src, "imported name", &p.item.text, p.item.span, parent);
|
|
}
|
|
}
|
|
|
|
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) => {
|
|
check_name(src, "module name", &m.name, m.name_span, here);
|
|
check_opt_name(src, "endmodule label", m.end_label.as_ref(), m.end_label_span, here);
|
|
for imp in &m.imports {
|
|
check_import_paths(src, &imp.paths, here);
|
|
}
|
|
for d in m.param_directives.iter().chain(&m.port_directives) {
|
|
assert_inside(src, "list directive", d.raw.span, here);
|
|
}
|
|
if let Some(params) = &m.param_ports {
|
|
for p in params {
|
|
assert_inside(src, "parameter port", p.span, here);
|
|
check_name(src, "parameter port name", &p.name, p.name_span, p.span);
|
|
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);
|
|
check_name(src, "port name", &p.name, p.name_span, p.span);
|
|
}
|
|
}
|
|
PortList::NonAnsi(ports) => {
|
|
for p in ports {
|
|
assert_inside(src, "port", p.span, here);
|
|
// A non-ANSI port *is* its name, so `span` is the range.
|
|
check_name(src, "port name", &p.name, p.span, here);
|
|
}
|
|
}
|
|
PortList::None | PortList::Empty => {}
|
|
}
|
|
for i in &m.items {
|
|
check_item(src, i, here);
|
|
}
|
|
}
|
|
ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } => {
|
|
check_name(src, "package name", name, *name_span, here);
|
|
check_opt_name(src, "endpackage label", end_label.as_ref(), *end_label_span, here);
|
|
for i in items {
|
|
check_item(src, i, here);
|
|
}
|
|
}
|
|
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) => {
|
|
check_name(src, "typedef name", &t.name, t.name_span, here);
|
|
if let TypedefKind::Enum(e) = &t.kind {
|
|
for d in &e.directives {
|
|
assert_inside(src, "list directive", d.raw.span, here);
|
|
}
|
|
for member in &e.members {
|
|
assert_inside(src, "enum member", member.span, here);
|
|
check_name(
|
|
src,
|
|
"enum member name",
|
|
&member.name,
|
|
member.name_span,
|
|
member.span,
|
|
);
|
|
}
|
|
}
|
|
if let TypedefKind::Struct(s) = &t.kind {
|
|
for member in &s.members {
|
|
assert_inside(src, "struct member", member.span, here);
|
|
check_declarators(src, &member.declarators, 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::ElabTask(e) => check_expr(src, e, here),
|
|
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
|
check_stmt(src, stmt, here);
|
|
}
|
|
ItemKind::Instantiation(inst) => check_instantiation(src, inst, here),
|
|
ItemKind::Bind(b) => {
|
|
// Like an instantiation's `module_span`: a hierarchical target
|
|
// is stored with its `.` glued, so the slice matches it modulo
|
|
// whitespace the source may have written around the dots.
|
|
assert_inside(src, "bind target", b.target_span, here);
|
|
assert_eq!(
|
|
despace(slice(src, b.target_span)),
|
|
despace(&b.target),
|
|
"the bind target span does not slice back to its name"
|
|
);
|
|
check_names(src, "bind instance name", &b.instances, here);
|
|
check_instantiation(src, &b.inst, here);
|
|
}
|
|
ItemKind::GateInstantiation(g) => {
|
|
for i in &g.instances {
|
|
assert_inside(src, "gate instance", i.span, here);
|
|
check_opt_name(src, "gate instance name", i.name.as_ref(), i.name_span, i.span);
|
|
for a in &i.args {
|
|
assert_inside(src, "element", a.span, i.span);
|
|
check_expr(src, &a.expr, 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::Class(c) => {
|
|
check_name(src, "class name", &c.name, c.name_span, here);
|
|
check_opt_name(src, "endclass label", c.end_label.as_ref(), c.end_label_span, here);
|
|
check_names(src, "implemented interface", &c.implements, here);
|
|
for d in &c.param_directives {
|
|
assert_inside(src, "list directive", d.raw.span, here);
|
|
}
|
|
for p in c.param_ports.iter().flatten() {
|
|
assert_inside(src, "class parameter port", p.span, here);
|
|
check_name(src, "class parameter port name", &p.name, p.name_span, p.span);
|
|
check_opt_expr(src, p.default.as_ref(), p.span);
|
|
}
|
|
if let Some(ext) = &c.extends {
|
|
assert_inside(src, "extends clause", ext.span, here);
|
|
// A scope-qualified base name (`pkg::base`) is stored with its
|
|
// `::` glued, so the slice matches it modulo that whitespace.
|
|
assert_inside(src, "base class name", ext.name_span, ext.span);
|
|
assert_eq!(
|
|
despace(slice(src, ext.name_span)),
|
|
despace(&ext.name),
|
|
"the base class span does not slice back to its name"
|
|
);
|
|
for d in &ext.param_directives {
|
|
assert_inside(src, "list directive", d.raw.span, ext.span);
|
|
}
|
|
for c in ext.params.iter().flatten() {
|
|
assert_inside(src, "base parameter override", c.span, ext.span);
|
|
check_name(src, "base parameter override name", &c.name, c.name_span, c.span);
|
|
check_opt_expr(src, c.expr.as_ref(), c.span);
|
|
}
|
|
}
|
|
for item in &c.items {
|
|
check_item(src, item, here);
|
|
}
|
|
}
|
|
// A `constraint`/`covergroup` block: one verbatim leaf whose span is
|
|
// the item's own, checked above.
|
|
ItemKind::Verbatim(_) => {}
|
|
ItemKind::Function(f) => {
|
|
check_name(src, "function name", &f.name, f.name_span, here);
|
|
check_dpi_import(src, f.dpi.as_ref(), here);
|
|
check_opt_name(src, "endfunction label", f.end_label.as_ref(), f.end_label_span, here);
|
|
for a in &f.args {
|
|
assert_inside(src, "argument", a.span, here);
|
|
check_name(src, "argument name", &a.name, a.name_span, a.span);
|
|
}
|
|
for s in &f.stmts {
|
|
check_stmt(src, s, here);
|
|
}
|
|
}
|
|
ItemKind::Task(t) => {
|
|
check_name(src, "task name", &t.name, t.name_span, here);
|
|
check_dpi_import(src, t.dpi.as_ref(), here);
|
|
check_opt_name(src, "endtask label", t.end_label.as_ref(), t.end_label_span, here);
|
|
for a in &t.args {
|
|
assert_inside(src, "argument", a.span, here);
|
|
check_name(src, "argument name", &a.name, a.name_span, a.span);
|
|
}
|
|
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(paths) => check_import_paths(src, paths, here),
|
|
ItemKind::Export(ExportDecl::Package(paths)) => check_import_paths(src, paths, here),
|
|
ItemKind::Export(ExportDecl::Dpi(d)) => {
|
|
check_name(src, "DPI export name", &d.name.text, d.name.span, here);
|
|
if let Some(c) = &d.c_identifier {
|
|
check_name(src, "DPI export linkage name", &c.text, c.span, here);
|
|
}
|
|
}
|
|
ItemKind::Genvar(names) => check_names(src, "genvar name", names, here),
|
|
ItemKind::Timeunit(_) => {}
|
|
// Leaves; only error-tolerant parsing produces the last one, which
|
|
// `tests/error_recovery.rs` checks the spans of.
|
|
ItemKind::Error(_) => {}
|
|
}
|
|
}
|
|
|
|
fn check_instantiation(src: &str, inst: &Instantiation, here: TextRange) {
|
|
// A scope-qualified module name (`pkg::mod`) is stored with its `::`
|
|
// glued, so the slice matches it modulo that whitespace.
|
|
assert_inside(src, "module name", inst.module_span, here);
|
|
assert_eq!(
|
|
despace(slice(src, inst.module_span)),
|
|
despace(&inst.module),
|
|
"the instantiated module span does not slice back to its name"
|
|
);
|
|
for d in &inst.param_directives {
|
|
assert_inside(src, "list directive", d.raw.span, here);
|
|
}
|
|
for c in inst.params.iter().flatten() {
|
|
assert_inside(src, "parameter override", c.span, here);
|
|
check_name(src, "parameter override name", &c.name, c.name_span, c.span);
|
|
check_opt_expr(src, c.expr.as_ref(), c.span);
|
|
}
|
|
for i in &inst.instances {
|
|
assert_inside(src, "instance", i.span, here);
|
|
check_name(src, "instance name", &i.name, i.name_span, i.span);
|
|
for d in &i.conn_directives {
|
|
assert_inside(src, "list directive", d.raw.span, i.span);
|
|
}
|
|
match &i.conns {
|
|
Connections::Named(cs) => {
|
|
for c in cs {
|
|
assert_inside(src, "connection", c.span, i.span);
|
|
check_name(src, "connection name", &c.name, c.name_span, c.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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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);
|
|
check_opt_name(src, "generate block label", b.label.as_ref(), b.label_span, b.span);
|
|
check_opt_name(src, "generate end label", b.end_label.as_ref(), b.end_label_span, b.span);
|
|
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_name(src, "declarator name", &d.name, d.name_span, d.span);
|
|
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 { label, label_span, stmts, end_label, end_label_span, .. }
|
|
| StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => {
|
|
check_opt_name(src, "block label", label.as_ref(), *label_span, here);
|
|
check_opt_name(src, "block end label", end_label.as_ref(), *end_label_span, here);
|
|
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 } => {
|
|
check_expr(src, e, here);
|
|
check_stmt(src, body, here);
|
|
}
|
|
StmtKind::Foreach { target, vars, body } => {
|
|
check_expr(src, target, here);
|
|
check_names(src, "foreach variable", vars, 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::Verbatim(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::NamedArg { name, name_span, value, .. } => {
|
|
check_name(src, "named argument", name, *name_span, here);
|
|
check_expr(src, value, 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, .. }
|
|
| ExprKind::Parameterized { 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 {
|
|
assert_inside(src, "element", i.span, here);
|
|
check_expr(src, &i.expr, 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(_) => {}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Name spans
|
|
// ------------------------------------------------------------------
|
|
|
|
/// One source dense enough to reach every node that carries a name span, with
|
|
/// each name asserted by hand. The walker above proves the *invariant* over
|
|
/// many sources; this proves the fields are wired to the right token, which is
|
|
/// the mistake containment cannot catch (the `GenIf` precedent).
|
|
const DENSE: &str = "\
|
|
package pkg_a;
|
|
typedef enum logic [1:0] {RED = 0, GREEN} color_e;
|
|
typedef struct packed {logic [3:0] hi; logic lo;} pair_t;
|
|
typedef logic [7:0] byte_t;
|
|
endpackage : pkg_a
|
|
|
|
module top import pkg_a::*, pkg_a::color_e; #(
|
|
parameter int W = 8,
|
|
parameter type T = logic
|
|
) (
|
|
input logic clk_i,
|
|
output byte_t data_o
|
|
);
|
|
genvar gi, gj;
|
|
wire w_a, w_b = 1'b0;
|
|
sub #(.PW(W)) u_sub (.clk(clk_i), .*);
|
|
and g_and (o, a, b);
|
|
generate
|
|
if (W > 1) begin : g_wide
|
|
wire inner;
|
|
end : g_wide
|
|
endgenerate
|
|
initial begin : b_init
|
|
foreach (arr[fi, fj]) x = fi + fj;
|
|
fork : f_par
|
|
join : f_par
|
|
end : b_init
|
|
function automatic int fn_add(input int a_i, int b_i);
|
|
return a_i + b_i;
|
|
endfunction : fn_add
|
|
task tsk_go(output int r_o);
|
|
endtask : tsk_go
|
|
endmodule : top
|
|
";
|
|
|
|
#[test]
|
|
fn every_name_span_slices_back_to_its_name() {
|
|
let src = DENSE;
|
|
let file = parse_source(src).expect("parse error");
|
|
|
|
// The package, its end label, and the three typedefs in it.
|
|
let ItemKind::Package { name, name_span, items, end_label, end_label_span, .. } =
|
|
&file.items[0].kind
|
|
else {
|
|
panic!("expected a package")
|
|
};
|
|
assert_eq!(name, "pkg_a");
|
|
assert_eq!(slice(src, *name_span), "pkg_a");
|
|
assert_eq!(slice(src, end_label_span.expect("an endpackage label")), "pkg_a");
|
|
assert_eq!(end_label.as_deref(), Some("pkg_a"));
|
|
|
|
let ItemKind::Typedef(en) = &items[0].kind else { panic!("expected the enum typedef") };
|
|
assert_eq!(slice(src, en.name_span), "color_e");
|
|
let TypedefKind::Enum(e) = &en.kind else { panic!("expected an enum") };
|
|
assert_eq!(slice(src, e.members[0].name_span), "RED");
|
|
assert_eq!(slice(src, e.members[1].name_span), "GREEN");
|
|
|
|
let ItemKind::Typedef(st) = &items[1].kind else { panic!("expected the struct typedef") };
|
|
assert_eq!(slice(src, st.name_span), "pair_t");
|
|
let TypedefKind::Struct(s) = &st.kind else { panic!("expected a struct") };
|
|
assert_eq!(slice(src, s.members[0].declarators[0].name_span), "hi");
|
|
assert_eq!(slice(src, s.members[1].declarators[0].name_span), "lo");
|
|
|
|
let ItemKind::Typedef(al) = &items[2].kind else { panic!("expected the alias typedef") };
|
|
assert_eq!(slice(src, al.name_span), "byte_t");
|
|
|
|
// The module header: name, end label, imports, parameters, ports.
|
|
let ItemKind::Module(m) = &file.items[1].kind else { panic!("expected a module") };
|
|
assert_eq!(slice(src, m.name_span), "top");
|
|
assert_eq!(slice(src, m.end_label_span.expect("an endmodule label")), "top");
|
|
let paths = &m.imports[0].paths;
|
|
assert_eq!(slice(src, paths[0].pkg.span), "pkg_a");
|
|
assert_eq!(slice(src, paths[0].item.span), "*");
|
|
assert_eq!(slice(src, paths[1].pkg.span), "pkg_a");
|
|
assert_eq!(slice(src, paths[1].item.span), "color_e");
|
|
|
|
let params = m.param_ports.as_ref().expect("a parameter port list");
|
|
assert_eq!(slice(src, params[0].name_span), "W");
|
|
// The `parameter type T` arm is a separate construction site.
|
|
assert!(params[1].is_type);
|
|
assert_eq!(slice(src, params[1].name_span), "T");
|
|
|
|
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
|
|
assert_eq!(slice(src, ports[0].name_span), "clk_i");
|
|
assert_eq!(slice(src, ports[1].name_span), "data_o");
|
|
|
|
// Body: genvars, declarators, instantiation, gate, generate, statements.
|
|
let ItemKind::Genvar(gs) = &m.items[0].kind else { panic!("expected genvars") };
|
|
assert_eq!(slice(src, gs[0].span), "gi");
|
|
assert_eq!(slice(src, gs[1].span), "gj");
|
|
|
|
let ItemKind::DataDecl(d) = &m.items[1].kind else { panic!("expected a wire declaration") };
|
|
assert_eq!(slice(src, d.declarators[0].name_span), "w_a");
|
|
assert_eq!(slice(src, d.declarators[1].name_span), "w_b");
|
|
|
|
let ItemKind::Instantiation(inst) = &m.items[2].kind else { panic!("expected an instance") };
|
|
assert_eq!(slice(src, inst.module_span), "sub");
|
|
assert_eq!(slice(src, inst.params.as_ref().expect("a parameter override")[0].name_span), "PW");
|
|
assert_eq!(slice(src, inst.instances[0].name_span), "u_sub");
|
|
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
|
assert_eq!(slice(src, conns[0].name_span), "clk");
|
|
// `.*` has no name of its own; its span is the wildcard token.
|
|
assert_eq!(slice(src, conns[1].name_span), "*");
|
|
|
|
let ItemKind::GateInstantiation(g) = &m.items[3].kind else { panic!("expected a gate") };
|
|
assert_eq!(slice(src, g.instances[0].name_span.expect("a gate name")), "g_and");
|
|
|
|
let ItemKind::GenerateRegion { items: gen, .. } = &m.items[4].kind else {
|
|
panic!("expected a generate region")
|
|
};
|
|
let ItemKind::GenIf(gi) = &gen[0].kind else { panic!("expected a generate if") };
|
|
assert_eq!(slice(src, gi.then.label_span.expect("a block label")), "g_wide");
|
|
assert_eq!(slice(src, gi.then.end_label_span.expect("an end label")), "g_wide");
|
|
|
|
let ItemKind::Initial(init) = &m.items[5].kind else { panic!("expected an initial") };
|
|
let StmtKind::Block { label_span, stmts, end_label_span, .. } = &init.kind else {
|
|
panic!("expected a block")
|
|
};
|
|
assert_eq!(slice(src, label_span.expect("a block label")), "b_init");
|
|
assert_eq!(slice(src, end_label_span.expect("an end label")), "b_init");
|
|
let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") };
|
|
assert_eq!(slice(src, vars[0].span), "fi");
|
|
assert_eq!(slice(src, vars[1].span), "fj");
|
|
let StmtKind::ForkJoin { label_span, end_label_span, .. } = &stmts[1].kind else {
|
|
panic!("expected a fork")
|
|
};
|
|
assert_eq!(slice(src, label_span.expect("a fork label")), "f_par");
|
|
assert_eq!(slice(src, end_label_span.expect("a join label")), "f_par");
|
|
|
|
let ItemKind::Function(f) = &m.items[6].kind else { panic!("expected a function") };
|
|
assert_eq!(slice(src, f.name_span), "fn_add");
|
|
assert_eq!(slice(src, f.end_label_span.expect("an endfunction label")), "fn_add");
|
|
assert_eq!(slice(src, f.args[0].name_span), "a_i");
|
|
assert_eq!(slice(src, f.args[1].name_span), "b_i");
|
|
|
|
let ItemKind::Task(t) = &m.items[7].kind else { panic!("expected a task") };
|
|
assert_eq!(slice(src, t.name_span), "tsk_go");
|
|
assert_eq!(slice(src, t.end_label_span.expect("an endtask label")), "tsk_go");
|
|
assert_eq!(slice(src, t.args[0].name_span), "r_o");
|
|
}
|
|
|
|
#[test]
|
|
fn name_spans_hold_across_the_formatter_fixtures() {
|
|
// The same walker as `every_node_span_nests_inside_its_parent`, over the
|
|
// real Verilog next door: it asserts `src[name_span] == name` on every
|
|
// declaration in every fixture, which is the corpus this crate has.
|
|
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");
|
|
let Ok(file) = parse_source(&src) else { continue };
|
|
for item in &file.items {
|
|
check_item(&src, item, file.span);
|
|
}
|
|
seen += 1;
|
|
}
|
|
assert!(seen > 0, "no fixtures found in {}", dir.display());
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_byte_name_gets_its_exact_byte_range() {
|
|
// Escaped identifiers run to the next whitespace, so they are the one way
|
|
// a Verilog name carries multi-byte text. Multi-byte comments before each
|
|
// name also shift every offset that follows them.
|
|
let src = "// αβγ\nmodule \\mödule✓ ;\n // ünïcode λ\n wire \\wïre✓ ;\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!(m.name, "\\mödule✓");
|
|
assert_eq!(slice(src, m.name_span), "\\mödule✓");
|
|
assert_eq!(m.name_span.len(), 11, "6 ASCII (\\mdule) + ö (2) + ✓ (3)");
|
|
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a wire") };
|
|
assert_eq!(slice(src, d.declarators[0].name_span), "\\wïre✓");
|
|
}
|
|
|
|
#[test]
|
|
fn a_name_after_attributes_and_comments_is_still_pinned() {
|
|
// `(* ... *)` is code inside the item's span, and comments sit between the
|
|
// keyword and the name; neither may drag the name span along.
|
|
let src = "(* keep = \"true\" *)\nmodule /* c1 */ m /* c2 */ ;\n (* dont_touch *) wire // c3\n 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.name_span), "m");
|
|
assert!(
|
|
file.items[0].span.start < m.name_span.start,
|
|
"the attribute is inside the item span and before the name"
|
|
);
|
|
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a wire") };
|
|
assert_eq!(slice(src, d.declarators[0].name_span), "w");
|
|
}
|
|
|
|
#[test]
|
|
fn a_label_and_its_end_label_get_separate_spans() {
|
|
// Two occurrences of the same text: a span that found the first one where
|
|
// it should have found the second still slices back to the right string,
|
|
// so the two must be distinguished by position.
|
|
let src = "module m;\n initial begin : same\n x = 1;\n end : same\nendmodule : m\n";
|
|
let file = parse_source(src).expect("parse error");
|
|
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
|
let ItemKind::Initial(s) = &m.items[0].kind else { panic!("expected an initial") };
|
|
let StmtKind::Block { label_span, end_label_span, .. } = &s.kind else {
|
|
panic!("expected a block")
|
|
};
|
|
let open = label_span.expect("a block label");
|
|
let close = end_label_span.expect("an end label");
|
|
assert_eq!(slice(src, open), "same");
|
|
assert_eq!(slice(src, close), "same");
|
|
assert!(open.end < close.start, "the two labels are different occurrences");
|
|
assert_eq!(open.start as usize, src.find("begin : same").expect("the begin") + 8);
|
|
}
|