Files
lucisv/crates/vlog_parser/src/parser/tests/directive.rs
T
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

460 lines
19 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Macros, and the directives a list keeps between its elements.
use super::*;
#[test]
fn macro_items_and_statements() {
let file = parse_ok(
"`GLOBAL_MACRO(a, b)
package p;
`DEFINE_REGS(foo)
endpackage
module m;
`ASSERT_INIT(Check_A, N > 0)
`FFARNC(q, d, en, '0, clk_i, rst_ni);
`BARE
`BARE_SEMI;
generate
for (genvar i = 0; i < N; i++) begin : g
`FF(q[i], d[i], '0, clk_i, rst_ni)
end
endgenerate
always_ff @(posedge clk_i) begin
`DV_CHECK(a_i)
`uvm_info(\"id\", \"m\", UVM_LOW);
q <= d;
end
function automatic int f();
`TRACE_ENTER(f)
return 0;
endfunction
endmodule",
);
assert!(matches!(file.items[0].kind, ItemKind::MacroItem(_)));
}
/// The one-token lookahead in `at_macro_item` must not steal a macro that
/// names a type, a module or the target of an assignment.
#[test]
fn macro_lookahead_leaves_declarations_alone() {
let file = parse_ok(
"module m;
`MY_TYPE_T sig;
`MY_TYPE_T [3:0] vec;
`MY_MODULE u_inst (.a(sig));
`MY_MODULE #(.W(8)) u_param (.a(sig));
initial `LVALUE(x) = 1;
assign y = `PACK(a, b);
endmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert!(
!m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))),
"no item should have been read as a standalone macro invocation"
);
}
/// `` `uvm_field_int (a, b) `` — the lexer only glues a `(` that touches
/// the macro name, so the argument list arrives as separate tokens and the
/// parser has to rebuild the invocation from the source bytes.
#[test]
fn a_space_before_the_argument_list_is_still_a_macro_item() {
let file = parse_ok(
"class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int (a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let texts: Vec<&str> = c
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(call) => call.raw.text.as_str(),
other => panic!("expected a macro item, got {other:?}"),
})
.collect();
assert_eq!(
texts,
["`uvm_object_utils_begin(c)", "`uvm_field_int (a, UVM_DEFAULT)", "`uvm_object_utils_end",],
"the space and the argument text are reproduced byte-for-byte"
);
}
/// The spaced reading is offered at item and statement position only. In
/// an expression `` `A (b) `` may be `` `A `` applied to `(b)`, which
/// depends on a `` `define`` lucisv never sees.
#[test]
fn a_spaced_macro_in_expression_position_is_still_a_call() {
let file = parse_ok("module m;\nassign x = `A (b);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
assert!(
matches!(a.assigns[0].rhs.kind, ExprKind::Call { .. }),
"expression position must keep its old parse: {:?}",
a.assigns[0].rhs.kind
);
}
/// A `(` that opens the *next* line is not the macro's argument list.
#[test]
fn a_paren_on_the_next_line_does_not_join_the_macro() {
let file = parse_ok("module m;\n`BARE\ninitial x = (a);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::MacroItem(call) = &m.items[0].kind else { panic!("expected a macro item") };
assert_eq!(call.raw.text, "`BARE");
assert!(matches!(m.items[1].kind, ItemKind::Initial(_)));
}
/// A macro that ends its line is complete; the declaration below it is its
/// own item, not the declarator of a macro-named type.
#[test]
fn a_bare_macro_ending_its_line_does_not_type_the_next_declaration() {
let file = parse_ok(
"class c;\n `uvm_component_new\n\n uvm_report_server rs;\n `MY_TYPE_T sig;\nendclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
assert!(matches!(c.items[0].kind, ItemKind::MacroItem(_)));
assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)));
// Same line ⇒ still a declaration with a macro-named type.
assert!(matches!(c.items[2].kind, ItemKind::DataDecl(_)));
}
/// A macro statement that ends its line is complete whatever *kind* of
/// token opens the next line — a symbol as much as an identifier
/// (`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`).
#[test]
fn a_symbol_on_the_next_line_does_not_continue_a_macro_statement() {
let file = parse_ok(
"class c;\n\
task t;\n\
`uvm_info(`gfn, \"waiting\", UVM_MEDIUM)\n\
@(negedge rst_n);\n\
`DV_WAIT\n\
#10ns;\n\
`SEND\n\
-> ev;\n\
`PRE\n\
{a, b} = c;\n\
endtask\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Task(t) = &c.items[0].kind else { panic!("expected a task") };
let macros = t.stmts.iter().filter(|s| matches!(s.kind, StmtKind::MacroStmt(_))).count();
assert_eq!(macros, 4, "each macro stands alone: {:?}", t.stmts);
assert_eq!(t.stmts.len(), 8, "and each next line opens its own statement");
}
/// The same rule must not fire on the macro's *own* line, and a macro
/// whose argument list spans lines owns every line it covers.
#[test]
fn a_symbol_on_the_macros_own_line_still_continues_it() {
let file = parse_ok(
"module m;\n\
`MY_TYPE_T [3:0] vec;\n\
`PACKED(a,\n\
b) [7:0] wide;\n\
endmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert!(
!m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))),
"both lines declare: {:?}",
m.items
);
}
#[test]
fn macro_semicolon_is_reproduced_not_invented() {
let file = parse_ok("module m;\n`A(x)\n`B(y);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let semis: Vec<bool> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::MacroItem(call) => call.semi,
other => panic!("expected a macro item, got {other:?}"),
})
.collect();
assert_eq!(semis, [false, true]);
}
#[test]
fn a_directive_between_ports_records_its_place_and_the_commas_around_it() {
let src = "module m (\n input a,\n`ifdef X\n input b,\n`endif\n input c\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.len(), 3);
assert_eq!(
ports.iter().map(|p| p.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &m.port_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second port");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2, "written before the third port");
assert!(d.iter().all(|d| !d.comma), "no comma follows either directive");
}
#[test]
fn a_comma_written_after_a_directive_belongs_to_the_directive() {
// The shape `prim_sparse_fsm_flop.sv` writes: the comma lives inside
// the `ifdef arm so that both arms are legal. Deriving the comma from
// the element's position would move it across the directive.
let src = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
assert_eq!(params.len(), 2);
assert!(!params[0].comma, "the first parameter wrote no comma of its own");
assert!(!params[1].comma);
assert_eq!(m.param_directives.len(), 2);
assert!(m.param_directives[0].comma, "`ifdef carries the comma");
assert!(!m.param_directives[1].comma);
}
#[test]
fn a_list_with_no_directive_keeps_an_empty_directive_vector() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing list byte-for-byte unchanged.
let src = "module m #(parameter int P = 1) (input a, input b);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
assert!(m.param_directives.is_empty());
assert!(m.port_directives.is_empty());
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
}
#[test]
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
// lucisv does not evaluate the condition: an `ifdef/`else pair simply
// contributes every element of both arms, in source order.
let src = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
assert!(ports.iter().all(|p| !p.comma), "neither arm's port wrote a comma");
assert_eq!(m.port_directives.len(), 3);
}
#[test]
fn a_directive_between_enum_members_lands_on_the_enum() {
let src = "typedef enum logic {\n A,\n`include \"more.svh\"\n B\n} e_t;\n";
let file = parse_ok(src);
let ItemKind::Typedef(t) = &file.items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.members.len(), 2);
assert_eq!(e.directives.len(), 1);
assert_eq!(e.directives[0].raw.text, "`include \"more.svh\"");
assert_eq!(e.directives[0].before, 1);
}
#[test]
fn a_comment_before_a_list_directive_stays_with_the_directive() {
let src = "module m (\n input a,\n // only when X\n`ifdef X // why\n input b\n`endif\n);\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let d = &m.port_directives[0];
assert_eq!(d.meta.leading.len(), 1);
assert_eq!(d.meta.leading[0].text, "// only when X");
assert_eq!(d.meta.trailing.as_ref().expect("a trailing comment").text, "// why");
}
#[test]
fn a_directive_inside_an_element_is_still_a_parse_error() {
// A directive runs to end of line, so it can only stand *between*
// elements. One written mid-declaration is out of scope by design;
// this pins that it is refused rather than half-parsed.
let src = "module m (\n input\n`ifdef X\n logic\n`endif\n a\n);\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error"), src).is_err());
}
fn instantiation_of(file: &SourceFile) -> &Instantiation {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(i) = &m.items[0].kind else { panic!("expected an instantiation") };
i
}
#[test]
fn a_directive_between_connections_records_its_place_and_the_commas() {
let src =
"module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.len(), 3);
assert_eq!(
conns.iter().map(|c| c.comma).collect::<Vec<_>>(),
vec![true, true, false],
"the commas the source wrote, not the ones the positions imply"
);
let d = &inst.instances[0].conn_directives;
assert_eq!(d.len(), 2);
assert_eq!(d[0].raw.text, "`ifdef X");
assert_eq!(d[0].before, 1, "written before the second connection");
assert_eq!(d[1].raw.text, "`endif");
assert_eq!(d[1].before, 2);
assert!(d.iter().all(|d| !d.comma));
assert!(inst.param_directives.is_empty(), "the override list holds none");
}
#[test]
fn a_directive_between_parameter_overrides_lands_on_the_instantiation() {
// The `picorv32/testbench.v` shape: nested `ifdef, the outer one
// wrapping the whole override list.
let src = "module m;\n sub #(\n`ifndef S\n`ifdef T\n .P(0),\n`endif\n .Q(1)\n`endif\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let params = oks(inst.params.as_ref().expect("an override list"));
assert_eq!(params.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["P", "Q"]);
assert_eq!(params.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
let d = &inst.param_directives;
assert_eq!(d.iter().map(|d| d.before).collect::<Vec<_>>(), vec![0, 0, 1, 2]);
assert_eq!(d[0].raw.text, "`ifndef S");
assert_eq!(d[3].raw.text, "`endif");
}
#[test]
fn an_override_list_may_be_nothing_but_a_directive() {
// `picorv32/scripts/torture/testbench.v`: the whole `#( ... )` is one
// `include, so there is no element to hang the directive on.
let src = "module m;\n sub #(\n`include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.params.as_ref().expect("a written `#()`").is_empty());
assert_eq!(inst.param_directives.len(), 1);
assert_eq!(inst.param_directives[0].raw.text, "`include \"config.vh\"");
assert_eq!(inst.param_directives[0].before, 0);
}
#[test]
fn a_connection_list_may_be_nothing_but_a_directive() {
let src = "module m;\n sub u (\n`ifdef X\n`endif\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("an element-less list has no `.` to make it named")
};
assert!(conns.is_empty());
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn a_directive_before_the_first_connection_does_not_hide_the_dot() {
// The harvest must run before the `.`-peek that chooses named over
// ordered connections, or the backtick is read as a positional value.
let src = "module m;\n sub u (\n`ifdef X\n .a(x),\n`endif\n .b(y)\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.len(), 2);
assert_eq!(inst.instances[0].conn_directives[0].before, 0);
}
#[test]
fn a_directive_between_positional_connections_is_harvested_too() {
let src = "module m;\n sub u (\n x,\n`ifdef X\n y,\n`endif\n z\n );\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("expected ordered connections")
};
let conns = oks(conns);
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, true, false]);
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
#[test]
fn an_instantiation_with_no_directive_keeps_empty_directive_vectors() {
// The harvest is a no-op unless a directive is actually there, which
// is what keeps every pre-existing instantiation byte-for-byte alike.
let src = "module m;\n sub #(.P(1)) u (.a(x), .b(y));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
assert!(inst.param_directives.is_empty());
assert!(inst.instances[0].conn_directives.is_empty());
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
}
#[test]
fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() {
// Superseded twice. `directive-in-statements` (2026-08-29) made a
// *conditional* region inside a connection's parens a verbatim
// capture rather than a refusal — of the whole item. TODO §26
// narrowed the capture to the one connection's **value**, so the
// instantiation is a real node again: its module, its instance and
// its other connections are all structural, and only the region
// itself is opaque bytes.
let src = "module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
panic!("expected an instantiation")
};
assert_eq!(inst.module, "sub");
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns[0].name, "a");
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &conns[0].expr else {
panic!("expected a verbatim value")
};
assert!(raw.text.starts_with("`ifdef X"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
// Any *other* directive there is still an ordinary parse error: the
// recovery triggers on `ifdef / `ifndef only.
let msg = parse_err(
"module m;\n sub u (\n .a(\n`include \"x.vh\"\n y\n )\n );\nendmodule\n",
);
assert!(msg.contains("`include"), "{msg}");
}
/// The strict entry point keeps its contract: it fails at the *first*
/// error, with the same message tolerant mode files as its first
/// diagnostic.
#[test]
fn strict_parsing_still_stops_at_the_first_error() {
let src = "module m;\n wire a\n wire b;\n wire c\nendmodule\n";
let err = parse(tokenize(src).expect("lex error"), src).expect_err("strict must refuse");
let (_, diags) = crate::parse_source_tolerant(src);
assert_eq!(diags.len(), 2, "tolerant mode reports both");
assert_eq!(err.message, diags[0].message);
assert_eq!((err.line, err.col), (diags[0].line, diags[0].col));
}
#[test]
fn a_macro_followed_by_a_hierarchical_call_stands_alone() {
// `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(a);` — a declarator name is
// never followed by `.`, so the macro is a standalone statement.
let f = parse_ok(
"module m;\n task t;\n `WAIT_FOR_RESET\n cov.cg.sample(a);\n endtask\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
assert!(matches!(&task.stmts[0].kind, StmtKind::MacroStmt(_)));
assert!(matches!(&task.stmts[1].kind, StmtKind::ExprStmt(_)));
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com