//! Classes and constraint bodies, in-class and out-of-block. use super::*; #[test] fn class_header_parts_are_kept_apart() { let f = parse_ok( "virtual class c #(parameter int W = 8) extends pkg::base #(.A(1), b) \ implements i, j;\nendclass : c\n", ); let c = class_of(&f); assert_eq!(words(&c.prefix), ["virtual"]); assert_eq!(c.name, "c"); assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1); let ext = c.extends.as_ref().expect("an extends clause"); assert_eq!(ext.name, "pkg::base"); let params = oks(ext.params.as_ref().expect("base parameter overrides")); assert_eq!(params.len(), 2); assert_eq!(params[0].name, "A"); // An ordered override has no name, only an expression. assert_eq!(params[1].name, ""); assert_eq!(c.implements.iter().map(|n| n.text.as_str()).collect::>(), ["i", "j"]); assert_eq!(c.end_label.as_deref(), Some("c")); } #[test] fn class_bodies_hold_ordinary_items() { let f = parse_ok( "class c;\n `M(x)\n`ifdef Y\n int a;\n`endif\n typedef int t;\n \ localparam int W = 1;\n import p::q;\n rand bit [3:0] r;\nendclass\n", ); let kinds: Vec<&str> = class_of(&f) .items .iter() .map(|i| match &i.kind { ItemKind::MacroItem(_) => "macro", ItemKind::Directive(_) => "directive", ItemKind::Typedef(_) => "typedef", ItemKind::ParamDecl(_) => "param", ItemKind::Import(_) => "import", ItemKind::DataDecl(_) => "data", _ => "other", }) .collect(); assert_eq!( kinds, ["macro", "directive", "data", "directive", "typedef", "param", "import", "data"] ); } #[test] fn member_qualifiers_land_on_the_construct_they_qualify() { let f = parse_ok( "class c;\n local rand int a;\n pure virtual function void g();\n \ extern task t(int x);\n protected virtual task automatic u();\n endtask\nendclass\n", ); let items = &class_of(&f).items; let ItemKind::DataDecl(d) = &items[0].kind else { panic!("expected a declaration") }; assert_eq!(words(&d.qualifiers), ["local", "rand"]); let ItemKind::Function(g) = &items[1].kind else { panic!("expected a function") }; assert_eq!(words(&g.prefix), ["pure", "virtual"]); assert!(g.is_prototype && g.stmts.is_empty()); let ItemKind::Task(t) = &items[2].kind else { panic!("expected a task") }; assert_eq!(words(&t.prefix), ["extern"]); assert!(t.is_prototype); let ItemKind::Task(u) = &items[3].kind else { panic!("expected a task") }; assert_eq!(words(&u.prefix), ["protected", "virtual"]); assert_eq!(words(&u.qualifiers), ["automatic"]); assert!(!u.is_prototype); } #[test] fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() { let f = parse_ok("function void my_class::configure(int x);\nendfunction\n"); let ItemKind::Function(g) = &f.items[0].kind else { panic!("expected a function") }; assert_eq!(scope_path(&g.scope), "my_class"); assert_eq!(g.name, "configure"); } // ------------------------------------------------------------------ // Constraint bodies (`docs/features/constraint-bodies/README.md`) // ------------------------------------------------------------------ fn constraint_of(f: &SourceFile) -> &ConstraintDecl { match &class_of(f).items[0].kind { ItemKind::Constraint(c) => c, other => panic!("expected a constraint, got {other:?}"), } } /// The items of `constraint c { ... }` written alone in a class. fn constraint_items(f: &SourceFile) -> &[ConstraintItem] { &constraint_of(f).body.as_ref().expect("a body").items } fn in_class(body: &str) -> String { format!("class k;\n constraint c {{\n{body}\n }}\nendclass\n") } #[test] fn a_constraint_keeps_its_name_and_its_items() { let src = "class k;\n constraint c_len {\n a == 0;\n b < 4;\n }\nendclass\n"; let f = parse_ok(src); let c = constraint_of(&f); assert_eq!(c.name.text, "c_len"); assert_eq!(&src[c.name.span.as_range()], "c_len", "the name span slices the name"); assert!(c.scope.is_empty()); assert!(!c.semi); let items = &c.body.as_ref().expect("a body").items; assert_eq!(items.len(), 2); assert!(matches!(items[0].kind, ConstraintItemKind::Expr { soft: false, .. })); } #[test] fn a_constraint_prototype_has_no_body() { let f = parse_ok("class k;\n extern constraint c;\nendclass\n"); let c = constraint_of(&f); assert_eq!(words(&c.qualifiers), ["extern"]); assert_eq!(c.name.text, "c"); assert!(c.body.is_none()); } #[test] fn a_pure_static_constraint_keeps_every_qualifier() { let f = parse_ok("class k;\n pure static constraint c;\nendclass\n"); assert_eq!(words(&constraint_of(&f).qualifiers), ["pure", "static"]); } #[test] fn a_stray_semicolon_after_the_block_is_recorded() { let f = parse_ok("class k;\n constraint c { a == 0; };\nendclass\n"); assert!(constraint_of(&f).semi); } #[test] fn a_soft_constraint_is_flagged_and_a_signal_named_soft_is_not() { let f = parse_ok(&in_class(" soft a == 0;")); assert!(matches!(constraint_items(&f)[0].kind, ConstraintItemKind::Expr { soft: true, .. })); // `soft` as an ordinary name: no term follows it, so it is the // expression's own head. Reserving the word would have broken this. let f = parse_ok(&in_class(" soft == 0;")); let ConstraintItemKind::Expr { soft, expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; assert!(!soft); assert!(matches!(expr.kind, ExprKind::Binary { .. })); } #[test] fn a_dist_set_keeps_both_weight_operators_apart() { let f = parse_ok(&in_class(" n dist { 0 := 5, [1:20] :/ 20, 99 };")); let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; let ExprKind::Dist { weights, .. } = &expr.kind else { panic!("expected a dist") }; assert_eq!(weights.len(), 3); assert_eq!(weights[0].op.as_deref(), Some(":=")); assert_eq!(weights[1].op.as_deref(), Some(":/")); assert!(matches!(weights[1].value.kind, ExprKind::ValueRange { .. })); // A weightless item is legal and keeps no operator. assert!(weights[2].op.is_none()); assert!(weights[2].weight.is_none()); } #[test] fn a_soft_dist_is_both() { let f = parse_ok(&in_class(" soft n dist { 0 :/ 5 };")); let ConstraintItemKind::Expr { soft, expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; assert!(soft); assert!(matches!(expr.kind, ExprKind::Dist { .. })); } #[test] fn a_spaced_dist_weight_operator_falls_back() { // `0 : / 5` is not `:/`: the two tokens are not adjacent, so the body // does not fit the grammar and the whole item rewinds. let f = parse_ok("class k;\n constraint c { n dist { 0 : / 5 }; }\nendclass\n"); assert!(matches!(class_of(&f).items[0].kind, ItemKind::Verbatim(_))); assert_eq!(f.constraint_fallbacks, 1); } #[test] fn an_inside_set_inside_a_constraint_is_an_ordinary_expression() { let f = parse_ok(&in_class(" n inside {[1:10], 20};")); let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; assert!(matches!(expr.kind, ExprKind::Inside { .. })); } #[test] fn an_implication_takes_a_set_and_a_bare_item_alike() { let f = parse_ok(&in_class(" a > 0 -> { b == 1; c == 2; }\n d -> e == 3;")); let items = constraint_items(&f); let ConstraintItemKind::Implication { set, .. } = &items[0].kind else { panic!("expected an implication") }; assert!(set.braced); assert_eq!(set.items.len(), 2); let ConstraintItemKind::Implication { set, .. } = &items[1].kind else { panic!("expected an implication") }; assert!(!set.braced, "an unbraced set holds exactly one item"); assert_eq!(set.items.len(), 1); } #[test] fn an_equivalence_operator_stays_inside_the_expression() { // `<->` is an operator, not an implication: its right-hand side can // never be a braced set, so it must not become one. let f = parse_ok(&in_class(" a <-> b;")); let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; let ExprKind::Binary { op, .. } = &expr.kind else { panic!("expected a binary") }; assert_eq!(op, "<->"); } #[test] fn a_constraint_if_chains_through_else_if() { let f = parse_ok(&in_class( " if (a == 0) b == 1;\n else if (a == 1) { b == 2; }\n else b == 3;", )); let ConstraintItemKind::If { els, .. } = &constraint_items(&f)[0].kind else { panic!("expected an if") }; let els = els.as_ref().expect("an else"); assert!(!els.braced); assert!(matches!(els.items[0].kind, ConstraintItemKind::If { .. }), "the else-if chain"); } #[test] fn a_constraint_foreach_keeps_its_skipped_dimensions() { let f = parse_ok(&in_class(" foreach (arr[, j]) { arr[j] < 4; }")); let ConstraintItemKind::Foreach { vars, set, .. } = &constraint_items(&f)[0].kind else { panic!("expected a foreach") }; assert_eq!(vars.len(), 2); assert!(vars[0].name.text.is_empty(), "a skipped dimension is an empty name"); assert_eq!(vars[1].name.text, "j"); assert!(set.braced); } #[test] fn a_solve_before_keeps_both_operand_lists_in_order() { let f = parse_ok(&in_class(" solve a, b before c, d;")); let ConstraintItemKind::SolveBefore { solve, before, .. } = &constraint_items(&f)[0].kind else { panic!("expected a solve/before") }; assert_eq!(solve.len(), 2); assert_eq!(before.len(), 2); // A signal named `solve` compared to something is not a solve item. let f = parse_ok(&in_class(" solve == 1;")); assert!(matches!(constraint_items(&f)[0].kind, ConstraintItemKind::Expr { .. })); } #[test] fn unique_and_disable_soft_are_their_own_items() { let f = parse_ok(&in_class(" unique {a, b};\n disable soft c;")); let items = constraint_items(&f); let ConstraintItemKind::Unique { items: set, .. } = &items[0].kind else { panic!("expected unique") }; assert_eq!(set.len(), 2); assert!(matches!(items[1].kind, ConstraintItemKind::DisableSoft { .. })); } #[test] fn a_null_constraint_item_is_its_semicolon() { let f = parse_ok(&in_class(" a == 0;\n ;")); assert!(matches!(constraint_items(&f)[1].kind, ConstraintItemKind::Empty)); } #[test] fn a_directive_inside_a_constraint_body_is_a_directive_item() { let f = parse_ok(&in_class(" `ifdef FOO\n a == 0;\n `endif")); let items = constraint_items(&f); assert_eq!(items.len(), 3); assert!(matches!(items[0].kind, ConstraintItemKind::Directive(_))); assert!(matches!(items[1].kind, ConstraintItemKind::Expr { .. })); assert!(matches!(items[2].kind, ConstraintItemKind::Directive(_))); assert_eq!(f.constraint_fallbacks, 0); } #[test] fn comments_survive_every_slot_of_a_constraint_body() { let src = "class k;\n // head\n constraint c { // open\n // before\n \ a == 0; // after\n // dangling\n }\nendclass\n"; let f = parse_ok(src); let item = &class_of(&f).items[0]; assert_eq!(item.meta.leading[0].text, "// head"); let set = constraint_of(&f).body.as_ref().expect("a body"); // `// open` and `// before` both lead the one item; `// after` // trails it and `// dangling` sits before the `}`. let leading: Vec<&str> = set.items[0].meta.leading.iter().map(|c| &*c.text).collect(); assert_eq!(leading, ["// open", "// before"]); assert_eq!(set.items[0].meta.trailing.as_ref().expect("trailing").text, "// after"); assert_eq!(set.dangling.len(), 1); assert_eq!(set.dangling[0].text, "// dangling"); } #[test] fn an_unrecognised_constraint_body_rewinds_to_exactly_the_old_capture() { // A macro standing where a constraint item belongs — the macro // supplies the `;`, or half the constraint — is the shape the // grammar cannot know, and the one real DV code writes. The rewind // must produce byte-for-byte what `parse_constraint` produced before // there was a constraint grammar at all: the whole item, its `col`, // and its own source slice, double spaces and all. let src = "class k;\n constraint c {\n `MY_HALF\n b == 1;\n }\nendclass\n"; let f = parse_ok(src); let ItemKind::Verbatim(raw) = &class_of(&f).items[0].kind else { panic!("expected the verbatim fallback, got {:?}", class_of(&f).items[0].kind) }; assert_eq!(raw.text, "constraint c {\n `MY_HALF\n b == 1;\n }"); assert_eq!(raw.text, src[raw.span.as_range()], "the capture is the source bytes"); assert_eq!(raw.col, 3, "the column the re-indent contract needs"); assert_eq!(f.constraint_fallbacks, 1); } #[test] fn a_fallback_keeps_the_comments_written_around_it() { // The speculative parse harvests comments into metas it then throws // away; the rewind must put them back, or hard invariant #3 breaks. let f = parse_ok( "class k;\n // head\n constraint c { `MY_HALF b == 1; } // tail\n int b;\nendclass\n", ); let item = &class_of(&f).items[0]; assert!(matches!(item.kind, ItemKind::Verbatim(_))); assert_eq!(item.meta.leading[0].text, "// head"); assert_eq!(item.meta.trailing.as_ref().expect("trailing").text, "// tail"); } // ------------------------------------------------------------------ // Comment slots (the 2026-09-02 rework) // // Every keyword and punctuation position this round introduced must own // the comments written in front of it. A comment the AST loses is a // comment the formatter cannot print, and `format_source`'s own token // check then refuses the file — hard invariant #3 by way of #1. These // assert the *text is in the node*, which the `.cases` table then proves // is printed back in place. // ------------------------------------------------------------------ /// Every comment text the constraint at the head of `src`'s class holds, /// in the slots this round owns — not the item metas, which the ordinary /// leading/trailing plumbing already covered. fn slot_comments(c: &ConstraintDecl) -> Vec { let mut out = Vec::new(); let mut push = |cs: &[Comment]| out.extend(cs.iter().map(|c| c.text.clone())); push(&c.before_name); push(&c.after_name); push(&c.before_semi); let Some(set) = &c.body else { return out }; for item in &set.items { match &item.kind { ConstraintItemKind::Expr { after_soft, .. } => push(after_soft), ConstraintItemKind::If { comments, after_else, .. } => { push(&comments.after_kw); push(&comments.after_open); push(&comments.before_close); push(&comments.before_body); push(after_else); } ConstraintItemKind::Foreach { comments, .. } => { push(&comments.after_kw); push(&comments.after_open); push(&comments.before_close); push(&comments.before_body); } ConstraintItemKind::SolveBefore { before_comments, .. } => push(before_comments), ConstraintItemKind::Unique { comments, .. } => push(comments), ConstraintItemKind::DisableSoft { comments, .. } => { push(&comments.before); push(&comments.after); } _ => {} } push(&item.before_semi); } out } #[test] fn the_header_keeps_the_comments_written_around_its_name() { let f = parse_ok("class k;\n constraint /*a*/ c /*b*/ {\n x < 1;\n } /*c*/ ;\nendclass\n"); let c = constraint_of(&f); assert_eq!(c.before_name.len(), 1); assert_eq!(c.before_name[0].text, "/*a*/"); assert_eq!(c.after_name[0].text, "/*b*/"); assert_eq!(c.before_semi[0].text, "/*c*/"); assert!(c.semi); } #[test] fn a_prototype_keeps_the_comment_written_before_its_semicolon() { let f = parse_ok("class k;\n extern constraint /*a*/ c /*b*/ ;\nendclass\n"); let c = constraint_of(&f); assert_eq!(c.before_name[0].text, "/*a*/"); assert_eq!(c.after_name[0].text, "/*b*/"); } #[test] fn every_constraint_item_slot_keeps_its_comment() { let f = parse_ok(&in_class( " soft /*soft*/ n dist /*dist2*/ { 0 /*w1*/ := /*w2*/ 5 } /*semi1*/ ;\n\ \x20 if /*if1*/ ( /*if2*/ m /*if3*/ ) /*if4*/ { a == 1; }\n\ \x20 else /*else2*/ { a == 2; }\n\ \x20 foreach /*fe1*/ ( /*fe2*/ q[i] /*fe3*/ ) /*fe4*/ { q[i] < 2; }\n\ \x20 solve a /*solve*/ before b /*semi2*/ ;\n\ \x20 unique /*uniq*/ {a, b} /*semi3*/ ;\n\ \x20 disable /*ds1*/ soft /*ds2*/ n /*semi4*/ ;", )); let got = slot_comments(constraint_of(&f)); assert_eq!( got, vec![ "/*soft*/", "/*semi1*/", "/*if1*/", "/*if2*/", "/*if3*/", "/*if4*/", "/*else2*/", "/*fe1*/", "/*fe2*/", "/*fe3*/", "/*fe4*/", "/*solve*/", "/*semi2*/", "/*uniq*/", "/*semi3*/", "/*ds1*/", "/*ds2*/", "/*semi4*/", ], "a slot lost its comment" ); } #[test] fn a_dist_keeps_the_comments_around_its_word_and_its_weight_operators() { let f = parse_ok(&in_class(" n /*before*/ dist /*after*/ { 0 /*b1*/ := /*a1*/ 5, 9 };")); let ConstraintItemKind::Expr { expr, .. } = &constraint_items(&f)[0].kind else { panic!("expected an expression item") }; let ExprKind::Dist { comments, weights, .. } = &expr.kind else { panic!("expected a dist") }; assert_eq!(comments.before[0].text, "/*before*/"); assert_eq!(comments.after[0].text, "/*after*/"); assert_eq!(weights[0].op_comments.before[0].text, "/*b1*/"); assert_eq!(weights[0].op_comments.after[0].text, "/*a1*/"); // A weightless item holds no operator and therefore no operator // comments — the empty case must stay empty, not inherit the last. assert!(weights[1].op_comments.before.is_empty()); } #[test] fn the_gap_before_a_semicolon_that_was_not_written_belongs_to_what_follows() { // `takes_semi` is false for an implication, so nothing may claim the // comment in front of the next item; it must lead that item instead. let f = parse_ok(&in_class(" m -> { a == 1; }\n /*next*/\n b == 2;")); let items = constraint_items(&f); assert!(matches!(items[0].kind, ConstraintItemKind::Implication { .. })); assert!(items[0].before_semi.is_empty()); assert_eq!(items[1].meta.leading[0].text, "/*next*/"); } #[test] fn an_else_on_its_own_line_leaves_its_comment_to_the_body_item() { // The gap after `else` is only this item's when the set opens with a // `{` or a chained `if`; otherwise the source's own line break has // already made it the body's leading comment. let f = parse_ok(&in_class(" if (m) a == 1;\n else\n // why\n a == 2;")); let ConstraintItemKind::If { after_else, els, .. } = &constraint_items(&f)[0].kind else { panic!("expected an if") }; assert!(after_else.is_empty()); let els = els.as_ref().expect("an else"); assert_eq!(els.items[0].meta.leading[0].text, "// why"); } // ------------------------------------------------------------------ // Out-of-block constraints // (`docs/features/out-of-class-constraints/README.md`) // ------------------------------------------------------------------ fn file_constraint(f: &SourceFile) -> &ConstraintDecl { match &f.items[0].kind { ItemKind::Constraint(c) => c, other => panic!("expected a constraint, got {other:?}"), } } #[test] fn an_out_of_block_constraint_keeps_its_scope_apart_from_its_name() { let src = "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}\n"; let f = parse_ok(src); let c = file_constraint(&f); assert_eq!(scope_path(&c.scope), "my_item"); assert_eq!(c.name.text, "delay_c"); assert_eq!(&src[c.name.span.as_range()], "delay_c"); } #[test] fn an_out_of_block_constraint_scope_may_be_a_chain() { // `pkg::cls::name` — the same chain `parse_method_name` accepts for an // out-of-body method. let f = parse_ok("constraint pkg::cls::deep_c { x < 4; }\n"); assert_eq!(scope_path(&file_constraint(&f).scope), "pkg::cls"); } #[test] fn an_out_of_block_constraint_lives_in_a_package_too() { let f = parse_ok("package p;\n constraint c::x { a > 0; }\nendpackage\n"); let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected a package") }; assert!(matches!(items[0].kind, ItemKind::Constraint(_)), "{:?}", items[0].kind); } #[test] fn an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments() { // `constraint C::c { ... };` — the stray `;` belongs to the block, and // a comment written past the block must stay outside it. let f = parse_ok("// head\nconstraint c::x { a == 0; }; // tail\nint b;\n"); assert!(file_constraint(&f).semi); assert_eq!(f.items[0].meta.leading[0].text, "// head"); assert_eq!(f.items[0].meta.trailing.as_ref().expect("trailing comment").text, "// tail"); } #[test] fn an_in_class_constraint_still_rejects_a_scope_free_syntax_error() { // The widened name must not swallow a genuinely broken header: the // `::` path only accepts an identifier after the separator. The // fallback re-runs the same header parse, so the message is the one // it always was. assert_eq!(parse_err("constraint c:: { a == 0; }\n"), "expected identifier (found \"{\")"); assert_eq!(parse_err("constraint 4::x { a == 0; }\n"), "expected identifier (found \"4\")"); } #[test] fn interface_class_is_not_an_interface() { // IEEE 1800-2017 §8.26: a different construct — and since // `vendor-formal-grammar` a supported one. It is a *class*: the word // rides in the prefix, the closer is `endclass`, and nothing reads it // as an `interface ... endinterface`. let f = parse_ok("interface class ic;\n pure virtual function void f();\nendclass\n"); let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; assert_eq!(words(&c.prefix), ["interface"]); assert!(c.is_interface_class()); assert_eq!(c.name, "ic"); assert_eq!(c.items.len(), 1, "the pure virtual prototype is an ordinary class item"); // And an ordinary interface is still an interface. let f = parse_ok("interface i;\nendinterface\n"); assert!(matches!(&f.items[0].kind, ItemKind::Module(m) if m.kw == "interface")); } #[test] fn an_interface_class_may_extend_another_one() { // IEEE 1800-2017 §8.26.4: interface classes inherit with `extends`, // and a plain class promises them with `implements`. let f = parse_ok("interface class b extends a;\nendclass\n"); let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; assert!(c.is_interface_class()); assert_eq!(c.extends.as_ref().map(|e| e.name.as_str()), Some("a")); } #[test] fn a_randomize_with_block_is_parsed_and_the_call_is_not() { let f = parse_ok( "module m;\n initial begin\n x = std::randomize(y) with {\n y > 1;\n };\n end\nendmodule\n", ); let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { panic!("expected an assignment") }; let ExprKind::WithConstraint { base, block, .. } = &rhs.kind else { panic!("expected a with-constraint, got {:?}", rhs.kind) }; let ConstraintBody::Items(set) = &**block else { panic!("expected a parsed body") }; assert!(set.braced); assert_eq!(set.items.len(), 1); assert!(matches!(base.kind, ExprKind::Call { .. }), "the call is still structural"); assert_eq!(f.constraint_fallbacks, 0); } #[test] fn an_unrecognised_randomize_with_block_keeps_the_old_verbatim_capture() { let src = "module m;\n initial begin\n x = req.randomize() with {\n `MY_HALF\n a == 2;\n };\n end\nendmodule\n"; let f = parse_ok(src); let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { panic!("expected an assignment") }; let ExprKind::WithConstraint { block, .. } = &rhs.kind else { panic!("expected a with-constraint") }; let ConstraintBody::Verbatim(raw) = &**block else { panic!("expected the fallback") }; // The `with` keyword is outside the capture; the braces are inside. assert_eq!(raw.text, "{\n `MY_HALF\n a == 2;\n }"); assert_eq!(raw.text, src[raw.span.as_range()]); assert_eq!(f.constraint_fallbacks, 1); }