From 40976fd6ea7e0c73db67cd1f8b982cf2e54ce4f6 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 03:09:35 +0900 Subject: [PATCH] feat(sv)!: solve scalar class constraints during randomize Connect named scalar class constraints to Aplite through a serializable heap program. Support 1-64 bit two-state integer comparisons, Boolean and bitwise operators, and addition/subtraction/multiplication with SV context sizing. Inherit constraints and replace same-name blocks in derived classes, including calls through base handles. Read state and random modes after pre_randomize. Apply a complete satisfying assignment atomically; proved UNSAT returns 0 without changing random fields or calling post_randomize. Restore temporary member selections on failure. Check-only calls consume no object random draws. Resource exhaustion raises a heap fault instead of masquerading as UNSAT. Use seeded SAT search for the initial integration. This avoids hash-cell acceptance failures and makes no uniformity claim; distribution work is tracked in #2187. Constrained enums/randc, inside, dist, solve-before, inline with, conditional/soft/foreach constraints and external/static blocks remain diagnosed as unsupported. The publishing consumer requires the independent aplite 0.1.0 release before publishing celox-heap. Validation: 129 randomization regressions across native, Cranelift, Wasm and parallel backends; 25 heap, 832 analyzer and 132 syntax tests plus doctests; focused failure/replay and unsupported-form tests; affected-crate clippy and rustdoc with warnings denied; NAPI cargo check; formatting and package/release guards. Verilator passes scalar mode/selection and width/inheritance cases. Retained evidence records its post_randomize-on-UNSAT disagreement and Icarus unsupported constraint declarations, with narrow tool-specific exclusions and unchanged Celox assertions. No local release build. BREAKING CHANGE: ObjectOp and heap Fault gain constraint randomization variants. Change-Id: I0bbc4db8256385015e506817f5ea46fd3fcdd006 --- .github/RELEASING.md | 9 +- Cargo.lock | 4 + Cargo.toml | 4 +- crates/celox-frontend-sv/Cargo.toml | 2 + .../src/lowering/ff/objects.rs | 19 +- crates/celox-heap/Cargo.toml | 3 + crates/celox-heap/src/lib.rs | 1 + crates/celox-heap/src/objects.rs | 4 + crates/celox-heap/src/ops.rs | 16 + crates/celox-heap/src/randomization.rs | 356 ++++++++++++++++++ crates/celox-sv-analyzer/Cargo.toml | 2 + crates/celox-sv-analyzer/src/ast/classes.rs | 25 +- .../src/ast/classes/constraints.rs | 214 +++++++++++ .../src/ast/procedural/randomization.rs | 82 ++-- .../celox-sv-analyzer/src/system_functions.rs | 5 +- crates/celox-sv-analyzer/src/tests.rs | 32 +- crates/celox-test-suite/LIMITATIONS.md | 10 + .../celox-test-suite/src/sv/cases/class.vtest | 91 +++++ .../repros/sv_scalar_constraints.json | 33 ++ .../verification/sv/icarus/class.json | 69 ++++ .../verification/sv/limitations.json | 36 ++ .../verification/sv/verilator/class.json | 23 ++ crates/celox-testbench/src/format.rs | 2 +- .../tests/frontends/systemverilog/class.rs | 13 +- docs/guide/systemverilog-reference.md | 22 +- docs/ja/guide/systemverilog-reference.md | 17 +- scripts/ci-changes.mjs | 5 +- scripts/ci-changes.test.mjs | 9 +- scripts/ci-lydite-changes.test.mjs | 7 +- scripts/publish-crates.sh | 2 +- scripts/publish-crates.test.mjs | 6 + 31 files changed, 1073 insertions(+), 50 deletions(-) create mode 100644 crates/celox-heap/src/randomization.rs create mode 100644 crates/celox-sv-analyzer/src/ast/classes/constraints.rs create mode 100644 crates/celox-test-suite/verification/repros/sv_scalar_constraints.json diff --git a/.github/RELEASING.md b/.github/RELEASING.md index 8ebf82c9402..6d455b10f3a 100644 --- a/.github/RELEASING.md +++ b/.github/RELEASING.md @@ -1,12 +1,19 @@ # Release policy Celox is released as one lockstep distribution. `VERSION`, -`.release-please-manifest.json`, the npm packages, and all Rust workspace crates +`.release-please-manifest.json`, the npm packages, and all Celox Rust workspace crates must always carry the same version. The public Rust entry points are `celox`, `celox-frontend-sdk`, `celox-test-suite`, and the Rust adapter API in `celox-napi`; the remaining published `celox-*` crates satisfy their Cargo dependency graph and remain implementation details. +Aplite has its own version and release train (`release-aplite.yml` and +`publish-aplite.yml`). Publish the Aplite version required by the workspace +before releasing Celox: `celox-heap` depends on it, and Cargo resolves the +published Aplite crate when packaging Celox crates. A bootstrap `0.0.0` release +does not satisfy this dependency. Aplite is deliberately absent from Celox's +lockstep publication list. + ## Versioning before 1.0 Pull request titles are the input to release automation after GitHub copies the diff --git a/Cargo.lock b/Cargo.lock index a33a7e74520..42717f4af44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "miette", "num-bigint", "num-traits", + "serde_json", "thiserror 2.0.21", ] @@ -663,8 +664,10 @@ dependencies = [ name = "celox-heap" version = "0.11.0" dependencies = [ + "aplite", "fxhash", "serde", + "serde_json", ] [[package]] @@ -784,6 +787,7 @@ name = "celox-sv-analyzer" version = "0.11.0" dependencies = [ "celox-design", + "celox-heap", "celox-sv-syntax", "fxhash", "miette", diff --git a/Cargo.toml b/Cargo.toml index 90e67df41c8..49e7d97722b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,8 +57,8 @@ description = "Celox HDL Simulator" rust-version = "1.99.1" [workspace.dependencies] -# Aplite has its own release version; these consumers are unpublished. -aplite = { path = "crates/aplite" } +# Aplite has an independent release version. +aplite = { version = "0.1.0", path = "crates/aplite" } celox = { version = "=0.11.0", path = "crates/celox", default-features = false } # x-release-please-version celox-analysis = { version = "=0.11.0", path = "crates/celox-analysis" } # x-release-please-version celox-backend-arm64 = { version = "=0.11.0", path = "crates/celox-backend-arm64" } # x-release-please-version diff --git a/crates/celox-frontend-sv/Cargo.toml b/crates/celox-frontend-sv/Cargo.toml index a51b484247d..e40e95db058 100644 --- a/crates/celox-frontend-sv/Cargo.toml +++ b/crates/celox-frontend-sv/Cargo.toml @@ -10,6 +10,8 @@ edition.workspace = true rust-version.workspace = true [dependencies] +serde_json = { workspace = true } + celox-design = { workspace = true } celox-frontend-core = { workspace = true } celox-heap = { workspace = true } diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index b0f44024a44..e2d499dae70 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -24,6 +24,22 @@ impl Ff<'_, '_> { }) .collect::, _>>()?; let result = match op { + ObjectOp::Randomize(program) => { + let object = self.handle(&args[0])?; + let check = self.integer_of_width(&args[1], 1, false)?; + let bytes = serde_json::to_vec(program).expect("constraint program serialization"); + let mut buffer = self.heap_call(ops::NEW, &[]); + for chunk in bytes.chunks(8) { + let value = chunk + .iter() + .fold(0u64, |value, byte| (value << 8) | u64::from(*byte)); + let value = self.constant64(value); + let count = self.constant64(chunk.len() as u64); + buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, value, count]); + } + let program = self.heap_call(ops::FREEZE, &[buffer]); + self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check]) + } ObjectOp::Container { .. } => unreachable!("handled by container_call"), ObjectOp::New { class, @@ -132,7 +148,8 @@ impl Ff<'_, '_> { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, }), - ObjectOp::Store(_) + ObjectOp::Randomize(_) + | ObjectOp::Store(_) | ObjectOp::ClassOf | ObjectOp::Random | ObjectOp::RandomCyclic { .. } diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml index 0ab148bba27..e8223578ef6 100644 --- a/crates/celox-heap/Cargo.toml +++ b/crates/celox-heap/Cargo.toml @@ -10,6 +10,9 @@ edition.workspace = true rust-version.workspace = true [dependencies] +aplite = { workspace = true } +serde_json = { workspace = true } + serde = { workspace = true, features = ["rc"] } fxhash = { workspace = true } diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index ad28602712c..0e0c65aa918 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -19,6 +19,7 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; pub mod containers; mod objects; pub mod ops; +pub mod randomization; pub use objects::{Fault, NULL}; diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 19644b31990..4a55a8f4f2f 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -49,6 +49,7 @@ impl Object { /// reports once control returns to it. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Fault { + ConstraintRandomization(String), NegativeArraySize, ContainerAllocationLimit, /// A property access or method call through `null` or a handle of no @@ -61,6 +62,9 @@ pub enum Fault { impl std::fmt::Display for Fault { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Self::ConstraintRandomization(reason) => { + write!(f, "constraint randomization failed: {reason}") + } Self::NegativeArraySize => f.write_str("negative dynamic array size"), Self::ContainerAllocationLimit => { f.write_str("dynamic container allocation limit exceeded") diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index c1720c54a97..8df747bd277 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -83,6 +83,8 @@ pub const OBJECT_MODE_SELECTED: u64 = 61; pub const OBJECT_RANDOM_CYCLIC: u64 = 62; /// `copy(object)`: a new object with a copy of the properties of `object`. pub const OBJECT_COPY: u64 = 63; +/// Solve the scalar constraint program in string b for object a; c selects check-only. +pub const OBJECT_RANDOMIZE: u64 = 64; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -193,6 +195,20 @@ impl Heap { 0 } OBJECT_CLASS => self.class_of(a as Handle).into(), + OBJECT_RANDOMIZE => { + match serde_json::from_slice::( + self.string(b as Handle), + ) { + Ok(program) => u64::from(self.randomize_object(a as Handle, &program, c != 0)), + Err(error) => { + self.fault + .get_or_insert(crate::Fault::ConstraintRandomization( + error.to_string(), + )); + 0 + } + } + } OBJECT_RANDOM => self.random_object(a as Handle), OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b), OBJECT_SEED => { diff --git a/crates/celox-heap/src/randomization.rs b/crates/celox-heap/src/randomization.rs new file mode 100644 index 00000000000..18980c30405 --- /dev/null +++ b/crates/celox-heap/src/randomization.rs @@ -0,0 +1,356 @@ +//! Serializable scalar constraint programs shared by the SV compiler and heap. +//! The program carries no pointers or persistent solver state. +use crate::{Fault, Handle, Heap}; +use aplite::{ + Env, Limits, Scalar, Sort, Term, Verdict, and, boolv, bv, eq, ite, node, not, solve_seeded, var, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Field { + pub offset: u32, + pub width: u32, + pub random: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum Expr { + Literal(u32, u64), + Field(usize), + Resize { + value: Box, + width: u32, + signed: bool, + }, + Unary { + op: String, + value: Box, + }, + Binary { + op: String, + left: Box, + right: Box, + signed: bool, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Program { + pub fields: Vec, + pub constraints: Vec, +} + +fn truth(value: Term) -> Term { + let Sort::Bv(width) = value.0.sort else { + unreachable!() + }; + not(eq(value, bv(width, 0))) +} +fn boolean(value: Term) -> Term { + ite(value, bv(1, 1), bv(1, 0)) +} + +impl Expr { + fn term(&self, fields: &[Term]) -> Result { + Ok(match self { + Self::Literal(width, value) => bv(*width, *value), + Self::Field(index) => fields + .get(*index) + .ok_or("invalid constraint field")? + .clone(), + Self::Resize { + value, + width, + signed, + } => { + let value = value.term(fields)?; + let Sort::Bv(old) = value.0.sort else { + unreachable!() + }; + if old == *width { + value + } else { + let op = if old > *width { + format!("(_ extract {} 0)", width - 1) + } else { + format!( + "(_ {}_extend {})", + if *signed { "sign" } else { "zero" }, + width - old + ) + }; + node(Sort::Bv(*width), op, vec![value]) + } + } + Self::Unary { op, value } => { + let value = value.term(fields)?; + match op.as_str() { + "!" => boolean(not(truth(value))), + "~" => node(value.0.sort.clone(), "bvnot", vec![value]), + "-" => { + let Sort::Bv(width) = value.0.sort else { + unreachable!() + }; + node(Sort::Bv(width), "bvsub", vec![bv(width, 0), value]) + } + _ => return Err("invalid constraint unary operation".into()), + } + } + Self::Binary { + op, + left, + right, + signed, + } => { + let a = left.term(fields)?; + let b = right.term(fields)?; + let relation = match op.as_str() { + "==" => Some(eq(a.clone(), b.clone())), + "!=" => Some(not(eq(a.clone(), b.clone()))), + "&&" => Some(and(truth(a.clone()), truth(b.clone()))), + "||" => Some(node( + Sort::Bool, + "or", + vec![truth(a.clone()), truth(b.clone())], + )), + "<" | "<=" | ">" | ">=" => { + let suffix = if op.ends_with('=') { "le" } else { "lt" }; + let operands = if op.starts_with('>') { + vec![b.clone(), a.clone()] + } else { + vec![a.clone(), b.clone()] + }; + Some(node( + Sort::Bool, + format!("bv{}{suffix}", if *signed { "s" } else { "u" }), + operands, + )) + } + _ => None, + }; + if let Some(relation) = relation { + boolean(relation) + } else { + let op = match op.as_str() { + "+" => "bvadd", + "-" => "bvsub", + "*" => "bvmul", + "&" => "bvand", + "|" => "bvor", + "^" => "bvxor", + _ => return Err("invalid constraint binary operation".into()), + }; + node(a.0.sort.clone(), op, vec![a, b]) + } + } + }) + } +} + +impl Heap { + /// Evaluate against the state after pre_randomize; commit only a complete + /// assignment. A solver failure is a runtime fault, never an UNSAT result. + pub fn randomize_object( + &mut self, + handle: Handle, + program: &Program, + check_only: bool, + ) -> bool { + self.randomize_object_with_limits(handle, program, check_only, Limits::default()) + } + + fn randomize_object_with_limits( + &mut self, + handle: Handle, + program: &Program, + check_only: bool, + limits: Limits, + ) -> bool { + if !self.check_object(handle, 0) { + return false; + } + let result = (|| -> Result { + let mut projection = Env::new(); + let mut terms = Vec::new(); + let mut active = Vec::new(); + let mut formula = boolv(true); + for (index, field) in program.fields.iter().enumerate() { + if !(1..=64).contains(&field.width) { + return Err("invalid constraint field width".into()); + } + let name = index.to_string(); + let term = var(name.clone(), Sort::Bv(field.width)); + let enabled = !check_only && self.random_mode(handle, field.offset, field.random); + if enabled { + projection.insert(name, term.clone()); + active.push((index, field)); + } else { + let value = self.load( + handle, + field.offset as usize, + field.width.div_ceil(8) as usize, + ); + formula = and(formula, eq(term.clone(), bv(field.width, value))); + } + terms.push(term); + } + for constraint in &program.constraints { + formula = and(formula, truth(constraint.term(&terms)?)); + } + let seed = if projection.is_empty() { + 0 + } else { + self.random_object(handle) + }; + // Initial integration uses seeded SAT search, not hash-cell acceptance. + // It finds a valid model without claiming uniform sampling (#2187). + let outcome = solve_seeded(&formula, &projection, limits, seed); + match outcome.verdict { + Verdict::Unsat => Ok(false), + Verdict::Unknown => Err(outcome + .reason + .unwrap_or_else(|| "constraint solving incomplete".into())), + Verdict::Sat => { + let model = &outcome.context_values; + let updates = active + .into_iter() + .map(|(index, field)| match model.get(&index.to_string()) { + Some(Scalar::Bv { value, .. }) => Ok((field, *value)), + _ => Err("missing constraint field value".to_owned()), + }) + .collect::, _>>()?; + for (field, value) in updates { + self.store( + handle, + field.offset as usize, + field.width.div_ceil(8) as usize, + value, + ); + } + Ok(true) + } + } + })(); + match result { + Ok(success) => success, + Err(reason) => { + self.fault + .get_or_insert(Fault::ConstraintRandomization(reason)); + false + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program() -> Program { + Program { + fields: vec![Field { + offset: 0, + width: 4, + random: true, + }], + constraints: vec![Expr::Binary { + op: "<".into(), + left: Box::new(Expr::Field(0)), + right: Box::new(Expr::Literal(4, 3)), + signed: false, + }], + } + } + + #[test] + fn modes_unsat_faults_and_snapshot_replay() { + let mut heap = Heap::new(); + let object = heap.new_object(1, 1); + heap.store(object, 0, 1, 9); + let program = program(); + let mut before_check = heap.clone(); + assert!(!heap.randomize_object(object, &program, true)); + assert_eq!( + heap.random_object(object), + before_check.random_object(object) + ); + assert_eq!(heap.load(object, 0, 1), 9); + assert_eq!(heap.take_fault(), None); + let limits = Limits { + max_work: 0, + ..Limits::default() + }; + assert!(!heap.randomize_object_with_limits(object, &program, false, limits)); + assert_eq!(heap.load(object, 0, 1), 9); + assert!(matches!( + heap.take_fault(), + Some(Fault::ConstraintRandomization(_)) + )); + heap.seed_object(object, 42); + let mut restored = heap.clone(); + for _ in 0..16 { + assert!(heap.randomize_object(object, &program, false)); + assert!(restored.randomize_object(object, &program, false)); + let value = heap.load(object, 0, 1); + assert!(value < 3); + assert_eq!(value, restored.load(object, 0, 1)); + } + heap.set_random_mode(object, 0, false); + heap.store(object, 0, 1, 7); + assert!(!heap.randomize_object(object, &program, false)); + assert_eq!(heap.load(object, 0, 1), 7); + assert_eq!(heap.take_fault(), None); + } + + #[test] + fn signed_inputs_in_unsigned_arithmetic_context() { + let field = |i, signed| Expr::Resize { + value: Box::new(Expr::Field(i)), + width: 32, + signed, + }; + let binary = |op: &str, left, right| Expr::Binary { + op: op.into(), + left: Box::new(left), + right: Box::new(right), + signed: false, + }; + let program = Program { + fields: [8, 16, 32] + .into_iter() + .enumerate() + .map(|(i, width)| Field { + offset: i as u32 * 8, + width, + random: true, + }) + .collect(), + constraints: vec![ + binary( + "==", + field(0, true), + Expr::Unary { + op: "-".into(), + value: Box::new(Expr::Literal(32, 1)), + }, + ), + binary("==", field(1, true), Expr::Literal(32, 1)), + binary("==", Expr::Field(2), Expr::Literal(32, 256)), + binary( + "==", + binary("+", field(0, false), field(1, false)), + Expr::Field(2), + ), + ], + }; + let mut heap = Heap::new(); + let object = heap.new_object(1, 24); + assert!( + heap.randomize_object(object, &program, false), + "{:?}", + heap.take_fault() + ); + assert_eq!(heap.load(object, 0, 1), 255); + assert_eq!(heap.load(object, 8, 2), 1); + assert_eq!(heap.load(object, 16, 4), 256); + } +} diff --git a/crates/celox-sv-analyzer/Cargo.toml b/crates/celox-sv-analyzer/Cargo.toml index dbcb248dc87..16fa5ab642c 100644 --- a/crates/celox-sv-analyzer/Cargo.toml +++ b/crates/celox-sv-analyzer/Cargo.toml @@ -10,6 +10,8 @@ edition.workspace = true rust-version.workspace = true [dependencies] +celox-heap = { workspace = true } + celox-design = { workspace = true } celox-sv-syntax = { workspace = true } fxhash = { workspace = true } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 471476bbbe7..a3924547f9b 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -12,6 +12,7 @@ use std::rc::Rc; use super::*; use crate::system_functions::{HandleProperty, ObjectField, ObjectOp}; +mod constraints; pub(super) mod specializations; /// Bit width of a handle, see `celox_design::HANDLE_WIDTH`. @@ -131,6 +132,7 @@ pub(super) struct Class { /// Bytes of an object. pub size: u32, pub has_constraints: bool, + pub constraints: Vec<(String, Result, String>)>, } /// An internal unsigned packed argument of a generated method. @@ -152,7 +154,7 @@ impl Class { /// Validate the supported unconstrained subset before binding a call. pub fn check_randomize(&self) -> Converted<()> { if self.has_constraints { - return Err(unsupported("class randomize with constraints")); + self.constraint_program()?; } for property in &self.properties { if property.randc && property.cyclic_domain_size().is_none() { @@ -860,9 +862,29 @@ pub(super) fn class( method.name ))); } + let mut constraints = base + .as_ref() + .map(|base| base.constraints.clone()) + .unwrap_or_default(); + for block in &declaration.constraints { + let block_name = block.name.spelling.clone(); + constraints.retain(|(name, _)| *name != block_name); + let expressions = block + .expressions + .as_ref() + .ok_or_else(|| "unsupported constraint block form".to_owned()) + .and_then(|expressions| { + expressions + .iter() + .map(|&id| constraints::bind(id, tree, &properties, env)) + .collect() + }); + constraints.push((block_name, expressions)); + } let class = Rc::new(Class { name: name.to_owned(), id: class_id(tree, name), + constraints, has_constraints: declaration.has_constraints || base.as_ref().is_some_and(|base| base.has_constraints), base: base.map(|base| base.name.clone()), @@ -988,6 +1010,7 @@ fn interface_class( is_abstract: true, is_interface: true, has_constraints: false, + constraints: Vec::new(), properties: Vec::new(), base_properties: 0, statics: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs new file mode 100644 index 00000000000..3cb2e87ef24 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -0,0 +1,214 @@ +//! Scalar constraint binding. Unsupported forms fail before any RNG draws. +use super::*; +use celox_heap::randomization::{Expr as ConstraintExpr, Field, Program}; +use celox_sv_syntax::{ExprId, ExprKind}; + +struct Typed { + kind: Kind, + width: u32, + signed: bool, +} +enum Kind { + Leaf(ConstraintExpr), + Unary(String, Box), + Binary(String, Box, Box), +} +fn comparison(op: &str) -> bool { + matches!(op, "==" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||") +} + +// Apply context sizing before arithmetic evaluation (IEEE 1800-2023 11.8.2). +// Keep operand types until this pass: eagerly extending signed children would +// incorrectly sign-extend them before a wider unsigned parent is encountered. +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::Unary(op, child) => { + let logical = op == "!"; + ( + ConstraintExpr::Unary { + op, + value: Box::new(emit(*child, (!logical).then_some((width, signed)))), + }, + if logical { 1 } else { width }, + ) + } + Kind::Binary(op, a, b) => { + let is_comparison = comparison(&op); + let logical = matches!(op.as_str(), "&&" | "||"); + let operands = if is_comparison { + (a.width.max(b.width), a.signed && b.signed) + } else { + (width, signed) + }; + let a = emit(*a, (!logical).then_some(operands)); + let b = emit(*b, (!logical).then_some(operands)); + ( + ConstraintExpr::Binary { + op, + left: Box::new(a), + right: Box::new(b), + signed: operands.1, + }, + if is_comparison { 1 } else { width }, + ) + } + }; + if result_width == width { + expr + } else { + ConstraintExpr::Resize { + value: Box::new(expr), + width, + signed, + } + } +} + +pub(super) fn bind( + id: ExprId, + tree: &AnalysisContext<'_>, + properties: &[Property], + env: &HashMap, +) -> Result { + fn expression( + id: ExprId, + tree: &AnalysisContext<'_>, + properties: &[Property], + env: &HashMap, + depth: usize, + ) -> Result { + if depth > 64 { + return Err("constraint expression nesting limit".into()); + } + let recurse = |id| expression(id, tree, properties, env, depth + 1); + let native = tree.declarations(); + Ok(match &native.expression(id).kind { + ExprKind::Group(id) => return recurse(*id), + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + if let Some((index, property)) = properties + .iter() + .enumerate() + .rev() + .find(|(_, p)| p.name == name) + { + Typed { + kind: Kind::Leaf(ConstraintExpr::Field(index)), + width: property.field.width, + signed: property.field.signed, + } + } else if env.contains_key(&name) { + // Parameter type reconstruction belongs to the general expression binder. + // Do not guess its width/sign here. + return Err("typed parameters in constraints".into()); + } else { + return Err(format!("constraint variable `{name}`")); + } + } + ExprKind::Literal(text) => { + if text.starts_with("'0") || text.starts_with("'1") { + return Err("unbased unsized constraint literal".into()); + } + let literal = + typecheck::parse_integral_literal(text).ok_or("integral constraint literal")?; + if literal.width > 64 || literal.mask != num_bigint::BigUint::default() { + return Err("constraint literal wider than 64 bits or containing X/Z".into()); + } + let value = literal.value.to_u64_digits().first().copied().unwrap_or(0); + Typed { + kind: Kind::Leaf(ConstraintExpr::Literal(literal.width as u32, value)), + width: literal.width as u32, + signed: literal.signed, + } + } + ExprKind::Unary { + operator, + expression, + postfix: false, + } if matches!(operator.as_str(), "+" | "-" | "~" | "!") => { + let value = recurse(*expression)?; + if operator == "+" { + return Ok(value); + } + Typed { + width: if operator == "!" { 1 } else { value.width }, + signed: operator != "!" && value.signed, + kind: Kind::Unary(operator.clone(), Box::new(value)), + } + } + ExprKind::Binary { + left, + operator, + right, + } if matches!( + operator.as_str(), + "+" | "-" + | "*" + | "&" + | "|" + | "^" + | "==" + | "!=" + | "<" + | "<=" + | ">" + | ">=" + | "&&" + | "||" + ) => + { + let a = recurse(*left)?; + let b = recurse(*right)?; + let width = a.width.max(b.width); + let signed = a.signed && b.signed; + let logical = matches!(operator.as_str(), "&&" | "||"); + let comparison = + logical || matches!(operator.as_str(), "==" | "!=" | "<" | "<=" | ">" | ">="); + Typed { + width: if comparison { 1 } else { width }, + signed: !comparison && signed, + kind: Kind::Binary(operator.clone(), Box::new(a), Box::new(b)), + } + } + _ => return Err("unsupported scalar constraint expression".into()), + }) + } + expression(id, tree, properties, env, 0).map(|value| emit(value, None)) +} + +impl Class { + pub fn constraint_program(&self) -> Converted { + let mut fields = Vec::new(); + for property in &self.properties { + if property.randc + || property.field.handle.is_some() + || property.field.width > 64 + || property.r#type.is_enum + { + return Err(unsupported( + "constraints currently require scalar non-enum properties without randc", + )); + } + fields.push(Field { + offset: property.field.offset, + width: property.field.width, + random: property.rand, + }); + } + let mut constraints = Vec::new(); + for (_, block) in &self.constraints { + constraints.extend( + block + .as_ref() + .map_err(|reason| unsupported(format!("constraints: {reason}")))? + .clone(), + ); + } + Ok(Program { + fields, + constraints, + }) + } +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 5e446a9caa9..06b9c0a3c8d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -133,32 +133,66 @@ pub(super) fn lower( else_body: Vec::new(), }); body.extend(hook("pre_randomize")); - for property in &class.properties { - if property.constant - || property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none()) - { - continue; - } + if class.has_constraints { + let success = builder.declare("$constraint_success", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(success.clone()), + rhs: classes::object_call( + ObjectOp::Randomize(class.constraint_program()?), + vec![ + Expr::Ident(this.clone()), + Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal("1".into())), + }, + ], + ), + nonblocking: false, + }); body.push(Stmt::If { - condition: Expr::Binary { - left: Box::new(Expr::Binary { - left: Box::new(Expr::Ident(argument.clone())), - op: BinaryOp::Ne, - right: Box::new(Expr::Literal("1".into())), - }), - op: BinaryOp::LogicAnd, - right: Box::new(classes::object_call( - ObjectOp::ModeGet( - property.field.offset, - property.rand || property.randc, - ), - vec![Expr::Ident(this.clone())], - )), - }, - then_body: random_property(&mut builder, property, &this), - else_body: Vec::new(), + condition: Expr::Ident(success), + then_body: Vec::new(), + else_body: vec![ + Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePop, + vec![Expr::Ident(this.clone())], + ))], + else_body: Vec::new(), + }, + Stmt::Return(Some(Expr::Literal("32'sd0".into()))), + ], }); + } else { + for property in &class.properties { + if property.constant + || property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + { + continue; + } + body.push(Stmt::If { + condition: Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1".into())), + }), + op: BinaryOp::LogicAnd, + right: Box::new(classes::object_call( + ObjectOp::ModeGet( + property.field.offset, + property.rand || property.randc, + ), + vec![Expr::Ident(this.clone())], + )), + }, + then_body: random_property(&mut builder, property, &this), + else_body: Vec::new(), + }); + } } body.extend(hook("post_randomize")); body.push(Stmt::If { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 0ee78a1655e..d580fad8947 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -896,6 +896,7 @@ impl ContainerOp { /// frontend needs no class table. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ObjectOp { + Randomize(celox_heap::randomization::Program), Container { op: ContainerOp, layout: ContainerLayout, @@ -955,7 +956,8 @@ impl ObjectOp { match self { Self::Container { op, layout } => op.result_type(*layout), Self::Random | Self::RandomCyclic { .. } => (64, false), - Self::Seed + Self::Randomize(_) + | Self::Seed | Self::Check(_) | Self::ModeSet(_) | Self::ModePush @@ -978,6 +980,7 @@ impl fmt::Display for ObjectOp { Self::Store(_) => "property write", Self::ClassOf => "class query", Self::Random => "object random bits", + Self::Randomize(_) => "constrained object randomization", Self::RandomCyclic { .. } => "object random cyclic index", Self::Seed => "object random seed", Self::Check(_) => "object receiver check", diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index dca17b7b5b6..9d1c6193ed2 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6588,7 +6588,37 @@ fn explicit_output_data_types_default_to_variables() { fn class_randomize_rejects_unsupported_semantics() { for (members, call, expected) in [ ( - "rand int x; constraint c { x == 1; }", + "rand int x; constraint c { if (x) x == 1; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { soft x == 1; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x, y; constraint c { solve x before y; x == y; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { x inside {[1:3]}; }", + "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()", + "constraints", + ), + ( + "rand int x; constraint c { x dist {1 := 2}; }", "c.randomize()", "constraints", ), diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index c6304b223f4..fa2a2e8ecfa 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -345,6 +345,16 @@ records the native-runner result; the case stays enabled on all Celox backends. ## SystemVerilog suite +The scalar class-constraint cases are rejected by Icarus 13.0 because constraint +blocks are unsupported. Verilator 5.052 passes the scalar modes and mixed-width +inheritance cases, but calls `post_randomize` even when ordinary `randomize` +returns failure. IEEE 1800-2023 18.6.3 requires skipping that hook. The focused +`class::constrained_randomize_hooks` assertion stays enabled in Celox and is +excluded only for Verilator. [Recorded diagnostics](verification/repros/sv_scalar_constraints.json) +retain both tool limitations; reproduce with `--include-ignored --filter +class::constrained_randomize`. + + Verilator 5.052 rejects a string variable or string method expression as the `$sscanf` format, requiring a literal instead. IEEE 1800-2023 21.3.4.3 permits string expressions here. Only `scan::sscanf_string_format_expression` is diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 87511f25c91..cd39b6a0903 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1911,3 +1911,94 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "5\n")) + +(case constrained_randomize_scalar + (source "constraints.sv" #" +module Top(output bit done); + class Packet; + rand bit [3:0] x, y; + int limit = 4; + constraint bounds { x < limit; y < 4; x + y == 5; x >= 0; y > 0; x <= 3; } + endclass + Packet p; + int old_x, old_y; + initial begin + p = new; + p.srandom(17); + repeat (8) begin + if (!p.randomize()) $fatal(1, "sat failed"); + if (!(p.x < 4 && p.y < 4 && p.x + p.y == 5)) $fatal(1, "invalid model"); + end + old_x = p.x; old_y = p.y; + p.limit = 1; + if (p.randomize()) $fatal(1, "unsat succeeded"); + if (p.x != old_x || p.y != old_y) $fatal(1, "unsat changed fields"); + p.limit = 4; + p.x = 2; p.y = 3; + if (!p.randomize(null)) $fatal(1, "check-only failed"); + p.y = 0; + if (p.randomize(null)) $fatal(1, "check-only ignored constraints"); + p.x.rand_mode(0); + if (!p.randomize() || p.x != 2 || p.y != 3) $fatal(1, "disabled rand is not state"); + p.y = 1; + if (p.randomize(x)) $fatal(1, "selection should be unsat"); + if (p.x.rand_mode() != 0 || p.y.rand_mode() != 1) $fatal(1, "failed selection leaked modes"); + p.y = 3; + if (!p.randomize() || p.x != 2) $fatal(1, "modes not restored"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_width_and_inheritance + (source "constraint_widths.sv" #" +module Top(output bit done); + class Base; + rand bit signed [7:0] a; + rand bit signed [15:0] b; + rand bit [31:0] c; + constraint values { a == -1; b == 1; c == 256; } + constraint sum { (a + b) == c; } + endclass + class Derived extends Base; + constraint values { a == -2; b == 2; c == 256; } + endclass + Base p; + Derived q; + initial begin + p = new; + if (!p.randomize()) $fatal(1, "unsigned context was lost"); + if (p.a != -1 || p.b != 1 || p.c != 256) $fatal(1, "base values"); + q = new; + p = q; + if (!p.randomize()) $fatal(1, "derived constraints were not dispatched"); + if (q.a != -2 || q.b != 2 || q.c != 256) $fatal(1, "override values"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_hooks + (source "constraint_hooks.sv" #" +module Top(output bit done); + class Packet; + rand int x; + int limit, before_count, after_count; + constraint bounds { x == limit; x < 3; } + function void pre_randomize(); before_count++; limit = before_count; endfunction + function void post_randomize(); after_count++; endfunction + endclass + Packet p; + initial begin + p = new; + if (!p.randomize() || p.x != 1) $fatal(1, "first pre state"); + if (!p.randomize() || p.x != 2) $fatal(1, "second pre state"); + if (p.randomize() || p.x != 2) $fatal(1, "unsat changed fields"); + if (p.before_count != 3 || p.after_count != 2) $fatal(1, "post called on failure"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json b/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json new file mode 100644 index 00000000000..fdbb8d899b8 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json @@ -0,0 +1,33 @@ +{ + "specification": "IEEE 1800-2023 18.5, 18.6.3", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "case": "class::constrained_randomize_hooks", + "status": "runtime_error", + "log": "%Warning-UNSATCONSTR: /source_0.sv:6: Unsatisfied constraint: 'constraint bounds { x == limit; x < 3; }'\n%Warning-UNSATCONSTR: /source_0.sv:6: Unsatisfied constraint: 'constraint bounds { x == limit; x < 3; }'\n[0] %Fatal: source_0.sv:16: Assertion failed in TOP.celox_suite_tb.dut: post called on failure\n%Error: /source_0.sv:16: Verilog $stop\nAborting...\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_hooks", + "status": "compile_error", + "log": "/source_0.sv:6: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_scalar", + "status": "compile_error", + "log": "/source_0.sv:6: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_width_and_inheritance", + "status": "compile_error", + "log": "/source_0.sv:7: sorry: Constraint declarations not supported.\n/source_0.sv:8: sorry: Constraint declarations not supported.\n/source_0.sv:11: 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 693a8141fb0..6aee7194ef9 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -184,6 +184,75 @@ "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" + ], + "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_hooks", + "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" + ], + "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_scalar", + "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" + ], + "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_width_and_inheritance", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 6c53e1025bc..0ddd3479670 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2578,5 +2578,41 @@ "scan::sscanf_string_format_expression" ] } + }, + { + "id": "sv_icarus_scalar_constraints", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "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": [], + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::constrained_randomize_scalar", + "class::constrained_randomize_width_and_inheritance", + "class::constrained_randomize_hooks" + ] + } + }, + { + "id": "sv_verilator_post_randomize_unsat", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::constrained_randomize_hooks" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index ceb08b51dc7..d576761f5c8 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -101,6 +101,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_post_randomize_unsat", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "upstream": [] + }, + "name": "class::constrained_randomize_hooks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-testbench/src/format.rs b/crates/celox-testbench/src/format.rs index 5aa0e3b0c7b..cff68d2b959 100644 --- a/crates/celox-testbench/src/format.rs +++ b/crates/celox-testbench/src/format.rs @@ -720,7 +720,7 @@ mod tests { is_string: false, float_precision: None, }; - assert_eq!(format_sized_display_arg(&arg, 's', Some(0)), []); + assert!(format_sized_display_arg(&arg, 's', Some(0)).is_empty()); } fn sized(value: u32, width: usize, signed: bool, spec: char, field: Option) -> String { diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index b3243686b6b..22d5d034586 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -381,7 +381,7 @@ sv_backends! { } sv_backends! { - fn class_randomize_rejects_dynamic_base_handle(sim) { + fn class_randomize_rejects_unsupported_dynamic_constraints(sim) { @setup { let source = r#"module Top(output int value, hooks, result); class Base; @@ -391,7 +391,7 @@ sv_backends! { function void post_randomize(); calls++; endfunction endclass class Derived extends Base; - constraint c { x == 1; } + constraint c { x dist {1 := 2}; } endclass Base b; Derived d; @@ -923,3 +923,12 @@ sv_backends! { assert_eq!(sim.get_four_state(value), expected); } } + +sv_backends! { + fn constrained_randomize_scalar(sim) { @case "class::constrained_randomize_scalar"; } + fn constrained_randomize_width_and_inheritance(sim) { @case "class::constrained_randomize_width_and_inheritance"; } +} + +sv_backends! { + fn constrained_randomize_hooks(sim) { @case "class::constrained_randomize_hooks"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ea7c9387bfb..4cf3e16b95a 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -200,8 +200,8 @@ including supported properties not declared `rand`. Names are resolved in the receiver's class, not the caller's scope; expressions and inaccessible members are rejected. The temporary modes are installed before the pre-hook and restored after the post-hook; hooks can inspect and change them. `randomize(null)` runs -the hooks without drawing or assigning random values (18.11). Constraints are -not supported even for this checker form. +the pre-hook and checks constraints without drawing or assigning random values; +the post-hook runs only on success (18.11). Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both @@ -212,9 +212,21 @@ members. Each property visits every value once before starting another cycle Disabled properties retain their cycle; checkpoints restore it. `srandom` reseeds the RNG without making already consumed values eligible again. -Constraints, `with`, larger `randc` domains, static random properties, and random -array/object/string properties remain unsupported. A constrained dynamic -subclass is rejected rather than silently randomizing only its base properties. +Named constraint blocks support 1–64-bit two-state scalar integer properties, +comparisons, logical and bitwise operations, addition, subtraction and multiplication. +Inherited blocks apply, and a derived block with the same name replaces its base +block. Disabled and unselected properties are state inputs read after the pre-hook. +Aplite searches for a satisfying assignment using the object's seed, then updates +all selected properties together. Proved infeasibility returns `0`, preserves the +properties and skips the post-hook (18.6.3). Resource exhaustion is a runtime error. +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, +`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 +remain unsupported. Unsupported dynamic subclasses are rejected before draws. A call through `null` is a runtime error. ### Time literal delays {#time-literal-delays} diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 439ea865291..6c0507119d2 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -125,8 +125,8 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や `object.randomize(x, y)` はその呼び出しに限り対象を指定します。対応型なら `rand` でない プロパティも指定できます。名前は呼び出し元ではなくreceiverのクラスで解決し、式やアクセス権のない メンバーは拒否します。一時モードはpreフックの前に設定し、postフックの後に復元します。 -フックから一時モードを参照・変更できます。`randomize(null)` は乱数生成や代入を行わずフックを -呼びます(18.11)。この形式でも制約付きクラスは未対応です。 +フックから一時モードを参照・変更できます。`randomize(null)` はpreフックの後、乱数生成や +代入を行わず制約を検査し、成功時だけpostフックを呼びます(18.11)。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します @@ -136,8 +136,17 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や `rand_mode`、引数による対象選択とチェックポイント復元にも対応します。無効化中は 循環を進めず、`srandom` は消費済みの値を保持したまま乱数生成器を再シードします。 -制約、`with`、上記の上限を超える `randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の -乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 +名前付き制約ブロックは、1〜64ビットの2値整数プロパティに対する比較、論理・ビット演算、 +加減乗算に対応します。親の制約を継承し、子クラスの同名ブロックで置き換えられます。 +無効化・選択対象外のプロパティはpreフック後の状態値として扱います。Apliteがオブジェクトの +seedを使って解を探索し、成功時だけ対象プロパティをまとめて更新します。解なしが確定した場合は +値を保持して`0`を返し、postフックを呼びません(18.6.3)。探索予算切れは実行時エラーです。 +この初期実装は一様分布を保証しません。分布の改善は[#2187](https://github.com/celox-sim/celox/issues/2187)で追跡します。 + +制約付きenum・`randc`、`inside`、条件付き・foreach・soft制約、`dist`、`solve before`、 +制約モード、外部・static制約ブロック、制約中の型付きパラメーター、inline `with` は未対応です。 +上記の上限を超える制約なし`randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の +乱数化も未対応です。未対応の子クラスは乱数生成前に拒否します。 `null` を通した呼び出しは実行時エラーです。 ### 時間リテラルによる遅延 {#time-literal-delays} diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 3e343ee2a67..a97b9d17302 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -42,7 +42,6 @@ const RELEASE_PLEASE_FILES = new Set([ // dependencies of celox-napi. ci-changes.test.mjs checks the workspace graph // so adding a dependency cannot silently make this exclusion unsafe. const RUST_ONLY_CRATES = new Set([ - "aplite", "celox-test-suite", "celox-bench", "celox-bench-sv", @@ -309,8 +308,8 @@ if ( // Lydite core tests run independently; bridge CI is disabled. export function celoxRustTestScope(files, packages) { return rustTestScope( - files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/(?:lydite(?:-|\/)|aplite\/))/.test(path)), - packages.filter((pkg) => !/^(?:lydite(?:-|$)|aplite$)/.test(pkg.name)), + files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/lydite(?:-|\/))/.test(path)), + packages.filter((pkg) => !/^lydite(?:-|$)/.test(pkg.name)), ); } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 42b42f7e884..0c856295b91 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -56,7 +56,6 @@ test("Rust test infrastructure skips bindings while retaining Rust checks", () = "crates/celox-bench-sv/src/main.rs", "crates/celox-vpi/src/lib.rs", "crates/celox-wasm/src/lib.rs", - "crates/aplite/src/lib.rs", "crates/lydite/src/lib.rs", "crates/lydite-ir/src/lib.rs", "crates/lydite-solver/src/lib.rs", @@ -355,6 +354,14 @@ test("Rust changes exercise native builds and JavaScript bindings", () => { }); }); +test("Aplite runtime changes exercise native builds and JavaScript bindings", () => { + assert.deepEqual(classifyFiles(["crates/aplite/src/finite.rs"]), { + ...all, + docs: false, + scripts: false, + }); +}); + test("test runner configuration changes exercise Rust", () => { assert.deepEqual(classifyFiles([".config/nextest.toml"]), { ...all, diff --git a/scripts/ci-lydite-changes.test.mjs b/scripts/ci-lydite-changes.test.mjs index 2a31c7d37f1..6a153af2a8e 100644 --- a/scripts/ci-lydite-changes.test.mjs +++ b/scripts/ci-lydite-changes.test.mjs @@ -313,8 +313,11 @@ test("normal CI and standalone core conformance never build the bridge", () => { }); // The extracted solver is tested directly as well as through its proof consumers. -test("Aplite runs its own tests in the Lydite lane", () => { +test("Aplite changes test both proof and simulation consumers", () => { const workflow = readFileSync(new URL("../.github/workflows/lydite-checks.yml", import.meta.url), "utf8"); assert.match(workflow, /cargo test --locked .* -p aplite/); - assert.deepEqual(celoxRustTestScope(["crates/aplite/src/finite.rs"], packages).packages ?? [], []); + const selected = celoxRustTestScope(["crates/aplite/src/finite.rs"], packages).packages; + for (const name of ["aplite", "celox-heap", "celox", "celox-napi"]) + assert.ok(selected.includes(name), name); + assert.ok(selected.every(name => !isLydite(name))); }); diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 890afaef325..d57887307df 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -18,6 +18,7 @@ fi crates=( celox-sv-syntax celox-design + celox-heap celox-sv-analyzer celox-test-suite celox-analysis @@ -25,7 +26,6 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen - celox-heap celox-testbench celox-sir celox-state-layout diff --git a/scripts/publish-crates.test.mjs b/scripts/publish-crates.test.mjs index 9e8025385eb..7fadfe12418 100644 --- a/scripts/publish-crates.test.mjs +++ b/scripts/publish-crates.test.mjs @@ -120,6 +120,12 @@ test("publication order includes every public crate after its workspace dependen for (const [index, name] of order.entries()) { for (const dependency of packages.get(name).dependencies) { if (!dependency.path) continue; + // Aplite has an independent release train and must already be available + // on crates.io before publishing a Celox version that depends on it. + if (dependency.name === "aplite") { + assert.equal(dependency.req, `^${packages.get("aplite").version}`); + continue; + } const dependencyIndex = order.indexOf(dependency.name); assert.ok( dependencyIndex >= 0 && dependencyIndex < index,