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 2ff45141965..6891ab9925b 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/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index aea0736743f..1d0a8c7d61a 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -164,6 +164,19 @@ the initial 28 upstream checks passed. Arity and void-result rejection remain ch Queue slices, queue operands in concatenations, element-reference persistence, warning diagnostics, and queries on nonintegral pop results remain outside this change's support contract. +Logical equivalence (`<->`) now passes six generated cases in both state modes. +The binary-operator case passes elaboration; the five logical-operator cases +execute simulations and pass their assertions. A full run before the container +method changes above changed only these twelve verdicts, with no passing case +regressing: 1,208 cases pass in 2state and 1,219 in 4state. Shared tests cover unknown operands and +evaluate both operands exactly once (IEEE 1800-2023 11.4.7). + +Logical implication (`->`) now passes six generated cases in both state modes. +The binary-operator case passes elaboration; the five logical-operator cases +execute simulations and pass their assertions. A full run before the container +method changes above changed only these twelve verdicts, with no passing case +regressing: 1,208 cases pass in 2state and 1,219 in 4state. Shared tests also cover short-circuiting and +unknown operands (IEEE 1800-2023 11.4.7). ## Running locally diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 547a5dcf84c..89501cb5d10 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1817,10 +1817,10 @@ generated/binary_op/11.4.6--binary_op_wild_neq.sv 2state pass generated/binary_op/11.4.6--binary_op_wild_neq.sv 4state pass generated/binary_op/11.4.7--binary_op_log_and.sv 2state pass generated/binary_op/11.4.7--binary_op_log_and.sv 4state pass -generated/binary_op/11.4.7--binary_op_log_equiv.sv 2state fail -generated/binary_op/11.4.7--binary_op_log_equiv.sv 4state fail -generated/binary_op/11.4.7--binary_op_log_imp.sv 2state fail -generated/binary_op/11.4.7--binary_op_log_imp.sv 4state fail +generated/binary_op/11.4.7--binary_op_log_equiv.sv 2state pass +generated/binary_op/11.4.7--binary_op_log_equiv.sv 4state pass +generated/binary_op/11.4.7--binary_op_log_imp.sv 2state pass +generated/binary_op/11.4.7--binary_op_log_imp.sv 4state pass generated/binary_op/11.4.7--binary_op_log_or.sv 2state pass generated/binary_op/11.4.7--binary_op_log_or.sv 4state pass generated/binary_op/11.4.8--binary_op_bit_and.sv 2state pass @@ -2451,22 +2451,22 @@ generated/keywords/5.6.2--keyword_xnor.sv 2state pass generated/keywords/5.6.2--keyword_xnor.sv 4state pass generated/keywords/5.6.2--keyword_xor.sv 2state pass generated/keywords/5.6.2--keyword_xor.sv 4state pass -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 4state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 2state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 4state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_1.sv 2state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_1.sv 4state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state fail -generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state fail +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 4state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 2state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 4state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_1.sv 2state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_1.sv 4state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state pass +generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state pass generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state pass generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state pass generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state pass @@ -2647,10 +2647,10 @@ generated/sampled_functions/20.13--steady_gclk.sv 2state fail generated/sampled_functions/20.13--steady_gclk.sv 4state fail generated/simple_logical_operators_sim/11.4.7--simple_and_logical_operator.sv 2state pass generated/simple_logical_operators_sim/11.4.7--simple_and_logical_operator.sv 4state pass -generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 2state fail -generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 4state fail -generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 2state fail -generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 4state fail +generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 2state pass +generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 4state pass +generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 2state pass +generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 4state pass generated/simple_logical_operators_sim/11.4.7--simple_or_logical_operator.sv 2state pass generated/simple_logical_operators_sim/11.4.7--simple_or_logical_operator.sv 4state pass generated/trig_functions/20.8--acos.sv 2state pass diff --git a/crates/celox-backend-x86/src/backend/native/isel.rs b/crates/celox-backend-x86/src/backend/native/isel.rs index e4da6840d2a..798f1615f56 100644 --- a/crates/celox-backend-x86/src/backend/native/isel.rs +++ b/crates/celox-backend-x86/src/backend/native/isel.rs @@ -1480,10 +1480,6 @@ pub fn lower_execution_unit_with_diagnostics( sparse_write_states.metadata_action(sir_block_id, inst_idx), ); } - if cfg!(debug_assertions) { - ctx.verify_wide_values(); - } - // Track known bit width for redundant mask elimination. let dst_reg = inst.defined_register(); if let Some(dr) = dst_reg { @@ -1563,6 +1559,12 @@ pub fn lower_execution_unit_with_diagnostics( // Extract mask_map for phi node construction (ctx borrows func fields) let saved_mask_map = std::mem::replace(&mut ctx.mask_map, RegMap::new(0)); + // Each mutation validates its own entry. Scan the whole map once at + // the boundary rather than once per instruction, which is quadratic in + // large functions with many wide values. + if cfg!(debug_assertions) { + ctx.verify_wide_values(); + } let saved_wide_regs = std::mem::take(&mut ctx.wide_regs); let saved_wide_masks = std::mem::take(&mut ctx.wide_masks); drop(ctx); // Release borrows on func @@ -1758,6 +1760,11 @@ type WideMaskMap = crate::HashMap>; /// Tracks known constant values for SIR registers (for constant folding in ISel). type ConstMap = crate::HashMap; +#[cfg(test)] +thread_local! { + static WIDE_VALUE_VERIFICATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + struct ISelContext<'a> { vregs: &'a mut VRegAllocator, spill_descs: &'a mut Vec, @@ -2193,6 +2200,9 @@ impl<'a> ISelContext<'a> { if width <= 64 { self.wide_regs.remove(®); } else { + if cfg!(debug_assertions) { + self.verify_wide_value(®, &chunks); + } self.wide_regs.replace(reg, chunks); } } @@ -2244,28 +2254,34 @@ impl<'a> ISelContext<'a> { /// this map through a direct insertion. fn verify_wide_values(&self) { for (reg, chunks) in self.wide_regs.iter() { - let width = self.sir_width(reg); - assert!( - width > 64, - "narrow SIR register r{} has a wide native representation (width={width})", - reg.0 - ); - let expected_chunks = Self::num_chunks(width); + self.verify_wide_value(reg, chunks); + } + } + + fn verify_wide_value(&self, reg: &RegisterId, chunks: &[(VReg, usize)]) { + #[cfg(test)] + WIDE_VALUE_VERIFICATIONS.with(|count| count.set(count.get() + 1)); + let width = self.sir_width(reg); + assert!( + width > 64, + "narrow SIR register r{} has a wide native representation (width={width})", + reg.0 + ); + let expected_chunks = Self::num_chunks(width); + assert_eq!( + chunks.len(), + expected_chunks, + "wide SIR register r{} has {} chunks, expected {expected_chunks}", + reg.0, + chunks.len() + ); + for (index, (_, chunk_width)) in chunks.iter().enumerate() { + let expected_width = width.saturating_sub(index * 64).min(64); assert_eq!( - chunks.len(), - expected_chunks, - "wide SIR register r{} has {} chunks, expected {expected_chunks}", - reg.0, - chunks.len() + *chunk_width, expected_width, + "wide SIR register r{} chunk {index} has width {chunk_width}, expected {expected_width}", + reg.0 ); - for (index, (_, chunk_width)) in chunks.iter().enumerate() { - let expected_width = width.saturating_sub(index * 64).min(64); - assert_eq!( - *chunk_width, expected_width, - "wide SIR register r{} chunk {index} has width {chunk_width}, expected {expected_width}", - reg.0 - ); - } } } diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 3f94d1bda99..e1b98ebefce 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -1463,3 +1463,44 @@ fn widened_zero_compares_equal_to_a_zero_wide_load() { assert_eq!(state[output_offset] & 1, 1, "four_state={four_state}"); } } + +#[cfg(debug_assertions)] +#[test] +fn wide_value_invariant_validation_scales_with_values() { + const COUNT: usize = 128; + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: (0..COUNT) + .map(|i| { + SIRInstruction::Imm( + RegisterId(i), + SIRValue::new_four_state(BigUint::from(i), BigUint::default()), + ) + }) + .collect(), + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: (0..COUNT) + .map(|i| (RegisterId(i), RegisterType::Logic { width: 65 })) + .collect(), + }; + WIDE_VALUE_VERIFICATIONS.with(|count| count.set(0)); + let _ = lower_execution_unit(&unit, &empty_layout(), false); + let checks = WIDE_VALUE_VERIFICATIONS.with(|count| count.get()); + assert!( + checks >= COUNT, + "the invariant must still be checked: {checks}" + ); + assert!( + checks <= 2 * COUNT, + "repeated whole-map validation: {checks}" + ); +} 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-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 4d5752d35ce..9bdc2f46418 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -42,6 +42,10 @@ pub enum FrontendWarningKind { MixedTimescale, #[error("`$size` on an interface array is a language extension")] InterfaceArrayQuery, + #[error( + "unindexed interface array parameter `{path}` uses the first declared element `{element}`" + )] + InterfaceArrayParameter { path: String, element: String }, /// IEEE 1800-2023 9.2.2.4 restricts writes by other processes. #[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")] MultipleAlwaysFfDrivers { module: String, signal: String }, @@ -101,6 +105,17 @@ pub(crate) fn analyzer_warnings( celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayQuery { site } => { (FrontendWarningKind::InterfaceArrayQuery, site.clone()) } + celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayParameter { + path, + element, + site, + } => ( + FrontendWarningKind::InterfaceArrayParameter { + path: path.clone(), + element: element.clone(), + }, + site.clone(), + ), celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => { (FrontendWarningKind::MixedTimescale, None) } @@ -155,6 +170,7 @@ impl miette::Diagnostic for FrontendWarning { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", FrontendWarningKind::InterfaceArrayQuery => "interface_array_query", + FrontendWarningKind::InterfaceArrayParameter { .. } => "interface_array_parameter", FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers", FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::InferredLatch => "inferred_latch", @@ -175,6 +191,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::InterfaceArrayQuery => { "interface arrays are not data arrays in IEEE 1800-2023 20.7; set interface_array_query=warn or allow for compatibility" } + FrontendWarningKind::InterfaceArrayParameter { .. } => { + "IEEE 1800-2023 23.6 requires an instance select before a member; set interface_array_parameter=warn or allow to use the first declared element" + } FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } 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/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index bf5a52b71b2..881680ca018 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -125,7 +125,9 @@ fn bind_in_context( operator, right, } => { - if constants::binary_op_from_text(operator).is_none() { + if !matches!(operator.as_str(), "->" | "<->") + && constants::binary_op_from_text(operator).is_none() + { return Ok(None); } jobs.push(Job::Binary(operator.clone())); @@ -366,9 +368,31 @@ fn bind_in_context( Job::Binary(op) => { let right = values.pop().ok_or_else(disagreement)?; let left = values.pop().ok_or_else(disagreement)?; + let left = if op == "->" || op == "<->" { + ConstExpr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(left), + } + } else { + left + }; + let right = if op == "<->" { + ConstExpr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(right), + } + } else { + right + }; values.push(ConstExpr::Binary { left: Box::new(left), - op: constants::binary_op_from_text(&op).ok_or_else(disagreement)?, + op: if op == "<->" { + BinaryOp::Eq + } else if op == "->" { + BinaryOp::LogicOr + } else { + constants::binary_op_from_text(&op).ok_or_else(disagreement)? + }, right: Box::new(right), }); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index c7416bb7102..16b2b487c85 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -960,14 +960,39 @@ pub(in crate::ast) fn bind_value( | ">=" | "&&" | "||" + | "->" + | "<->" ) { return Err(unsupported("operator on a real operand")); } + let implication = op == "->"; + let equivalence = op == "<->"; + let left = if implication || equivalence { + Expr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(left), + } + } else { + left + }; + // Each truth-value conversion evaluates its operand once (11.4.7). + let right = if equivalence { + Expr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(right), + } + } else { + right + }; let xnor = matches!(op.as_str(), "~^" | "^~"); let value = Expr::Binary { left: Box::new(left), - op: if xnor { + op: if equivalence { + BinaryOp::Eq + } else if implication { + BinaryOp::LogicOr + } else if xnor { BinaryOp::BitXor } else { constants::binary_op_from_text(&op) @@ -1389,6 +1414,7 @@ fn path( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted<(Vec, Option)> { + let authored = root; // A static class property is a variable of the module. if let Some(variable) = objects::static_property(tree, root, native, dimensions)? { return Ok((vec![variable], None)); @@ -1426,12 +1452,25 @@ fn path( let last = prefix.last_mut().ok_or_else(disagreement)?; last.push_str(&format!("[{value}]")); prefix.extend(parts.into_iter().rev()); + if base.is_none() + && let Some(name) = + interface_binding::unindexed_parameter(&prefix, tree, dimensions, authored) + { + return Ok((vec![name], None)); + } return Ok((prefix, base)); } _ => return Err(unsupported("member receiver")), } } parts.reverse(); + if qualified.is_none() + && let Some(name) = + interface_binding::unindexed_parameter(&parts, tree, dimensions, authored) + { + return Ok((vec![name], None)); + } + if let Some(length) = qualified { if parts.len() == length + 1 { let base = parts[..2].join("::"); diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 5b2ec074539..da526c4c675 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -33,6 +33,43 @@ pub(super) struct ArrayBinding { pub ranges: Vec<(i128, i128)>, } +/// Compatibility shorthand for an unindexed interface-array value parameter. +/// Follow the first element in declaration order, including nonzero bounds. +/// Runtime members and type parameters retain their ordinary indexed lookup. +pub(super) fn unindexed_parameter( + path: &[String], + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + root: celox_sv_syntax::ExprId, +) -> Option { + let (member, handle) = path.split_last()?; + let root_name = handle.first()?; + if dimensions.get(root_name).is_some() + || dimensions.const_env.contains_key(root_name) + || dimensions.parameter_values.contains_key(root_name) + { + return None; + } + let imported = scope::imported(&tree.state); + let array = imported.interface_arrays.get(&handle.join("."))?; + let element = array.elements.first()?; + let bound = imported + .interface_members + .get(&format!("{element}.{member}"))?; + if !imported.parameter_values.contains_key(bound) { + return None; + } + warnings::append( + &mut tree.state.diagnostics.borrow_mut(), + [warnings::AnalyzerWarning::InterfaceArrayParameter { + path: path.join("."), + element: element.clone(), + site: procedural::source_span(tree.declarations().expression(root).tokens, tree), + }], + ); + Some(bound.clone()) +} + pub(super) fn analyze_module( tree: &AnalysisContext<'_>, path: &Path, 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/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index c4924e34220..9d5372e82b8 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -10,6 +10,12 @@ pub enum AnalyzerWarning { MixedTimescale, /// `$size` on an interface array is a compatibility extension to 20.7. InterfaceArrayQuery { site: Option }, + /// Omitted interface array selections are an extension to 23.6. + InterfaceArrayParameter { + path: String, + element: String, + site: Option, + }, /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). ExitOutsideProgram { site: Option }, } 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/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index 78a54d85cf2..fceded314db 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1782,3 +1782,121 @@ endmodule (assert_eq hit 0) (assert_eq field_minus_one 0xffffffff) (assert_eq q 0xab)) + +(case logical_implication + ; IEEE 1800-2023 11.4.7: implication short-circuits for a false antecedent. + (source "logical_implication.sv" #" + module Top(input logic [3:0] a, input logic b, output logic y, + output logic hit, output logic constant_result); + localparam bit C = 2 -> 0; + function automatic logic mark(); + hit = 1; + return b; + endfunction + always_comb begin + hit = 0; + y = a -> mark(); + end + assign constant_result = C; + endmodule + "#) + (top Top) + (modify (set a 2) (set b 0)) + (assert_eq y 0) + (assert_eq hit 1) + (assert_eq constant_result 0) + (set a 0) + (assert_eq y 1) + (modify (set a 2) (set b 1)) + (assert_eq y 1)) + +(case logical_implication_unknown + (four_state) + (source "logical_implication_unknown.sv" #" + module Top(input logic a, input logic b, output logic y, output logic hit); + function automatic logic mark(); + hit = 1; + return b; + endfunction + always_comb begin + hit = 0; + y = a -> mark(); + end + endmodule + "#) + (top Top) + (set a (fourstate 1 1)) + (set b 0) + (assert_eq y (fourstate 1 1)) + (assert_eq hit 1) + (set b 1) + (assert_eq y 1) + (assert_eq hit 1)) + +(case logical_implication_short_circuit + (source "logical_implication_short_circuit.sv" #" + module Top(output logic hit, output logic y); + function automatic logic mark(); + hit = 1; + return 0; + endfunction + initial begin + hit = 0; + y = 1'b0 -> mark(); + end + endmodule + "#) + (top Top) + (assert_eq hit 0) + (assert_eq y 1)) + +(case logical_equivalence + (source "logical_equivalence.sv" #" + module Top(input logic [3:0] a, b, output logic y, output logic c); + localparam bit C = 4 <-> 2; + assign y = a <-> b; + assign c = C; + endmodule + "#) + (top Top) + (modify (set a 0) (set b 0)) + (assert_eq y 1) + (assert_eq c 1) + (modify (set a 2) (set b 0)) + (assert_eq y 0) + (modify (set a 2) (set b 4)) + (assert_eq y 1) + (modify (set a 0) (set b 4)) + (assert_eq y 0)) + +(case logical_equivalence_unknown + (four_state) + (source "logical_equivalence_unknown.sv" #" + module Top(input logic [1:0] a, b, output logic y); + assign y = a <-> b; + endmodule + "#) + (top Top) + (modify (set a (fourstate 1 1)) (set b 0)) + (assert_eq y (fourstate 1 1)) + (set b 1) + (assert_eq y (fourstate 1 1)) + (set a (fourstate 3 1)) + (assert_eq y 1)) + +(case logical_equivalence_evaluates_operands_once + (source "logical_equivalence_calls.sv" #" + module Top(output logic [7:0] a_count, b_count, output logic y); + function automatic logic left(); a_count = a_count + 1; return 0; endfunction + function automatic logic right(); b_count = b_count + 1; return 1; endfunction + initial begin + a_count = 0; + b_count = 0; + y = left() <-> right(); + end + endmodule + "#) + (top Top) + (assert_eq a_count 1) + (assert_eq b_count 1) + (assert_eq y 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv b/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv new file mode 100644 index 00000000000..eaf5c845486 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv @@ -0,0 +1,11 @@ +module top; + int a_count = 0, b_count = 0; + function automatic bit left(); a_count++; return 0; endfunction + function automatic bit right(); b_count++; return 1; endfunction + initial begin + bit y; + y = left() <-> right(); + $display("y=%0d a=%0d b=%0d", y, a_count, b_count); + $finish; + end +endmodule 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..a3597307bc6 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1,4 +1,21 @@ [ + { + "id": "sv_verilator_logical_equivalence_side_effects", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "upstream": [], + "evidence": [ + "verification/repros/sv_logical_equivalence_once.sv", + "src/sv/cases/operators.vtest" + ], + "cases": { + "verilator": [ + "operators::logical_equivalence_evaluates_operands_once" + ] + } + }, { "id": "sv_static_function_result_lifetime", "category": "simulator_disagreement", @@ -2578,5 +2595,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-test-suite/verification/sv/verilator/operators.json b/crates/celox-test-suite/verification/sv/verilator/operators.json index 0a9e2636556..a71785fcc6f 100644 --- a/crates/celox-test-suite/verification/sv/verilator/operators.json +++ b/crates/celox-test-suite/verification/sv/verilator/operators.json @@ -44,6 +44,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Operators", + "detail": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_logical_equivalence_once.sv", + "src/sv/cases/operators.vtest" + ], + "id": "sv_verilator_logical_equivalence_side_effects", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "upstream": [] + }, + "name": "operators::logical_equivalence_evaluates_operands_once", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Operators", "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/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index dc58a639307..d00d5e69359 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -86,6 +86,7 @@ impl DiagnosticPolicy { code, "mixed_timescale" | "interface_array_query" + | "interface_array_parameter" | "unpacked_port_default" | "multiple_always_ff_drivers" | "inferred_latch" diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index ffbc6bc5658..8896d12923a 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -734,3 +734,71 @@ fn invalid_interface_array_query_dimensions_return_integer_unknowns() { ); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_array_parameters_have_a_located_recoverable_diagnostic() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=8); logic [WIDTH-1:0] v; endinterface + module Top(output wire [31:0] q); Bus #(13) bus[5:4](); assign q=bus.WIDTH; endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, Path::new("array_parameter.sv"))], "Top"); + let error = build().build_cranelift().err().unwrap(); + assert!( + matches!(error.kind(), SimulatorErrorKind::DiagnosticPolicy(_)), + "{error}" + ); + assert!( + error.to_string().contains("interface_array_parameter"), + "{error}" + ); + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let mut sim = build() + .diagnostic_policy(policy("interface_array_parameter", level)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 13u8.into()); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + if let Some(warning) = sim.warnings().first() { + let rendered = celox::render_diagnostic(warning); + assert!(rendered.contains("array_parameter.sv"), "{rendered}"); + assert!(rendered.contains("bus[5]"), "{rendered}"); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_parameter_lookup_respects_lexical_shadowing() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=13); endinterface + module Top(output wire [31:0] q); + Bus bus[2](); + typedef struct packed {logic [7:0] WIDTH;} Word; + function automatic int f(input Word bus); return bus.WIDTH; endfunction + localparam VALUE=f(8'd42); assign q=VALUE; endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("shadowed_bus.sv"))], "Top") + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 42u8.into()); + assert!(sim.warnings().is_empty()); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_parameters_resolve_inside_indexed_generate_paths() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=8); endinterface + module Top(output wire [31:0] q); + for(genvar i=0;i<2;i=i+1) begin:g Bus #(10+i) bus[5:4](); end + assign q=g[1].bus.WIDTH; endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("generated_bus.sv"))], "Top") + .diagnostic_policy(policy("interface_array_parameter", DiagnosticLevel::Warn)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 11u8.into()); + assert_eq!(sim.warnings().len(), 1); +} 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/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index bd1bc1737c5..984d742005a 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -280,3 +280,41 @@ fn rejects_interface_array_slices_in_multiple_dimensions() { "{error}" ); } + +// The unindexed value-parameter shorthand is an explicit compatibility mode. +sv_backends! { + fn unindexed_interface_array_parameters_preserve_bound_values_and_types(sim) { + @setup { + let source = "interface Bus #(parameter int WIDTH=8, parameter logic signed [7:0] NEG=-3); + logic [WIDTH-1:0] data; modport sink(input data); endinterface + module Child(Bus.sink bus[5:4], output wire [31:0] q, n); + function automatic int width_value(); return bus.WIDTH; endfunction + localparam W=width_value(); + assign q=W; + assign n=bus.NEG; + endmodule + module Top(output wire [31:0] q,n); + Bus #(13,-5) buses[5:4](); Child dut(buses,q,n); + endmodule"; + let mut policy=celox::DiagnosticPolicy::default(); + policy.set("interface_array_parameter",celox::DiagnosticLevel::Allow); + } + @build Simulator::from_sv_sources(vec![(source,Path::new("array_parameter_types.sv"))],"Top").diagnostic_policy(policy); + assert_eq!(sim.get(sim.signal("q")),BigUint::from(13u8)); + assert_eq!(sim.get(sim.signal("n")),BigUint::from(0xfffffffbu32)); + } +} + +#[test] +fn interface_array_parameter_shorthand_does_not_bind_runtime_members() { + let source = "interface Bus #(parameter WIDTH=8); logic [WIDTH-1:0] data; endinterface + module Top(output wire [7:0] q); Bus bus[2](); assign q=bus.data; endmodule"; + let mut policy = celox::DiagnosticPolicy::default(); + policy.set("interface_array_parameter", celox::DiagnosticLevel::Allow); + let error = Simulator::from_sv_sources(vec![(source, Path::new("array_signal.sv"))], "Top") + .diagnostic_policy(policy) + .build_cranelift() + .err() + .unwrap(); + assert!(error.to_string().contains("bus.data"), "{error}"); +} diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index d19f42f5af4..7be6789e3d7 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,10 @@ sv_backends! { + fn logical_equivalence(sim) { @case "operators::logical_equivalence"; } + fn logical_equivalence_unknown(sim) { @case "operators::logical_equivalence_unknown"; } + fn logical_equivalence_evaluates_operands_once(sim) { @case "operators::logical_equivalence_evaluates_operands_once"; } + fn logical_implication_short_circuit(sim) { @case "operators::logical_implication_short_circuit"; } + fn logical_implication_unknown(sim) { @case "operators::logical_implication_unknown"; } + fn logical_implication(sim) { @case "operators::logical_implication"; } fn casts_preserve_guarded_division_signedness(sim) { @case "operators::casts_preserve_guarded_division_signedness"; } diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 3b54313138e..5a8c51d7b07 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -183,6 +183,14 @@ interface_array_query = "warn" The CLI uses the same policy: `celox run top.sv --top Top --diagnostic interface_array_query=warn`. +`interface_array_parameter` also defaults to `error`. Set it to `warn` or `allow` +for the compatibility shorthand `bus.WIDTH` when `bus` is an interface array. +It reads the value parameter from the first element in declaration order, +including arrays with nonzero bounds. Signals and type parameters still require +an explicit element selection. The same setting works in `[diagnostics]` and +with `--diagnostic interface_array_parameter=warn`. + + `multiple_always_ff_drivers` defaults to `error` for shared memories written by an `always_ff` and another edge process (IEEE 1800-2023 §9.2.2.4). With `warn` or `allow`, Celox stages their nonblocking writes in sparse next-state storage diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7eefdc84c57..6cb69aeb320 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..1af4a631c18 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", @@ -162,6 +161,14 @@ export function classifyFiles(files, { releasePlease = false } = {}) { continue; } + // Aplite has an independent release manifest. Its release notes and + // manifest need repository-policy checks, not a product rebuild. Keep + // source, Cargo.toml and Cargo.lock changes on their normal paths below. + if ([".release-please-aplite-manifest.json", "crates/aplite/CHANGELOG.md"].includes(path)) { + affected.scripts = true; + continue; + } + if (isRustOnlyPath(path)) { affected.rust = true; continue; @@ -309,8 +316,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..16f53c40c24 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", @@ -70,6 +69,22 @@ test("Rust test infrastructure skips bindings while retaining Rust checks", () = } }); +test("Aplite release metadata runs policy checks without rebuilding products", () => { + const metadata = [".release-please-aplite-manifest.json", "crates/aplite/CHANGELOG.md"]; + for (const files of [metadata, ...metadata.map(path => [path])]) { + for (const releasePlease of [false, true]) + assert.deepEqual(classifyFiles(files, { releasePlease }), { ...none, scripts: true }); + } + for (const path of ["crates/aplite/src/lib.rs", "crates/aplite/Cargo.toml", "Cargo.lock"]) { + assert.deepEqual( + classifyFiles([...metadata, path]), + { ...classifyFiles([path]), scripts: true }, + path, + ); + assert.equal(classifyFiles([...metadata, path]).rust, true, path); + } +}); + test("manifests and mixed runtime changes retain binding validation", () => { for (const path of [ "Cargo.toml", @@ -355,6 +370,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,