//! Split conditional regions (`docs/features/directive-split/README.md`) and //! the opening split of `directive-in-statements`. use super::*; // ------------------------------------------------------------------ // Split conditional regions (`docs/features/directive-split/README.md`) // ------------------------------------------------------------------ /// The verbatim item a split conditional region collapsed into, with the /// items that came before and after it, so every test can also assert /// that nothing around the region was swallowed. fn split_items(file: &SourceFile) -> Vec { file.items .iter() .map(|i| match &i.kind { ItemKind::Verbatim(raw) => format!("verbatim:{}", raw.text), ItemKind::Directive(raw) => format!("directive:{}", raw.text), ItemKind::DataDecl(_) => "decl".to_string(), ItemKind::ParamDecl(_) => "param".to_string(), ItemKind::Typedef(_) => "typedef".to_string(), _ => "other".to_string(), }) .collect() } #[test] fn alternative_declaration_heads_sharing_one_body_are_captured_verbatim() { // corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98 let src = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] \ = {\n`endif\n MVENDORID\n};\n\nparameter int AFTER = 1;\n"; let f = parse_ok(src); let kinds = split_items(&f); assert_eq!(kinds.len(), 3, "{kinds:?}"); assert_eq!(kinds[0], "directive:`ifdef DSIM"); assert_eq!(kinds[2], "param", "the item after the region was not swallowed"); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; assert_eq!(raw.text, src[raw.span.as_range()]); assert!(raw.text.starts_with("privileged_reg_t"), "{:?}", raw.text); assert!(raw.text.ends_with("};"), "{:?}", raw.text); assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{:?}", raw.text); } #[test] fn alternative_struct_bodies_sharing_one_closing_are_captured_verbatim() { // corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236 let src = "package p;\n`ifdef _VCP\n typedef struct packed {\n bit l;\n`else\n \ typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n\n parameter \ int AFTER = 1;\nendpackage\n"; let f = parse_ok(src); let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") }; assert_eq!(items.len(), 3, "{:?}", items.len()); let ItemKind::Verbatim(raw) = &items[1].kind else { panic!("expected a verbatim block") }; assert_eq!(raw.text, src[raw.span.as_range()]); assert!(raw.text.starts_with("typedef struct packed {"), "{:?}", raw.text); assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text); assert!(matches!(items[2].kind, ItemKind::ParamDecl(_)), "the next item survived"); } #[test] fn an_ifndef_and_an_elsif_chain_are_the_same_shape() { let src = "`ifndef A\nint x[] = {\n`elsif B\nconst int x[] = {\n`else\nstatic int x[] = \ {\n`endif\n 1\n};\n"; let f = parse_ok(src); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; // Every arm is inside the one block, and only the first arm's `{` was // counted -- otherwise the scan would still be looking for two more. assert!(raw.text.contains("`elsif B") && raw.text.contains("`else"), "{:?}", raw.text); assert!(raw.text.ends_with("};"), "{:?}", raw.text); } #[test] fn a_balanced_region_inside_the_shared_tail_does_not_end_the_scan() { let src = "`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n`ifdef B\n \ 2,\n`endif\n 3\n};\n\nparameter int AFTER = 1;\n"; let f = parse_ok(src); let kinds = split_items(&f); assert_eq!(kinds.len(), 3, "{kinds:?}"); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; assert!(raw.text.contains("`ifdef B"), "the nested region is inside: {:?}", raw.text); assert_eq!(kinds[2], "param", "the item after the region was not swallowed"); } #[test] fn comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not() { let src = "// head\n`ifdef A // which\nint x[] = { // open\n`else // other\nconst int \ x[] = {\n`endif\n // why\n 1\n}; // done\nint y;\n"; let f = parse_ok(src); assert_eq!(texts(&f.items[0].meta.leading), ["// head"]); assert_eq!(f.items[0].meta.trailing.as_ref().expect("`ifdef's own comment").text, "// which"); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; for c in ["// open", "// other", "// why"] { assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text); } assert!(!raw.text.contains("// done"), "the trailing comment was swallowed"); assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done"); } // -- the trigger refuses everything that is not a split --------------- #[test] fn a_plain_syntax_error_inside_a_complete_arm_is_still_an_error() { // Both arms are whole declarations; the `= ;` is an ordinary typo // that merely happens to sit inside a conditional region. let msg = parse_err("`ifdef A\nwire x = ;\n`else\nwire x = 1;\n`endif\n"); assert!(msg.contains("expected expression"), "{msg}"); // ... and the same typo with a bracket open before it, so the only // thing missing is the `else`/`endif` at the cursor. let msg = parse_err("`ifdef A\nint x[] = {1, };\nwire y = ;\n`else\n`endif\n"); assert!(msg.contains("expected expression"), "{msg}"); } #[test] fn a_garbage_token_run_between_directives_is_still_an_error() { let msg = parse_err("`ifdef A\n) ] }\n`else\n(\n`endif\n;\n"); assert!(msg.contains("expected item"), "{msg}"); let msg = parse_err("module m;\n`ifdef A\n = = =\n`else\n ;\n`endif\nendmodule\n"); assert!(!msg.is_empty(), "{msg}"); } #[test] fn an_unterminated_region_with_broken_code_is_still_an_error() { // No `endif at all: the scan finds no end for the region and the // original error stands. let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n 1\n};\n"); assert!(msg.contains("`else"), "{msg}"); // An `endif but no terminating `;` before the end of the file. let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n"); assert!(msg.contains("`else"), "{msg}"); } #[test] fn a_missing_semicolon_is_not_a_split() { // The arm left no bracket open, so it is a fragment of nothing: the // shape is indistinguishable from a forgotten `;` and is refused. let msg = parse_err("`ifdef A\nwire x\n`else\nwire y\n`endif\n;\n"); assert!(msg.contains("`else"), "{msg}"); } #[test] fn a_stray_endif_is_never_a_split() { // QA repro (2026-08-26): nothing opened a region, so the `endif // closes nothing and the arm before it is a fragment of nothing. // Recovering here would reformat invalid Verilog and exit 0. let msg = parse_err("int x[] = {\n`endif\n1\n};\n"); assert!(msg.contains("expected expression") && msg.contains("`endif"), "{msg}"); let msg = parse_err("module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n"); assert!(msg.contains("`endif"), "{msg}"); } #[test] fn a_closed_region_does_not_leave_a_later_endif_something_to_close() { // QA repro (2026-08-26): a legitimately closed region, then an // accidental duplicate closer, then a bracket-opening declaration. // The duplicate re-opens nothing, so the `else below is still stray. let msg = parse_err( "module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int \ x[] = {\n`endif\n 1\n};\nendmodule\n", ); assert!(msg.contains("`else"), "{msg}"); } #[test] fn a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was() { // lucisv has never validated directive nesting -- a lone `endif at // item position is an ordinary `ItemKind::Directive`, before this // work and after it. What matters is that no bracket-opening item // near it gets swallowed into a verbatim block. let f = parse_ok("wire a;\n`endif\nwire b;\n`endif\nint x[] = {1};\n"); let kinds = split_items(&f); assert_eq!( kinds, ["decl", "directive:`endif", "decl", "directive:`endif", "decl"], "nothing was collapsed into a verbatim block" ); } #[test] fn a_split_nested_inside_an_open_region_is_still_recovered() { // The guard is "a region is live", not "exactly one region is live": // both corpus shapes still recover when they sit inside an outer // `ifdef that stays open across them. let a = parse_ok( "`ifdef OUTER\n`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst \ privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n`endif\nparameter int AFTER = \ 1;\n", ); let ItemKind::Verbatim(raw) = &a.items[2].kind else { panic!("expected a verbatim block") }; assert!(raw.text.ends_with("};"), "{:?}", raw.text); // The outer region's own `endif is still its own directive item, and // the item past it was not swallowed. let kinds = split_items(&a); assert_eq!(kinds[3], "directive:`endif", "{kinds:?}"); assert_eq!(kinds[4], "param", "{kinds:?}"); let b = parse_ok( "package p;\n`ifdef OUTER\n`ifdef _VCP\n typedef struct packed {\n bit l;\n\ `else\n typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n`endif\n \ parameter int AFTER = 1;\nendpackage\n", ); let ItemKind::Package { items, .. } = &b.items[0].kind else { panic!("expected package") }; let ItemKind::Verbatim(raw) = &items[2].kind else { panic!("expected a verbatim block") }; assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text); assert!(matches!(items[4].kind, ItemKind::ParamDecl(_)), "the next item survived"); } /// `Parser::open_conds` once the whole file has parsed. The invariant it /// pins: this is the number of `` `ifdef ``/`` `ifndef `` regions opened /// **at item scope** and not closed at item scope — nothing consumed /// inside an opaque verbatim body may move it. fn open_conds_after(src: &str) -> u32 { let toks = tokenize(src).expect("lex error"); let mut p = Parser::new(toks, src, false); p.parse_source_file().expect("parse error"); p.open_conds } #[test] fn item_scope_conditional_nesting_ignores_opaque_bodies() { // QA repro (2026-08-26, round 4): an unbalanced `ifdef written inside // a construct lucisv keeps as opaque bytes used to leak into the // file's item-scope nesting, because those bodies are walked token by // token through `bump`. Every one of them must leave the count alone. assert_eq!(open_conds_after("wire x;\n"), 0); assert_eq!(open_conds_after("`ifdef A\nwire x;\n"), 1, "an item-scope region does count"); assert_eq!(open_conds_after("`ifdef A\nwire x;\n`endif\n"), 0); for body in [ "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\n", "covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\n", "module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\nendmodule\n", "module m;\n assert property (\n`ifdef FAKE\n a |-> b);\nendmodule\n", ] { assert_eq!(open_conds_after(body), 0, "an opaque body leaked: {body:?}"); } } #[test] fn an_unbalanced_ifdef_inside_an_opaque_body_cannot_launder_a_later_stray_endif() { // The end-to-end shape of the leak above: the polluted count used to // make an unrelated stray `endif look like a live region's closer. let msg = parse_err( "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = \ {\n`endif\n1\n};\n", ); assert!(msg.contains("`endif"), "{msg}"); let msg = parse_err( "covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = \ {\n`endif\n1\n};\n", ); assert!(msg.contains("`endif"), "{msg}"); let msg = parse_err( "module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = \ {\n`endif\n1\n};\nendmodule\n", ); assert!(msg.contains("`endif"), "{msg}"); // Control: the same shape with the inner directive balanced. The tail // is still a stray `endif with no live region, so it still refuses -- // the count was never the thing making the tail legal. let msg = parse_err( "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint \ y[] = {\n`endif\n1\n};\n", ); assert!(msg.contains("`endif"), "{msg}"); } #[test] fn suppressing_opaque_bodies_does_not_suppress_the_regions_around_them() { // Over-suppression guard: balanced directives inside an opaque body, // then a genuine split later in the same file. let f = parse_ok( "class c;\n constraint co {\n`ifdef X\n x < 10;\n`endif\n }\nendclass\n`ifdef \ DSIM\nint y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};\nparameter int AFTER = \ 1;\n", ); assert!(matches!(f.items[2].kind, ItemKind::Verbatim(_)), "{:?}", split_items(&f)); // Under-suppression guard: an earlier verbatim item (a constraint) // inside the very region the split sits in. let f = parse_ok( "`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \ {\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n", ); let kinds = split_items(&f); assert_eq!(kinds[3], "verbatim:int y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};"); assert_eq!(kinds[4], "directive:`endif"); assert_eq!(kinds[5], "param"); assert_eq!( open_conds_after( "`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \ {\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n" ), 0, "the recovered block accounted for the `endif it swallowed" ); } #[test] fn a_recovered_block_leaves_the_right_nesting_behind_it() { // The block swallows the region's own `endif, so the count has to come // down with it -- otherwise the next `endif looks like it closes // something and the stray after it gets laundered. let src = "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ 1\n};\n`endif\nparameter int AFTER = 1;\n"; assert_eq!(open_conds_after(src), 0); let msg = parse_err( "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ 1\n};\n`endif\nint z[] = {\n`endif\n 1\n};\n", ); assert!(msg.contains("`endif"), "{msg}"); // Two splits under one outer region both recover, and the outer region // is still open between them. let f = parse_ok( "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ 1\n};\n`ifdef B\nint y[] = {\n`else\nconst int y[] = {\n`endif\n \ 2\n};\n`endif\nparameter int AFTER = 1;\n", ); let kinds = split_items(&f); assert_eq!(kinds.iter().filter(|k| k.starts_with("verbatim:")).count(), 2, "{kinds:?}"); assert_eq!(kinds[kinds.len() - 1], "param", "{kinds:?}"); } #[test] fn a_region_whose_arms_are_whole_items_still_parses_arm_by_arm() { let f = parse_ok("`ifdef A\nwire x;\n`else\nwire y;\n`endif\n"); assert_eq!( split_items(&f), ["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"] ); } // ------------------------------------------------------------------ // directive-in-statements: a region opened *inside* a construct // (`docs/features/directive-in-statements/README.md`) // ------------------------------------------------------------------ #[test] fn an_ifdef_splitting_an_assigns_rhs_is_captured_verbatim() { // hw/top_earlgrey/dv/env/chip_if.sv:1189-1194, the anchor shape: each // arm carries the construct's own `;`, so the block ends at the // `endif -- there is no `;` after it to stop at. let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n a.b.mr_rnd_ctr[3:0];\n`else\n a.b.rnd_ctr;\n`endif\n wire z;\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text); assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn an_ifdef_between_call_arguments_captures_the_statement_only() { // hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173. The region is // balanced inside the call's parens, so the statement ends at its own // `;` -- and the capture is the *statement*, not the enclosing // function, which is what running the recovery at statement level // buys. let src = "module m;\n initial begin\n a.configure(\n .size(2),\n`ifdef USE_DMI\n .reset(32'h10),\n`else\n .reset(32'h07),\n`endif\n .has_reset(1));\n b = 1;\n end\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; let StmtKind::Verbatim(raw) = &stmts[0].kind else { panic!("expected a verbatim stmt") }; assert!(raw.text.starts_with("a.configure("), "{:?}", raw.text); assert!(raw.text.ends_with(".has_reset(1));"), "{:?}", raw.text); assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }), "the next statement survived"); } #[test] fn an_ifdef_inside_an_instantiations_parameter_value_captures_only_that_value() { // hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621 -- a region // between the elements of a concatenation, three brackets deep inside // a parameter override. Until TODO §26 the whole instantiation became // opaque bytes, which cost it its edge, its lens and its port // references; now the override's value alone is the verbatim leaf. let src = "module m;\n padring #(\n .PadType({\n A,\n`ifdef ANALOGSIM\n \ '0,\n`else\n CC2,\n`endif\n B\n })\n ) u_padring (\n \ .clk(c)\n );\n wire z;\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, "padring"); assert_eq!(inst.instances[0].name, "u_padring"); let params = oks(inst.params.as_ref().expect("a parameter override list")); let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = ¶ms[0].expr else { panic!("expected a verbatim override value") }; assert!(raw.text.starts_with("{"), "{:?}", raw.text); assert!(raw.text.ends_with("}"), "{:?}", raw.text); // The connection list around it is structural again. let Connections::Named(conns) = &inst.instances[0].conns else { panic!("expected named connections") }; assert_eq!(oks(conns)[0].name, "clk"); assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn a_split_function_header_captures_through_endfunction() { // hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273. A `function`'s own // `;` closes its *header*: stopping there left `super.new(...)` behind // as an item and the file failed three lines into the body. The // closing keyword, and the `: label` it may carry, end the block. let src = "class c;\n function new(string name = \"\",\n`ifdef USE_DMI\n int unsigned n = 50,\n`else\n int unsigned n = 41,\n`endif\n int cov = 0);\n super.new(name, n, cov);\n endfunction : new\n int after;\nendclass\n"; let f = parse_ok(src); let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; let ItemKind::Verbatim(raw) = &c.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.starts_with("function new("), "{:?}", raw.text); assert!(raw.text.ends_with("endfunction : new"), "{:?}", raw.text); assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape() { // hw/top_earlgrey/dv/tb/tb.sv:113 (bucket 13): two instantiation heads // behind one `ifdef sharing a connection list. The region opened // *before* the item, so this is `at_split_conditional`'s shape -- what // this round changed is that `take_list_directives` no longer harvests // the `else as a list element and hides the seam. let src = "module m;\n`ifdef DISABLE_ROM\n chip #(\n .Scramble(1'b1)\n ) dut \ (\n`else\n chip dut (\n`endif\n .POR_N(p),\n .USB_P(u)\n );\n wire \ z;\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; assert!(matches!(m.items[0].kind, ItemKind::Directive(_)), "the `ifdef stayed an item"); let ItemKind::Verbatim(raw) = &m.items[1].kind else { panic!("expected a verbatim block") }; assert!(raw.text.starts_with("chip #("), "{:?}", raw.text); assert!(raw.text.ends_with(");"), "{:?}", raw.text); assert!(matches!(m.items[2].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn a_list_internal_region_is_still_harvested_as_list_elements() { // The other side of the `take_list_directives` guard: a region opened // *and* closed inside the connection list still conditions elements, // and the instantiation still parses as an instantiation. Written // inside an outer region, which is the state that arms the guard. let src = "module m;\n`ifdef OUTER\n chip dut (\n .A(a),\n`ifdef ANALOGSIM\n \ .CC1(c1),\n`else\n .CC1(d1),\n`endif\n .B(b)\n );\n`endif\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[1].kind else { panic!("expected an instantiation, got {:?}", split_items(&f)) }; assert_eq!(inst.instances[0].conn_directives.len(), 3, "`ifdef / `else / `endif harvested"); } #[test] fn an_opening_split_leaves_item_scope_nesting_alone() { // Every exit of the extent scan has conditional nesting back at zero, // so a captured block is conditional-balanced by construction. assert_eq!( open_conds_after( "module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n" ), 0 ); assert_eq!( open_conds_after( "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n a;\n`else\n \ b;\n`endif\nendmodule\n" ), 1, "the region around it is untouched" ); } #[test] fn the_opening_split_refuses_everything_it_does_not_model() { // Each of these reaches `at_opening_split` or `scan_opening_split_extent` // and is handed its parse error back. Verified against the release // binary on the real files as well; see the feature README. for (why, src) in [ ( "a non-conditional directive is not a split", "module m;\n assign y =\n`include \"x.vh\"\n a;\nendmodule\n", ), ("a stray closer opens nothing", "module m;\n assign y =\n`endif\n a;\nendmodule\n"), ("an unterminated region has no end", "module m;\n assign y =\n`ifdef A\n a;\n"), ("the construct never ends", "module m;\n assign y =\n`ifdef A\n a\n`endif\nendmodule\n"), ( "a plain syntax error near a directive stays one", "module m;\n`ifdef A\n assign y = ;\n`endif\nendmodule\n", ), ( "brackets that do not balance across the arms", "module m;\n assign y = (\n`ifdef A\n a;\n`else\n b);\n`endif\nendmodule\n", ), ( "a body-opening head whose end is not modeled", "module m;\n initial\n case (\n`ifdef A\n x\n`else\n \ y\n`endif\n )\n 1: a = 1;\n endcase\nendmodule\n", ), ] { let toks = tokenize(src).expect("lex error"); assert!(parse(toks, src).is_err(), "should still refuse: {why}"); } } #[test] fn a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call() { // The handshake `docs/features/formatter-bug-fixes/README.md` filed: // `take_before_open` drained the whole pending queue, so a comment // written after `if (` was printed between the condition's first // callee and its own `(`. Both of the call's comment slots must now // leave it queued for whoever owns the place it was written. let src = "module m;\n initial begin\n if (// why\n !en() || b\n ) \ begin\n x = 1;\n end\n end\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; let StmtKind::If { cond, then, .. } = &stmts[0].kind else { panic!("expected an if") }; // Neither `before_open` (the `(` of `en(`) nor `dangling` (the inside // of the empty `()`) may hold it. let ExprKind::Binary { lhs, .. } = &cond.kind else { panic!("expected a binary") }; let ExprKind::Unary { expr, .. } = &lhs.kind else { panic!("expected a unary") }; let ExprKind::Call { comments, .. } = &expr.kind else { panic!("expected a call") }; assert!(comments.before_open.is_empty(), "{:?}", comments.before_open); assert!(comments.dangling.is_empty(), "{:?}", comments.dangling); // It stays queued and reaches the body's leading comments, which is // where the formatter's `header_parens` takes it back from. assert_eq!(then.meta.leading.len(), 1, "{:?}", then.meta.leading); assert!(then.meta.leading[0].text.contains("why")); } #[test] fn a_comment_actually_written_before_a_bracket_is_still_taken() { // The other side of the same guard: `take_before_open` must keep // doing its job for the comments written in the gap it owns. let f = parse_ok("module m\n // why\n #(\n parameter int W = 1\n ) ();\nendmodule\n"); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; assert_eq!(m.param_comments.len(), 1, "{:?}", m.param_comments); assert!(m.param_comments[0].text.contains("why")); let f = parse_ok("module m;\n initial x = f\n // why\n ();\nendmodule\n"); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") }; let ExprKind::Call { comments, .. } = &rhs.kind else { panic!("expected a call") }; assert_eq!(comments.before_open.len(), 1, "{:?}", comments.before_open); } // ------------------------------------------------------------------ // QA (2026-08-29): adversarial coverage for directive-in-statements, // none of which turned up a bug -- pinned so a future refactor of // `scan_opening_split_extent`/`at_outer_arm_split` cannot silently // regress any of them. // ------------------------------------------------------------------ #[test] fn a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region() { // Three levels of conditional at once: an outer region already open // when the item starts, an opening split inside the assign's RHS, and // a *nested* `ifdef / `elsif / `else / `endif fully inside that // split's first arm. The nested region's own arms must not be // mistaken for the split's own `else / `endif, and `open_conds` must // land back at 1 (the outer region only) once the whole thing is // captured. let src = "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n`ifdef NESTED\n a\n\ `elsif NESTED2\n a2\n`else\n a3\n`endif\n + 1;\n`elsif A2\n q;\n\ `else\n b;\n`endif\n wire z;\nendmodule\n"; let f = parse_ok(src); assert_eq!(open_conds_after(src), 1, "the outer region is still open at eof"); // items[0] is the outer `ifdef OUTER` itself, a file-scope directive. let ItemKind::Module(m) = &f.items[1].kind else { panic!("expected a module") }; let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text); assert!(raw.text.contains("`ifdef NESTED"), "the nested region is inside the capture"); assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif() { // Only if/else was exercised elsewhere; a 4-arm chain must still end // at the one closing `endif, not at an intermediate `elsif. let src = "module m;\n assign y =\n`ifdef A\n a;\n`elsif B\n b;\n`elsif C\n \ c;\n`else\n d;\n`endif\n wire z;\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.contains("`elsif B") && raw.text.contains("`elsif C"), "{:?}", raw.text); assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn a_block_comment_naming_endif_does_not_fool_the_extent_scan() { // The extent scan walks tokens, not source text -- a comment is never // a `TokenKind::Directive`, so text that merely *mentions* `endif // inside a comment must not be mistaken for the real closer. let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n /* not a real `endif here */ \ a;\n`else\n b;\n`endif\n wire z;\nendmodule\n"; let f = parse_ok(src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.contains("not a real"), "{:?}", raw.text); assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); } #[test] fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() { // No sibling item follows the split in either container -- the scan // must stop at the split's own terminator and never wander into // `endmodule`/`endclass`. let module_src = "module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n"; let f = parse_ok(module_src); let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; assert_eq!(m.items.len(), 1, "{:?}", split_items(&f)); let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); let class_src = "class c;\n function new();\n`ifdef A\n super.new(1);\n`else\n \ super.new(2);\n`endif\n endfunction\nendclass\n"; // The `ifdef here opens at a *statement-list* boundary (the function // body's first statement), which is ordinary directive pass-through, // not an opening split -- included as the sibling case that must // stay a pass-through rather than being swept into this recovery. let f = parse_ok(class_src); let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; let ItemKind::Function(func) = &c.items[0].kind else { panic!("expected a function") }; assert!( matches!(func.stmts[0].kind, StmtKind::Directive(_)), "a directive starting a statement list is pass-through, not a split" ); } // ------------------------------------------------------------------ // Rival unit headers written across the arms of one region // (`docs/features/parser-skips/README.md`) // ------------------------------------------------------------------ /// The `jtag_if.sv` shape, in the four spellings that differ only in the /// header: `interface`/`module`, with and without `#( ... )`, with `()` and /// with a real port list. Every one of them is one verbatim item running /// from the first header to the unit's own closing keyword. #[test] fn rival_unit_headers_across_one_region_become_one_verbatim_item() { for (why, src, ends) in [ ( "interface, `#( ... ) ()` — hw/dv/sv/jtag_agent/jtag_if.sv:6", "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \ ();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \ ();\n`endif\n wire tck;\nendinterface\nparameter int AFTER = 1;\n", "endinterface", ), ( "interface, no parameter list", "`ifdef A\ninterface i ();\n`else\ninterface i ();\n`endif\n wire \ tck;\nendinterface\nparameter int AFTER = 1;\n", "endinterface", ), ( "module, a real port list", "`ifdef A\nmodule m (input a, output b);\n`else\nmodule m (input a, output \ b);\n`endif\n wire x;\nendmodule\nparameter int AFTER = 1;\n", "endmodule", ), ( "module, a closing label", "`ifdef A\nmodule m #(parameter int W = 1) ();\n`else\nmodule m #(parameter int W = \ 2) ();\n`endif\n wire x;\nendmodule : m\nparameter int AFTER = 1;\n", "endmodule : m", ), ] { let f = parse_ok(src); let kinds = split_items(&f); assert_eq!(kinds.len(), 3, "{why}: {kinds:?}"); assert!(kinds[0].starts_with("directive:`ifdef"), "{why}: {kinds:?}"); assert_eq!(kinds[2], "param", "{why}: the item after the unit was not swallowed"); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("{why}: expected verbatim") }; assert_eq!(raw.text, src[raw.span.as_range()], "{why}"); assert!(raw.text.ends_with(ends), "{why}: {:?}", raw.text); assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{why}: {:?}", raw.text); // The whole unit is inside the block, its body included. assert!(raw.text.contains("wire"), "{why}: {:?}", raw.text); assert_eq!(open_conds_after(src), 0, "{why}: the region's own `endif was accounted for"); } } #[test] fn rival_headers_produce_the_same_tree_in_both_modes() { let src = "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \ ();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \ ();\n`endif\n wire tck;\nendinterface\n"; let strict = parse_ok(src); let toks = tokenize(src).expect("lex error"); let (tolerant, diags) = parse_tolerant(toks, src); assert!(diags.is_empty(), "{diags:?}"); assert_eq!(split_items(&strict), split_items(&tolerant)); } #[test] fn comments_written_around_a_rival_header_are_kept() { // The real file writes a comment inside each arm and one before the // region; none of them may be dropped. let src = "// head\n`ifdef GATE_LEVEL // which\n // 24MHz for GLS\n interface jtag_if \ ();\n`else\n // 50MHz for DV\n interface jtag_if ();\n`endif\n // pins\n wire \ tck;\nendinterface // done\n"; let f = parse_ok(src); assert_eq!(texts(&f.items[0].meta.leading), ["// head"]); assert_eq!(f.items[0].meta.trailing.as_ref().expect("the `ifdef's comment").text, "// which"); // The capture starts at the item's *first token*, so the comment written // in front of the header is the item's own leading comment — the same // place every other split puts it — and the rest are inside the block. assert_eq!(texts(&f.items[1].meta.leading), ["// 24MHz for GLS"]); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; for c in ["// 50MHz for DV", "// pins"] { assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text); } assert!(!raw.text.contains("// done"), "the trailing comment was swallowed"); assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done"); } #[test] fn a_unit_nested_in_a_captured_body_does_not_end_the_scan_early() { // The extent scan counts units of the head's kind, so the *inner* // `endmodule` cannot be mistaken for the rival unit's own. let src = "`ifdef A\nmodule m ();\n`else\nmodule m ();\n`endif\n module inner ();\n \ endmodule\n wire x;\nendmodule\nparameter int AFTER = 1;\n"; let f = parse_ok(src); let kinds = split_items(&f); assert_eq!(kinds.len(), 3, "{kinds:?}"); let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; assert!(raw.text.contains("module inner"), "{:?}", raw.text); assert!(raw.text.ends_with("endmodule"), "{:?}", raw.text); assert_eq!(kinds[2], "param", "{kinds:?}"); } // -- the three negatives ---------------------------------------------- #[test] fn a_second_unit_in_an_arm_of_a_region_opened_inside_the_body_is_still_an_error() { // Two nested units, which is illegal: the region the `else belongs to // was opened *by the body*, not before the header, so the arm is not a // rival spelling of anything. let msg = parse_err( "`ifdef OUTER\nmodule m;\n`ifdef A\n wire a;\n`else\nmodule m;\n`endif\n wire \ b;\nendmodule\n", ); assert!(msg.contains("endmodule"), "{msg}"); // The same shape with no region open at all around the outer unit. let msg = parse_err( "module m;\n`ifdef A\n wire a;\n`else\nmodule m;\n wire \ b;\n`endif\nendmodule\n", ); assert!(msg.contains("endmodule"), "{msg}"); } #[test] fn a_different_name_after_the_else_is_not_a_rival_header() { let msg = parse_err( "`ifdef A\ninterface i ();\n`else\ninterface j ();\n`endif\n wire \ x;\nendinterface\n", ); assert!(msg.contains("endinterface"), "{msg}"); // Nor is a different keyword for the same name. let msg = parse_err( "`ifdef A\ninterface i ();\n`else\nmodule i ();\n`endif\n wire x;\nendinterface\n", ); assert!(msg.contains("endinterface"), "{msg}"); } #[test] fn a_region_closed_before_the_header_leaves_the_else_stray() { // The region opened at the top of the file is closed before the // interface begins, so the `else below closes nothing: broken input, // and the parse error stands. let msg = parse_err( "`ifdef A\n wire a;\n`endif\ninterface i ();\n`else\n interface i ();\n`endif\n wire \ x;\nendinterface\n", ); assert!(msg.contains("endinterface"), "{msg}"); // And a region closed *inside* the body before the `else: the header's // region is gone, so the live one is not the one it was written under. let msg = parse_err( "`ifdef OUTER\ninterface i ();\n`endif\n`ifdef B\n wire a;\n`else\n interface i \ ();\n`endif\nendinterface\n", ); assert!(msg.contains("endinterface"), "{msg}"); }