From a07dc703f90a9e4e70f5bdea9db3b52a632ad3cf Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:28:29 +0000 Subject: [PATCH 1/3] test(xezim): update xezim digest to 8082de3 --- flake.lock | 8 ++++---- flake.nix | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/flake.lock b/flake.lock index 6e915e2ba17..11c01378c72 100644 --- a/flake.lock +++ b/flake.lock @@ -68,17 +68,17 @@ "xezim": { "flake": false, "locked": { - "lastModified": 1793073936, - "narHash": "sha256-IxmhXhBMFZKuloRf3uB99p19pa2TBdnPCsbXLlzM8bs=", + "lastModified": 1793078782, + "narHash": "sha256-S19+CyN8gKzUt7F4Hpz4yTNjFXxnJYHIhVeRLdPUr/k=", "owner": "aionhw", "repo": "xezim", - "rev": "a059e87dc05dd85dc7b38a07f0091f20a6964ba2", + "rev": "8082de3cd5bc717e96145699c787a247fd6cf2e3", "type": "github" }, "original": { "owner": "aionhw", "repo": "xezim", - "rev": "a059e87dc05dd85dc7b38a07f0091f20a6964ba2", + "rev": "8082de3cd5bc717e96145699c787a247fd6cf2e3", "type": "github" } } diff --git a/flake.nix b/flake.nix index fddd8bf85de..0106c1de973 100644 --- a/flake.nix +++ b/flake.nix @@ -15,7 +15,7 @@ # The xezim reference simulator for the shared test suite, pinned by # revision so that Renovate proposes updates. xezim = { - url = "github:aionhw/xezim/a059e87dc05dd85dc7b38a07f0091f20a6964ba2"; + url = "github:aionhw/xezim/8082de3cd5bc717e96145699c787a247fd6cf2e3"; flake = false; }; }; From 909723e91bd4a755ffaba75a2ba01d2d1e975f73 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 15:00:55 +0900 Subject: [PATCH 2/3] feat(sv): support scalar set membership constraints Bind inside values and inclusive bounded ranges to solver relations, preserving signed and mixed-width comparison contexts. Negation excludes a set and reversed ranges are empty. Balance membership alternatives to avoid linear expression depth. This extends the existing seeded scalar solver; it does not add a uniform sampling guarantee. Array sets, X/Z wildcard items and unbounded ranges remain rejected. IEEE 1800-2023 11.4.13 and 18.5.3 define membership semantics. Validation: 30 constrained-randomization backend tests, four analyzer randomization regressions, analyzer all-target Clippy and formatting pass. Verilator passes both new shared cases. Icarus rejects constraint syntax; the observed compile limitation is recorded in the reviewed exclusions and retained evidence. Membership sizing is determined across all set items and range endpoints before arithmetic. Analysis charges an expansion budget before copying predicates, rejecting deeply nested expansions before solver allocation. Added check-only overflow/range regressions and a 25-level nesting diagnostic test; 30 constrained backend tests, three focused analyzer tests, Verilator and analyzer Clippy pass. Icarus remains excluded for its recorded unsupported constraint syntax. Change-Id: Icdebb01d187fe5c73787b941bbef72d6bb0ef033 --- .../src/ast/classes/constraints.rs | 116 +++++++++++++++++- crates/celox-sv-analyzer/src/tests.rs | 27 +++- .../celox-test-suite/src/sv/cases/class.vtest | 73 +++++++++++ .../repros/sv_inside_constraints.json | 16 +++ .../verification/sv/icarus/class.json | 57 ++++++++- .../verification/sv/limitations.json | 7 +- .../tests/frontends/systemverilog/class.rs | 5 + docs/guide/systemverilog-reference.md | 9 +- 8 files changed, 301 insertions(+), 9 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_inside_constraints.json diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs index 3cb2e87ef24..d3d7d3296de 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -3,16 +3,59 @@ use super::*; use celox_heap::randomization::{Expr as ConstraintExpr, Field, Program}; use celox_sv_syntax::{ExprId, ExprKind}; +#[derive(Clone)] struct Typed { kind: Kind, width: u32, signed: bool, } +#[derive(Clone)] enum Kind { Leaf(ConstraintExpr), + Context(Box), Unary(String, Box), Binary(String, Box, Box), } +fn relation(op: &str, left: Typed, right: Typed) -> Typed { + Typed { + kind: Kind::Binary(op.into(), Box::new(left), Box::new(right)), + width: 1, + signed: false, + } +} + +// Charge copies before allocating them: source nesting alone does not bound +// the expanded tree of nested membership predicates. +fn bounded_clone(value: &Typed, budget: &std::cell::Cell) -> Result { + let mut pending = vec![value]; + while let Some(value) = pending.pop() { + charge(budget)?; + match &value.kind { + Kind::Leaf(_) => {} + Kind::Context(child) | Kind::Unary(_, child) => pending.push(child), + Kind::Binary(_, a, b) => pending.extend([a.as_ref(), b.as_ref()]), + } + } + Ok(value.clone()) +} + +fn charge(budget: &std::cell::Cell) -> Result<(), String> { + let remaining = budget + .get() + .checked_sub(1) + .ok_or("constraint expression expansion limit")?; + budget.set(remaining); + Ok(()) +} + +fn sized(value: Typed, width: u32, signed: bool) -> Typed { + Typed { + kind: Kind::Context(Box::new(value)), + width, + signed, + } +} + fn comparison(op: &str) -> bool { matches!(op, "==" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||") } @@ -24,6 +67,7 @@ fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr { let (width, signed) = context.unwrap_or((value.width, value.signed)); let (expr, result_width) = match value.kind { Kind::Leaf(expr) => (expr, value.width), + Kind::Context(child) => (emit(*child, Some((value.width, value.signed))), value.width), Kind::Unary(op, child) => { let logical = op == "!"; ( @@ -78,11 +122,13 @@ pub(super) fn bind( properties: &[Property], env: &HashMap, depth: usize, + budget: &std::cell::Cell, ) -> Result { if depth > 64 { return Err("constraint expression nesting limit".into()); } - let recurse = |id| expression(id, tree, properties, env, depth + 1); + charge(budget)?; + let recurse = |id| expression(id, tree, properties, env, depth + 1, budget); let native = tree.declarations(); Ok(match &native.expression(id).kind { ExprKind::Group(id) => return recurse(*id), @@ -138,6 +184,71 @@ pub(super) fn bind( kind: Kind::Unary(operator.clone(), Box::new(value)), } } + ExprKind::Binary { + left, + operator, + right, + } if operator == "inside" => { + let value = recurse(*left)?; + let ExprKind::Set(items) = &native.expression(*right).kind else { + return Err("constraint inside set".into()); + }; + // Determine the context across every member and range endpoint + // before expanding comparisons, so arithmetic cannot truncate + // differently depending on which alternative is being tested. + let mut members = Vec::new(); + let mut width = value.width; + let mut signed = value.signed; + for item in items { + use celox_sv_syntax::DimensionKind; + let (low, high) = match item.kind { + DimensionKind::Index(id) => (recurse(id)?, None), + DimensionKind::Range { left, right } => { + (recurse(left)?, Some(recurse(right)?)) + } + _ => return Err("constraint inside range".into()), + }; + for operand in std::iter::once(&low).chain(high.iter()) { + width = width.max(operand.width); + signed &= operand.signed; + } + members.push((low, high)); + } + let value = sized(value, width, signed); + let mut alternatives = Vec::new(); + for (low, high) in members { + charge(budget)?; + let left = bounded_clone(&value, budget)?; + let low = sized(low, width, signed); + let predicate = if let Some(high) = high { + relation( + "&&", + relation(">=", left, low), + relation( + "<=", + bounded_clone(&value, budget)?, + sized(high, width, signed), + ), + ) + } else { + relation("==", left, low) + }; + alternatives.push(predicate); + } + // A balanced OR tree bounds recursion for large membership sets. + while alternatives.len() > 1 { + let mut next = Vec::new(); + let mut items = alternatives.into_iter(); + while let Some(a) = items.next() { + next.push(match items.next() { + Some(b) => relation("||", a, b), + None => a, + }); + } + alternatives = next; + } + alternatives.pop().ok_or("empty constraint inside set")? + } ExprKind::Binary { left, operator, @@ -175,7 +286,8 @@ pub(super) fn bind( _ => return Err("unsupported scalar constraint expression".into()), }) } - expression(id, tree, properties, env, 0).map(|value| emit(value, None)) + expression(id, tree, properties, env, 0, &std::cell::Cell::new(16_384)) + .map(|value| emit(value, None)) } impl Class { diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 9d1c6193ed2..bb1d1c4979c 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6603,7 +6603,7 @@ fn class_randomize_rejects_unsupported_semantics() { "constraints", ), ( - "rand int x; constraint c { x inside {[1:3]}; }", + "rand int x; constraint c { x inside {[1:$]}; }", "c.randomize()", "constraint", ), @@ -7345,3 +7345,28 @@ fn final_procedures_only_follow_defaults_for_omitted_arguments() { } } } + +#[test] +fn class_randomize_bounds_nested_membership_expansion() { + for levels in [4, 25] { + let mut expr = "x".to_owned(); + for _ in 0..levels { + expr = format!("({expr}) inside {{0, 1}}"); + } + let source = format!( + "module Top; class C; rand bit x; constraint c {{ {expr}; }} endclass C c; initial begin c = new; c.randomize(); end endmodule" + ); + let result = analyze_source(&source, Path::new("nested_membership.sv")); + if levels == 4 { + result.expect("small nested membership must remain supported"); + } else { + let error = result + .expect_err("expanded membership must be bounded") + .to_string(); + assert!( + error.contains("constraint expression expansion limit"), + "{error}" + ); + } + } +} diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index cd39b6a0903..7af02d12dea 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -2002,3 +2002,76 @@ module Top(output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inside + (source "constraint_inside.sv" #" +module Top(output bit done); + class Packet; + rand int x, lo, hi; + constraint bounds { lo inside {-3, -2}; hi inside {2, 3}; + x inside {[lo:hi], 9}; !(x inside {0, 9}); } + endclass + class Empty; + rand int x; + constraint c { x inside {[3:-3]}; } + endclass + Packet p; + Empty e; + initial begin + e = new; e.x = 42; + if (e.randomize() || e.x != 42) $fatal(1, "empty range changed fields"); + p = new; + repeat (12) begin + if (!p.randomize()) $fatal(1, "membership unsat"); + if (p.lo < -3 || p.lo > -2 || p.hi < 2 || p.hi > 3 || + p.x < p.lo || p.x > p.hi || p.x == 0) $fatal(1, "membership"); + end + p.lo = 3; p.hi = -3; + if (p.randomize(x)) $fatal(1, "reversed range must be empty"); + p.lo = -2; p.hi = 2; p.x = -1; + if (!p.randomize(null)) $fatal(1, "negative check-only member"); + p.x = p.lo; + if (!p.randomize(null)) $fatal(1, "low endpoint excluded"); + p.x = p.hi; + if (!p.randomize(null)) $fatal(1, "high endpoint excluded"); + p.x = 0; + if (p.randomize(null)) $fatal(1, "excluded check-only member"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inside_widths + (source "constraint_inside_widths.sv" #" +module Top(output bit done); + class Packet; + rand bit signed [7:0] x; + rand bit [15:0] y; + constraint c { x inside {-2, -1}; y inside {x}; } + endclass + class WideSet; + bit [3:0] a, b; + constraint c { !((a + b) inside {4'd0, 8'd17}); } + endclass + class WideRange; + bit [3:0] a, b; + constraint c { (a + b) inside {[4'd1:8'd16]}; } + endclass + Packet p; + WideSet s; + WideRange r; + initial begin + p = new; + if (!p.randomize()) $fatal(1, "mixed width membership"); + if (p.x != -2 && p.x != -1) $fatal(1, "signed membership"); + if (p.y != 254 && p.y != 255) $fatal(1, "unsigned comparison context"); + s = new; s.a = 15; s.b = 1; + if (!s.randomize(null)) $fatal(1, "membership-wide sum width"); + r = new; r.a = 15; r.b = 1; + if (!r.randomize(null)) $fatal(1, "range endpoint width"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_inside_constraints.json b/crates/celox-test-suite/verification/repros/sv_inside_constraints.json new file mode 100644 index 00000000000..caa16930ee9 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_inside_constraints.json @@ -0,0 +1,16 @@ +{ + "observations": [ + { + "tool": "icarus", + "case": "class::constrained_randomize_inside", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inside/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:5: sorry: Constraint declarations not supported.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:10: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside/source_0.sv:10: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "case": "class::constrained_randomize_inside_widths", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inside_widths/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside_widths/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inside_widths/source_0.sv:6: sorry: Constraint declarations not supported.\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 6aee7194ef9..24e8b0a50a1 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -192,7 +192,8 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -215,7 +216,56 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_inside", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_inside_widths", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -238,7 +288,8 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 0ddd3479670..fff5c99ff3a 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2588,13 +2588,16 @@ "upstream": [], "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json" ], "cases": { "icarus": [ "class::constrained_randomize_scalar", "class::constrained_randomize_width_and_inheritance", - "class::constrained_randomize_hooks" + "class::constrained_randomize_hooks", + "class::constrained_randomize_inside", + "class::constrained_randomize_inside_widths" ] } }, diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 22d5d034586..9f568f5a93e 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -932,3 +932,8 @@ sv_backends! { sv_backends! { fn constrained_randomize_hooks(sim) { @case "class::constrained_randomize_hooks"; } } + +sv_backends! { + fn constrained_randomize_inside(sim) { @case "class::constrained_randomize_inside"; } + fn constrained_randomize_inside_widths(sim) { @case "class::constrained_randomize_inside_widths"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6cb69aeb320..f9aaeaa84c1 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -222,7 +222,14 @@ properties and skips the post-hook (18.6.3). Resource exhaustion is a runtime er This initial seeded-search policy does not guarantee a uniform distribution; distribution improvements are tracked in [#2187](https://github.com/celox-sim/celox/issues/2187). -Constrained enums and `randc`, `inside`, conditional/foreach/soft constraints, +Set membership (`inside`) supports scalar two-state values and inclusive bounded +ranges, including expressions of other properties. Reversed ranges are empty; +negation excludes the set. All operands share the membership-wide width and +signedness before arithmetic evaluation. Excessive predicate expansion is rejected +during analysis, including repeated nested membership. Array sets, X/Z wildcard items and `$` bounds are not +yet supported. Membership uses the same seeded solver policy described above. + +Constrained enums and `randc`, conditional/foreach/soft constraints, `dist`, `solve before`, constraint modes, external/static blocks, typed parameters in constraints, and inline `with` remain unsupported. Larger unconstrained `randc` domains, static random properties and random array/object/string properties also From 32021e52a82bf0318b3f0afb9e81e40d25b33013 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 15:05:44 +0900 Subject: [PATCH 3/3] feat(sv): solve conditional class constraints bidirectionally Retain if/else and implication constraint sets as guarded Boolean relations. Nested sets, dangling else association and implication chains preserve their logical meaning; the condition participates in solving rather than selecting a procedural branch. Keep parsing on the existing explicit worklist and share constraint-block parsing for inline calls. IEEE 1800-2023 18.5.5 and 18.5.6. Validation: 40 constrained-randomization backend tests, 132 syntax tests, four analyzer randomization regressions, affected all-target Clippy and formatting pass. Both new cases pass Verilator; Icarus rejects constraint syntax. The final nested-guard fixture uses a one-bit constant to avoid Verilator 5.052 generating an ill-typed SMT Boolean conversion for if (0), and also passes the interpreter. Change-Id: I726d3ce3d92d511536ead0e18509261ce5cd2d20 --- crates/celox-sv-analyzer/src/tests.rs | 10 -- .../celox-sv-syntax/src/parser/constraints.rs | 92 +++++++++++++++---- crates/celox-sv-syntax/src/parser/tests.rs | 10 +- .../celox-test-suite/src/sv/cases/class.vtest | 53 +++++++++++ .../repros/sv_conditional_constraints.json | 16 ++++ .../verification/sv/icarus/class.json | 65 ++++++++++++- .../verification/sv/limitations.json | 7 +- .../tests/frontends/systemverilog/class.rs | 5 + docs/guide/systemverilog-reference.md | 6 +- 9 files changed, 228 insertions(+), 36 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_conditional_constraints.json diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index bb1d1c4979c..365d42c7165 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6587,11 +6587,6 @@ fn explicit_output_data_types_default_to_variables() { #[test] fn class_randomize_rejects_unsupported_semantics() { for (members, call, expected) in [ - ( - "rand int x; constraint c { if (x) x == 1; }", - "c.randomize()", - "constraints", - ), ( "rand int x; constraint c { soft x == 1; }", "c.randomize()", @@ -6607,11 +6602,6 @@ fn class_randomize_rejects_unsupported_semantics() { "c.randomize()", "constraint", ), - ( - "rand int x; constraint c { (x == 1) -> (x < 3); }", - "c.randomize()", - "constraints", - ), ( "rand int x; constraint c { (x == 1) <-> (x < 3); }", "c.randomize()", diff --git a/crates/celox-sv-syntax/src/parser/constraints.rs b/crates/celox-sv-syntax/src/parser/constraints.rs index 2469d9465da..778a1b98b14 100644 --- a/crates/celox-sv-syntax/src/parser/constraints.rs +++ b/crates/celox-sv-syntax/src/parser/constraints.rs @@ -6,7 +6,13 @@ enum Job { Block(bool), Expression, Set, - Else, + Guard { + condition: ExprId, + first: usize, + start: usize, + negate: bool, + has_else: bool, + }, } impl Parser<'_> { @@ -43,8 +49,6 @@ impl Parser<'_> { }) { return Err(self.error("duplicate constraint block")); } - let mut expressions = Vec::new(); - let mut supported = !is_static; if self.eat(";") { if let Some(class) = self.class_stack.last_mut() { class.constraints.push(ClassConstraint { @@ -57,6 +61,19 @@ impl Parser<'_> { if prototype { return Err(self.error("extern or pure constraint requires a prototype")); } + let expressions = self.constraint_block()?; + if let Some(class) = self.class_stack.last_mut() { + class.constraints.push(ClassConstraint { + name, + expressions: if is_static { None } else { expressions }, + }); + } + Ok(()) + } + + pub(super) fn constraint_block(&mut self) -> Result>> { + let mut expressions = Vec::new(); + let mut supported = true; self.expect("{")?; let mut jobs = vec![Job::Block(true)]; while let Some(job) = jobs.pop() { @@ -84,18 +101,60 @@ impl Parser<'_> { jobs.push(Job::Expression); } } - Job::Else => { - if self.eat("else") { + Job::Guard { + condition, + first, + start, + negate, + has_else, + } => { + let guard = if negate { + self.node( + start, + ExprKind::Unary { + operator: "!".into(), + expression: condition, + postfix: false, + }, + )? + } else { + condition + }; + let body: Vec<_> = expressions.drain(first..).collect(); + for expression in body { + expressions.push(self.node( + start, + ExprKind::Binary { + left: guard, + operator: "||".into(), + right: expression, + }, + )?); + } + if has_else && self.eat("else") { + jobs.push(Job::Guard { + condition, + first: expressions.len(), + start, + negate: false, + has_else: false, + }); jobs.push(Job::Set); } } Job::Expression => { + let start = self.at; if self.eat("if") { - supported = false; self.expect("(")?; - self.expression(0)?; + let condition = self.expression(0)?; self.expect(")")?; - jobs.push(Job::Else); + jobs.push(Job::Guard { + condition, + first: expressions.len(), + start, + negate: true, + has_else: true, + }); jobs.push(Job::Set); } else if self.eat("foreach") { supported = false; @@ -121,7 +180,14 @@ impl Parser<'_> { supported &= simple; } if !soft && self.eat("->") { - supported = false; + let condition = expressions.pop().expect("condition retained"); + jobs.push(Job::Guard { + condition, + first: expressions.len(), + start, + negate: true, + has_else: false, + }); jobs.push(Job::Set); } else { if self.eat("dist") { @@ -134,13 +200,7 @@ impl Parser<'_> { } } } - if let Some(class) = self.class_stack.last_mut() { - class.constraints.push(ClassConstraint { - name, - expressions: supported.then_some(expressions), - }); - } - Ok(()) + Ok(supported.then_some(expressions)) } fn constraint_condition(&mut self) -> Result<(ExprId, bool)> { diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index 53d0d1c822a..efdf22c6581 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -3047,10 +3047,16 @@ fn malformed_array_method_with_is_rejected() { #[test] fn constraints_retain_simple_expressions_and_mark_other_forms() { let tree = parse( - "class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } endclass", + "class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } constraint c { soft x == 1; } constraint d { if (1) {} } endclass", ); let blocks = &tree.classes[0].constraints; assert_eq!(blocks[0].name.spelling, "a"); assert_eq!(blocks[0].expressions.as_ref().unwrap().len(), 2); - assert!(blocks[1].expressions.is_none()); + let guarded = blocks[1].expressions.as_ref().unwrap(); + assert_eq!(guarded.len(), 1); + assert!( + matches!(&tree.expression(guarded[0]).kind, ExprKind::Binary { operator, .. } if operator == "||") + ); + assert!(blocks[2].expressions.is_none()); + assert!(blocks[3].expressions.as_ref().unwrap().is_empty()); } diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 7af02d12dea..c153c186233 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -2075,3 +2075,56 @@ module Top(output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_conditionals + (source "conditional_constraints.sv" #" +module Top(output bit done); + class Packet; + rand bit mode; + rand int value; + int required; + constraint c { + value == required; + if (mode) { value inside {[1:3]}; value != 2; } + else value == 8; + mode -> { value > 0; if (value == 3) value != 1; } + } + endclass + Packet p; + initial begin + p = new; + p.required = 8; + if (!p.randomize() || p.mode != 0 || p.value != 8) $fatal(1, "reverse else solve"); + p.required = 3; + if (!p.randomize() || p.mode != 1 || p.value != 3) $fatal(1, "reverse then solve"); + p.required = 2; + if (p.randomize() || p.value != 3) $fatal(1, "block constraint lost"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_nested_guards + (source "nested_guards.sv" #" +module Top(output bit done); + class Packet; + rand bit a, b; + rand int x; + constraint c { + x == 7; + if (a) if (b) x == 1; else x == 7; + !a -> x == 2; + a -> b -> x == 1; + if (1'b0) x == 123; + } + endclass + Packet p; + initial begin + p = new; + if (!p.randomize() || p.a != 1 || p.b != 0 || p.x != 7) $fatal(1, "nested guards"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_conditional_constraints.json b/crates/celox-test-suite/verification/repros/sv_conditional_constraints.json new file mode 100644 index 00000000000..a10553b86ec --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_conditional_constraints.json @@ -0,0 +1,16 @@ +{ + "observations": [ + { + "tool": "icarus", + "case": "class::constrained_randomize_conditionals", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_conditionals/source_0.sv:9: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_conditionals/source_0.sv:7: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "case": "class::constrained_randomize_nested_guards", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_nested_guards/source_0.sv:6: sorry: Constraint declarations not supported.\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 24e8b0a50a1..9156cb55242 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -193,7 +193,33 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_conditionals", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -217,7 +243,8 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -241,7 +268,8 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -265,7 +293,33 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_nested_guards", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -289,7 +343,8 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index fff5c99ff3a..08e343c42fb 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2589,7 +2589,8 @@ "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", - "verification/repros/sv_inside_constraints.json" + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json" ], "cases": { "icarus": [ @@ -2597,7 +2598,9 @@ "class::constrained_randomize_width_and_inheritance", "class::constrained_randomize_hooks", "class::constrained_randomize_inside", - "class::constrained_randomize_inside_widths" + "class::constrained_randomize_inside_widths", + "class::constrained_randomize_conditionals", + "class::constrained_randomize_nested_guards" ] } }, diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 9f568f5a93e..38ae9074281 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -937,3 +937,8 @@ sv_backends! { fn constrained_randomize_inside(sim) { @case "class::constrained_randomize_inside"; } fn constrained_randomize_inside_widths(sim) { @case "class::constrained_randomize_inside_widths"; } } + +sv_backends! { + fn constrained_randomize_conditionals(sim) { @case "class::constrained_randomize_conditionals"; } + fn constrained_randomize_nested_guards(sim) { @case "class::constrained_randomize_nested_guards"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index f9aaeaa84c1..a911d2b4290 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -229,7 +229,11 @@ signedness before arithmetic evaluation. Excessive predicate expansion is reject during analysis, including repeated nested membership. Array sets, X/Z wildcard items and `$` bounds are not yet supported. Membership uses the same seeded solver policy described above. -Constrained enums and `randc`, conditional/foreach/soft constraints, +Conditional constraints support `if` / `else` and implication (`->`), including +nested blocks. Both sides participate in solving: a required result can constrain +the condition. These constructs do not choose a branch before solving. + +Constrained enums and `randc`, foreach/soft constraints, `dist`, `solve before`, constraint modes, external/static blocks, typed parameters in constraints, and inline `with` remain unsupported. Larger unconstrained `randc` domains, static random properties and random array/object/string properties also