diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 2784a824630..ad0ca48546b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -273,6 +273,12 @@ impl<'p, 'a> Ff<'p, 'a> { } continue; } + sv::ir::Callee::Object(op) if matches!(*op, sv::ir::ObjectOp::New { .. }) => { + // Constructor seeding consumes the process RNG. Register it + // before lower_process freezes the persistent target ranges. + self.urandom_state(); + continue; + } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 4ea69cf98bb..ac966cb01e3 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -32,6 +32,11 @@ impl Ff<'_, '_> { let size = self.constant64(u64::from(*size)); let object = self.heap_call(ops::encode(ops::OBJECT_NEW, u64::from(*class)), &[size]); + // Object seeding consumes the creating process's RNG once, + // before the constructor body (IEEE 1800-2023 18.14.3). + let seed = self.urandom(None)?; + let seed = self.integer_of_width(&seed, 32, false)?; + self.heap_call(ops::OBJECT_SEED, &[object, seed]); for &(offset, kind) in handles { let offset = self.constant64(u64::from(offset)); let kind = self.constant64(match kind { @@ -55,6 +60,49 @@ impl Ff<'_, '_> { let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?; self.heap_call(ops::OBJECT_STORE, &[object, place, value]) } + ObjectOp::Random + | ObjectOp::Check(_) + | ObjectOp::ModeGet(..) + | ObjectOp::ModePush + | ObjectOp::ModePop + | ObjectOp::ModeSelected(_) => { + let object = self.handle(&args[0])?; + self.heap_call( + match op { + ObjectOp::Check(class) => ops::encode(ops::OBJECT_CHECK, u64::from(*class)), + ObjectOp::ModeGet(offset, random) => ops::encode( + ops::OBJECT_MODE_GET, + u64::from(*offset) | (u64::from(*random) << 32), + ), + ObjectOp::ModePush => ops::OBJECT_MODE_PUSH, + ObjectOp::ModePop => ops::OBJECT_MODE_POP, + ObjectOp::ModeSelected(offset) => { + ops::encode(ops::OBJECT_MODE_SELECTED, u64::from(*offset)) + } + _ => ops::OBJECT_RANDOM, + }, + &[object], + ) + } + ObjectOp::ModeSet(offset) | ObjectOp::ModeSelect(offset, _) => { + let object = self.handle(&args[0])?; + let enabled = self.integer_of_width(&args[1], 1, false)?; + self.heap_call( + match op { + ObjectOp::ModeSelect(_, random) => ops::encode( + ops::OBJECT_MODE_SELECT, + u64::from(*offset) | (u64::from(*random) << 32), + ), + _ => ops::encode(ops::OBJECT_MODE_SET, u64::from(*offset)), + }, + &[object, enabled], + ) + } + ObjectOp::Seed => { + let object = self.handle(&args[0])?; + let seed = self.integer_of_width(&args[1], 32, false)?; + self.heap_call(ops::OBJECT_SEED, &[object, seed]) + } ObjectOp::ClassOf => { let object = self.handle(&args[0])?; self.heap_call(ops::OBJECT_CLASS, &[object]) @@ -70,7 +118,17 @@ impl Ff<'_, '_> { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, }), - ObjectOp::Store(_) | ObjectOp::ClassOf => None, + ObjectOp::Store(_) + | ObjectOp::ClassOf + | ObjectOp::Random + | ObjectOp::Seed + | ObjectOp::Check(_) + | ObjectOp::ModeGet(..) + | ObjectOp::ModePush + | ObjectOp::ModePop + | ObjectOp::ModeSelect(..) + | ObjectOp::ModeSelected(_) + | ObjectOp::ModeSet(_) => None, }; if let Some(kind) = kind { self.m.variables.get_mut(&temp).unwrap().value_kind = kind; diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 644e75b2a20..9d708fe87c1 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -150,14 +150,17 @@ impl Heap { self.strings.contains_key(&handle) } - /// Whether `other` holds the same strings under the same handles, the - /// same strings under construction, and names new strings alike. + /// Whether `other` holds the same strings and objects under the same + /// handles, including object RNG state and strings under construction, + /// and assigns the same handles to future allocations. pub fn same_contents(&self, other: &Heap) -> bool { self.strings == other.strings && self.next == other.next && self.buffers == other.buffers && self.free_buffers == other.free_buffers && self.pinned == other.pinned + && self.objects == other.objects + && self.next_object == other.next_object } /// The number of live strings, including `""`. @@ -261,6 +264,61 @@ impl Heap { mod tests { use super::*; + #[test] + fn comparison_detects_object_rng_divergence_before_a_property_write() { + let mut heap = Heap::new(); + let object = heap.new_object(7, 8); + heap.seed_object(object, 42); + let mut other = heap.clone(); + assert!(heap.same_contents(&other)); + let drawn = other.random_object(object); + assert_eq!(heap.load(object, 0, 8), other.load(object, 0, 8)); + assert!(!heap.same_contents(&other)); + assert_eq!(heap.random_object(object), drawn); + assert!(heap.same_contents(&other)); + } + + #[test] + fn comparison_detects_object_contents_and_allocation_state() { + let mut heap = Heap::new(); + let object = heap.new_object(7, 8); + let mut other = heap.clone(); + other.store(object, 0, 8, 99); + assert!(!heap.same_contents(&other)); + heap.store(object, 0, 8, 99); + assert!(heap.same_contents(&other)); + other.new_object(7, 8); + other.collect([Root::object(object)]); + // The same live object remains, but future allocation handles differ. + assert!(!heap.same_contents(&other)); + } + + #[test] + fn random_modes_restore_nested_scopes_and_participate_in_comparisons() { + let mut heap = Heap::new(); + let object = heap.new_object(1, 16); + assert!(heap.random_mode(object, 0, true)); + assert!(!heap.random_mode(object, 8, false)); + let original = heap.clone(); + heap.set_random_mode(object, 0, false); + assert!(!heap.same_contents(&original)); + let disabled = heap.clone(); + heap.push_random_modes(object); + heap.select_random_mode(object, 0, true, true); + heap.select_random_mode(object, 8, false, true); + assert!(heap.selected_random_mode(object, 8)); + assert!(heap.random_mode(object, 8, false)); + let outer = heap.clone(); + heap.push_random_modes(object); + heap.select_random_mode(object, 8, false, false); + assert!(!heap.selected_random_mode(object, 8)); + assert!(!heap.random_mode(object, 8, false)); + heap.pop_random_modes(object); + assert!(heap.same_contents(&outer)); + heap.pop_random_modes(object); + assert!(heap.same_contents(&disabled)); + } + #[test] fn interning_gives_equal_contents_equal_handles() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 112083a86af..b7d294c8964 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -11,14 +11,24 @@ use crate::{Handle, HandleKind, Heap}; /// The handle of `null`, the value of zero-initialized memory. pub const NULL: Handle = 0; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Object { class: u32, + random_state: u64, + random_modes: RandomModes, + saved_random_modes: Vec, bytes: Box<[u8]>, /// Byte offsets of the handle properties, with what they refer to. pub(crate) handles: Vec<(u32, HandleKind)>, } +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RandomModes { + overrides: fxhash::FxHashMap, + /// Non-rand properties temporarily made random by an argument list. + selected: fxhash::FxHashSet, +} + impl Object { pub(crate) fn size(&self) -> usize { self.bytes.len() @@ -32,12 +42,17 @@ pub enum Fault { /// A property access or method call through `null` or a handle of no /// live object (IEEE 1800-2023 8.4). NullDereference, + /// The first randomization subset does not implement virtual dispatch. + RandomizationClassMismatch, } impl std::fmt::Display for Fault { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NullDereference => f.write_str("null object handle dereferenced"), + Self::RandomizationClassMismatch => { + f.write_str("class randomization through a base handle is unsupported") + } } } } @@ -53,6 +68,9 @@ impl Heap { handle, Object { class, + random_state: 0, + random_modes: RandomModes::default(), + saved_random_modes: Vec::new(), bytes: vec![0; size].into(), handles: Vec::new(), }, @@ -61,6 +79,87 @@ impl Heap { handle } + /// Seed an object's independent random stream (IEEE 1800-2023 18.13.3). + pub fn seed_object(&mut self, handle: Handle, seed: u32) { + if let Some(object) = self.object_mut(handle) { + object.random_state = u64::from(seed); + } + } + + /// SplitMix64: a full-period state transition with a bijective output + /// permutation, including seed zero. The language does not fix the RNG. + pub fn random_object(&mut self, handle: Handle) -> u64 { + let Some(object) = self.object_mut(handle) else { + return 0; + }; + object.random_state = object.random_state.wrapping_add(0x9e3779b97f4a7c15); + let mut word = object.random_state; + word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); + word ^ (word >> 31) + } + + /// Random properties start enabled. Modes are shared by aliases of an + /// object and are part of its checkpoint and differential state. + pub fn random_mode(&mut self, handle: Handle, offset: u32, random: bool) -> bool { + self.object_mut(handle).is_some_and(|object| { + object + .random_modes + .overrides + .get(&offset) + .copied() + .unwrap_or(random) + }) + } + + pub fn set_random_mode(&mut self, handle: Handle, offset: u32, enabled: bool) { + if let Some(object) = self.object_mut(handle) { + object.random_modes.overrides.insert(offset, enabled); + } + } + + pub fn push_random_modes(&mut self, handle: Handle) { + if let Some(object) = self.object_mut(handle) { + object.saved_random_modes.push(object.random_modes.clone()); + } + } + + pub fn pop_random_modes(&mut self, handle: Handle) { + if let Some(object) = self.object_mut(handle) { + object.random_modes = object + .saved_random_modes + .pop() + .expect("paired random mode scope"); + } + } + + pub fn select_random_mode(&mut self, handle: Handle, offset: u32, random: bool, enabled: bool) { + if let Some(object) = self.object_mut(handle) { + object.random_modes.overrides.insert(offset, enabled); + if enabled && !random { + object.random_modes.selected.insert(offset); + } else { + object.random_modes.selected.remove(&offset); + } + } + } + + pub fn selected_random_mode(&mut self, handle: Handle, offset: u32) -> bool { + self.object_mut(handle) + .is_some_and(|object| object.random_modes.selected.contains(&offset)) + } + + pub(crate) fn check_object(&mut self, handle: Handle, class: u32) -> bool { + let Some(object) = self.object_mut(handle) else { + return false; + }; + if class != 0 && object.class != class { + self.fault.get_or_insert(Fault::RandomizationClassMismatch); + return false; + } + true + } + /// Declare that the property of `object` at byte `offset` holds a handle /// of `kind`. pub fn declare_handle(&mut self, object: Handle, offset: u32, kind: HandleKind) { @@ -183,3 +282,31 @@ mod tests { assert!(!heap.contains(text)); } } + +#[cfg(test)] +mod random_tests { + use super::*; + + #[test] + fn random_streams_are_independent_and_checkpointed() { + let mut heap = Heap::new(); + let a = heap.new_object(1, 1); + let b = heap.new_object(1, 1); + heap.seed_object(a, 0); + heap.seed_object(b, 0); + let first = heap.random_object(a); + for _ in 0..10 { + heap.random_object(a); + } + assert_eq!(first, heap.random_object(b)); + heap.seed_object(a, 0); + assert_eq!(first, heap.random_object(a)); + let mut snapshot = heap.clone(); + for _ in 0..20 { + assert_eq!(heap.random_object(a), snapshot.random_object(a)); + } + assert_eq!(heap.take_fault(), None); + heap.random_object(NULL); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + } +} diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index e8680035a1f..9c38b6a00e0 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -61,6 +61,24 @@ pub const OBJECT_LOAD: u64 = 50; pub const OBJECT_STORE: u64 = 51; /// `class_of(object)`: its class, or 0 for `null`. pub const OBJECT_CLASS: u64 = 52; +/// `random(object)`: 64 random bits from the object's RNG. +pub const OBJECT_RANDOM: u64 = 53; +/// `seed(object, seed)`: reset the object's RNG using the low 32 bits. +pub const OBJECT_SEED: u64 = 54; +/// `check(object)`: record a fault for an invalid receiver or, when the +/// parameter is nonzero, a different runtime class. Return 1 on success, 0 on failure. +pub const OBJECT_CHECK: u64 = 55; +/// Query the random mode of the property at the parameter's byte offset. +pub const OBJECT_MODE_GET: u64 = 56; +/// Set the random mode at the parameter's byte offset from the low bit of b. +pub const OBJECT_MODE_SET: u64 = 57; +/// Save/restore random modes around an inline member selection. +pub const OBJECT_MODE_PUSH: u64 = 58; +pub const OBJECT_MODE_POP: u64 = 59; +/// Install a selected mode; parameter bit 32 records a declared rand property. +pub const OBJECT_MODE_SELECT: u64 = 60; +/// Whether a non-rand property is temporarily random in the active scope. +pub const OBJECT_MODE_SELECTED: u64 = 61; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -168,6 +186,39 @@ impl Heap { 0 } OBJECT_CLASS => self.class_of(a as Handle).into(), + OBJECT_RANDOM => self.random_object(a as Handle), + OBJECT_SEED => { + self.seed_object(a as Handle, b as u32); + 0 + } + OBJECT_CHECK => u64::from(self.check_object(a as Handle, parameter as u32)), + OBJECT_MODE_GET => { + u64::from(self.random_mode(a as Handle, parameter as u32, parameter >> 32 != 0)) + } + OBJECT_MODE_SET => { + self.set_random_mode(a as Handle, parameter as u32, b & 1 != 0); + 0 + } + OBJECT_MODE_PUSH => { + self.push_random_modes(a as Handle); + 0 + } + OBJECT_MODE_POP => { + self.pop_random_modes(a as Handle); + 0 + } + OBJECT_MODE_SELECT => { + self.select_random_mode( + a as Handle, + parameter as u32, + parameter >> 32 != 0, + b & 1 != 0, + ); + 0 + } + OBJECT_MODE_SELECTED => { + u64::from(self.selected_random_mode(a as Handle, parameter as u32)) + } other => panic!("unknown heap operation {other}"), } } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index aea08638043..a44fee5735b 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -22,8 +22,14 @@ pub(super) const THIS: &str = "this"; #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Property { pub name: String, + pub owner: String, + pub constant: bool, + pub local: bool, + pub protected: bool, pub r#type: Type, pub field: ObjectField, + pub rand: bool, + pub randc: bool, /// The initializer of the declaration, evaluated by the constructor. pub initializer: Option, } @@ -88,9 +94,57 @@ pub(super) struct Class { pub methods: Vec, /// Bytes of an object. pub size: u32, + pub has_constraints: bool, +} + +/// An internal unsigned packed argument of a generated method. +pub(super) fn unsigned_type(width: usize) -> Type { + let mut ty = procedural::int_type(); + ty.is_signed = false; + ty.packed_ranges = vec![PackedRange::new( + ConstExpr::Literal((width - 1).to_string()), + ConstExpr::Literal("0".into()), + )]; + ty } impl Class { + pub fn selection_type(&self) -> Type { + unsigned_type(self.properties.len() + 1) + } + + /// Validate the supported unconstrained subset before binding a call. + pub fn check_randomize(&self, tree: &AnalysisContext<'_>) -> Converted<()> { + if self.has_constraints { + return Err(unsupported("class randomize with constraints")); + } + for property in &self.properties { + if property.randc { + return Err(unsupported("class randomize with randc properties")); + } + if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) { + return Err(unsupported( + "class randomize requires integral non-enum rand properties", + )); + } + } + for hook in ["pre_randomize", "post_randomize"] { + if let Some(method) = self.method(hook) { + let native = tree.declarations().subroutine(method.native); + if native.kind != celox_sv_syntax::SubroutineKind::Function + || native.ports.as_ref().is_some_and(|ports| !ports.is_empty()) + || method.qualifiers.is_static + || method.qualifiers.is_virtual + { + return Err(unsupported( + "randomization hooks require non-static, non-virtual functions without arguments", + )); + } + } + } + Ok(()) + } + /// The property `name`; one the class declares hides one of a base /// (IEEE 1800-2023 8.14). pub fn property(&self, name: &str) -> Option<&Property> { @@ -358,6 +412,14 @@ pub(super) fn class( .unwrap_or_default(); let mut size = base.as_ref().map_or(0, |base| base.size); for property in &declaration.properties { + if property.declaration.constant && (property.qualifiers.rand || property.qualifiers.randc) + { + return Err(unsupported("const random class property")); + } + if property.qualifiers.is_static && (property.qualifiers.rand || property.qualifiers.randc) + { + return Err(unsupported("static random class property")); + } let ty = type_binding::procedural_type( property.declaration.data_type, native, @@ -382,13 +444,20 @@ pub(super) fn class( }); continue; } + let owner = name.to_owned(); let name = property_name; let field = field(&tree.state, &ty, env, size)?; size = field.offset + field.bytes(); properties.push(Property { name, + owner, + constant: property.declaration.constant, + local: property.qualifiers.local, + protected: property.qualifiers.protected, r#type: ty.clone(), field, + rand: property.qualifiers.rand, + randc: property.qualifiers.randc, initializer: variable.value, }); } @@ -403,6 +472,11 @@ pub(super) fn class( for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); + if matches!(method_name.as_str(), "randomize" | "srandom" | "rand_mode") { + return Err(unsupported( + "overriding built-in class randomization methods", + )); + } // A method overriding a virtual method is virtual (8.20). let is_virtual = method.qualifiers.is_virtual || methods @@ -477,6 +551,8 @@ pub(super) fn class( let class = Rc::new(Class { name: name.to_owned(), id: class_id(name), + has_constraints: declaration.has_constraints + || base.as_ref().is_some_and(|base| base.has_constraints), base: base.map(|base| base.name.clone()), interfaces, is_abstract: declaration.virtual_class, @@ -561,6 +637,7 @@ fn interface_class( interfaces, is_abstract: true, is_interface: true, + has_constraints: false, properties: Vec::new(), base_properties: 0, statics: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index f7adf4d54f9..20a1d7b4f05 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -469,6 +469,46 @@ fn class_signatures( context, ); } + for method in ["randomize", "srandom", "rand_mode"] { + let mut formals = vec![( + FunctionArgumentMetadata { + name: classes::THIS.into(), + direction: ParamDirection::Input, + has_default: false, + }, + handle.clone(), + )]; + let (argument, ty) = match method { + "randomize" => ( + "$selection", + // Signature discovery must not require an otherwise unused class + // to have a supported layout. A call validates the layout before + // using this selection formal; lowering reports layout errors. + classes::class(tree, &class_name, &context.const_env, &context.type_aliases) + .map_or_else( + |_| classes::unsigned_type(1), + |layout| layout.selection_type(), + ), + ), + "srandom" => ("seed", procedural::int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + formals.push(( + FunctionArgumentMetadata { + name: argument.into(), + direction: ParamDirection::Input, + has_default: false, + }, + ty, + )); + publish_signature( + classes::Class::subroutine_name(&class_name, method), + formals, + Some((method == "randomize").then(procedural::int_type)), + tree, + context, + ); + } if !constructor && !class.interface { publish_signature( classes::Class::subroutine_name(&class_name, "new"), diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 0e3c5c64a85..90550ded28a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -17,8 +17,8 @@ pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, check_assignment as check_handle_assignment, constructor as object_constructor, - method as object_method, property as object_property, receiver as object_receiver, - this as object_this, + method as object_method, property as object_property, rand_mode_call as object_rand_mode_call, + receiver as object_receiver, this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, 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 353394f99bd..9ebd6e1001e 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -240,6 +240,7 @@ enum Finish { name: String, formals: usize, receiver: objects::Receiver, + selection: Option, }, } @@ -265,6 +266,10 @@ pub(in crate::ast) fn bind_value( match job { Job::Enter(id, target, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); + if let Some(call) = objects::rand_mode_call(tree, id, native, dimensions, false)? { + values.push(call); + continue; + } if timescales::is_query(id, native) { values.push(Expr::Literal(parameters::format_typed_parameter_literal( i128::from(timescales::query(id, tree)?), @@ -413,14 +418,24 @@ pub(in crate::ast) fn bind_value( let (name, formals, receiver) = objects::method(tree, *expression, native, dimensions)? .expect("checked by the guard"); - if args.len() > formals || args.iter().any(|arg| arg.name.is_some()) { + let selection = name + .ends_with("::randomize") + .then(|| { + objects::random_selection(tree, dimensions, &name, args, native) + }) + .transpose()?; + if selection.is_none() + && (args.len() > formals + || (name.ends_with("::srandom") && args.len() != 1) + || args.iter().any(|arg| arg.name.is_some())) + { return Err(unsupported(format!("arguments of method `{name}`"))); } let mut children = Vec::new(); if let objects::Receiver::Handle(handle) = receiver { children.push((handle, None)); } - for arg in args { + for arg in args.iter().filter(|_| selection.is_none()) { let Some(value) = arg.value else { return Err(unsupported(format!( "omitted argument of method `{name}`" @@ -433,6 +448,7 @@ pub(in crate::ast) fn bind_value( name, formals, receiver, + selection, }, children, ) @@ -921,6 +937,7 @@ pub(in crate::ast) fn bind_value( name, formals, receiver, + selection, } => { let mut args: Vec> = Vec::with_capacity(formals + 1); if receiver == objects::Receiver::This { @@ -928,6 +945,7 @@ pub(in crate::ast) fn bind_value( } let handles = usize::from(receiver != objects::Receiver::Static); args.extend(operands.into_iter().map(Some)); + args.extend(selection.map(Some)); // Omitted trailing arguments take their defaults. args.resize(formals + handles, None); Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 41b00e548c0..cfcd38f83ed 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -280,6 +280,23 @@ pub(in crate::ast) fn method( )), }; } + if matches!(method_name.as_str(), "randomize" | "srandom") { + if receiver == Receiver::Static + || (receiver == Receiver::This && dimensions.get(THIS).is_none()) + { + return Err(unsupported( + "class randomization requires an object receiver", + )); + } + if method_name == "randomize" { + class.check_randomize(tree)?; + } + return Ok(Some(( + Class::subroutine_name(&class_name, &method_name), + 1, + receiver, + ))); + } let Some(method) = class.method(&method_name) else { return Ok(None); }; @@ -499,3 +516,183 @@ pub(in crate::ast) fn constructor( arg_order: Vec::new(), })) } + +/// Inline randomization names are resolved in the receiver's class, not in +/// the caller's scope (18.11). Bit zero distinguishes an explicit empty set. +pub(super) fn random_selection( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + name: &str, + arguments: &[celox_sv_syntax::Argument], + native: &Declarations, +) -> Converted { + let owner = name.strip_suffix("::randomize").expect("randomize method"); + let class = class(tree, dimensions, owner)?; + let mut bits = vec!['0'; class.properties.len() + 1]; + if !arguments.is_empty() { + bits[0] = '1'; + } + for argument in arguments { + let id = argument + .value + .filter(|_| argument.name.is_none()) + .ok_or_else(|| unsupported("randomize arguments must be member names"))?; + match &native.expression(ungroup(id, native)).kind { + ExprKind::Literal(value) if value == "null" && arguments.len() == 1 => {} + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + let index = class + .properties + .iter() + .rposition(|p| p.name == name) + .ok_or_else(|| { + unsupported(format!( + "randomize argument `{name}` is not an instance property" + )) + })?; + let property = &class.properties[index]; + check_random_access(tree, dimensions, property)?; + if property.constant { + return Err(unsupported("randomize argument is a const property")); + } + if property.field.handle.is_some() || property.r#type.is_enum || property.randc { + return Err(unsupported( + "randomize arguments require integral non-enum, non-randc properties", + )); + } + bits[index + 1] = '1'; + } + _ => { + return Err(unsupported( + "randomize arguments must be member names or a single null", + )); + } + } + } + Ok(Expr::Literal(format!( + "{}'b{}", + bits.len(), + bits.into_iter().rev().collect::() + ))) +} + +/// Bind rand_mode's void setter and integer getter separately (18.8). +/// A getter requires one random property; only the setter accepts an object. +pub(in crate::ast) fn rand_mode_call( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + allow_set: bool, +) -> Converted> { + let (callee, args) = match &native.expression(ungroup(id, native)).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (id, &[][..]), + }; + let (property, owner, handle) = match &native.expression(ungroup(callee, native)).kind { + ExprKind::Member { + expression, + separator, + name, + } if separator == "." && name.spelling == "rand_mode" => { + let property_target = property(tree, *expression, native, dimensions)?; + if let Some((property, object)) = property_target.filter(|(property, _)| { + property.rand || property.randc || property.r#type.class().is_none() + }) { + check_random_access(tree, dimensions, &property)?; + if !property.rand && !property.randc { + return Err(unsupported("rand_mode requires a rand or randc property")); + } + ( + Some(property), + None, + receiver(tree, object, native, dimensions)?, + ) + } else if let Some(owner) = native_class(tree, *expression, native, dimensions) { + ( + None, + Some(owner), + bind_value(*expression, native, tree, dimensions, None)?, + ) + } else { + return Err(unsupported( + "rand_mode requires an object or random class property", + )); + } + } + ExprKind::Name(name) + if name.spelling == "rand_mode" && dimensions.get("rand_mode").is_none() => + { + let Some(owner) = scope_class(dimensions) else { + return Ok(None); + }; + if dimensions.get(THIS).is_none() { + return Err(unsupported("rand_mode requires an object receiver")); + } + (None, Some(owner), this()) + } + _ => return Ok(None), + }; + if args.is_empty() { + let property = + property.ok_or_else(|| unsupported("rand_mode getter requires one random property"))?; + return Ok(Some(classes::object_call( + ObjectOp::ModeGet(property.field.offset, true), + vec![handle], + ))); + } + if !allow_set { + return Err(unsupported( + "rand_mode setter is void and cannot be used as a value", + )); + } + if args.len() != 1 || args[0].name.is_some() || args[0].value.is_none() { + return Err(unsupported("rand_mode setter requires one on_off argument")); + } + let enabled = bind_value(args[0].value.unwrap(), native, tree, dimensions, None)?; + Ok(Some(match property { + Some(property) => classes::object_call( + ObjectOp::ModeSet(property.field.offset), + vec![handle, enabled], + ), + None => Expr::Call { + callee: Callee::Subroutine(Class::subroutine_name(&owner.unwrap(), "rand_mode")), + args: vec![Some(handle), Some(enabled)], + arg_order: Vec::new(), + }, + })) +} + +fn check_random_access( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + property: &classes::Property, +) -> Converted<()> { + let scope = scope_class(dimensions); + let accessible = if property.local { + scope.as_deref() == Some(&property.owner) + } else if property.protected { + scope + .and_then(|name| class(tree, dimensions, &name).ok()) + .is_some_and(|class| { + class.derives_from( + tree, + &property.owner, + &dimensions.const_env, + &dimensions.type_aliases, + ) + }) + } else { + true + }; + if !accessible { + return Err(unsupported(format!( + "randomization access to non-public property `{}`", + property.name + ))); + } + Ok(()) +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 925eb96cc2b..47c102a0582 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -10,6 +10,7 @@ use super::*; mod assertions; mod control; mod foreach; +mod randomization; pub(super) mod timed_tasks; mod timing; use crate::procedural::{ @@ -703,6 +704,23 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + if let Some(mut call) = + expression_binding::object_rand_mode_call(self.tree, root, native, &self.dims, true)? + { + self.rename_expr(&mut call); + return Ok(Some(match call { + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order, + } => Stmt::Call { + name, + args, + arg_order, + }, + call => Stmt::Eval(call), + })); + } let call = match native.expression(root).kind { celox_sv_syntax::ExprKind::Call { expression, .. } => { if expression_binding::object_method(self.tree, expression, native, &self.dims)? @@ -727,6 +745,12 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } expression_binding::ObjectReceiver::Static => Vec::new(), }; + if name.ends_with("::randomize") { + args.push(Some(Expr::Literal("1'b0".into()))); + } + if name.ends_with("::srandom") { + return Err(unsupported("srandom requires a seed argument")); + } args.resize( formals + usize::from(receiver != expression_binding::ObjectReceiver::Static), None, @@ -1646,6 +1670,30 @@ pub(super) fn subroutine_argument_names( params.into_iter().map(|(name, ..)| name).collect(), ); } + for method in ["randomize", "srandom", "rand_mode"] { + let qualified = item.name(&classes::Class::subroutine_name(&class, method)); + let mut param_names = vec![classes::THIS.to_owned()]; + let mut param_shapes = vec![dimensions_from_type(&handle)]; + let (argument, ty) = match method { + "randomize" => ( + "$selection", + layout.as_ref().map_or_else( + || classes::unsigned_type(1), + |layout| layout.selection_type(), + ), + ), + "srandom" => ("seed", int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + param_names.push(argument.into()); + param_shapes.push(dimensions_from_type(&ty)); + directions.insert( + qualified.clone(), + vec![ParamDirection::Input; param_names.len()], + ); + shapes.insert(qualified.clone(), param_shapes); + names.insert(qualified, param_names); + } let handle = dimensions_from_type(&scoped_type(handle, &item.env)); if !constructor && !layout.is_some_and(|layout| layout.is_interface) { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); @@ -2463,6 +2511,13 @@ fn lower_class( state, item, )?); + subroutines.extend(randomization::lower( + &class, + tree, + item_dimensions, + state, + item, + )?); Ok(subroutines) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs new file mode 100644 index 00000000000..2b8d305459e --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -0,0 +1,266 @@ +//! Built-in class randomization methods (IEEE 1800-2023 18.6, 18.8, 18.11). +use super::*; +use crate::system_functions::ObjectOp; + +/// Generate automatic methods so hooks, dispatch and property updates use +/// ordinary call machinery. The hidden selection argument is zero for the +/// persistent random modes, or has bit 0 set and bit i+1 for selected property i. +/// Inherited properties keep their indices, including hidden base properties. +pub(super) fn lower( + class: &classes::Class, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + state: &mut BodyState<'_>, + item: &generate::Item, +) -> Converted> { + let handle = classes::handle_type(tree, &class.name) + .ok_or_else(|| unsupported("class randomization receiver"))?; + let convert_type = |ty| { + crate::ir::Type::from_ast( + ty, + &const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }, + ) + }; + let mut result = Vec::new(); + for method in ["randomize", "srandom", "rand_mode"] { + if method == "randomize" && class.check_randomize(tree).is_err() { + continue; + } + let mut builder = + BodyBuilder::new(tree, dimensions, state, system_functions::Body::Subroutine); + builder.automatic = true; + let first_local = builder.state.locals.len(); + let this = builder.declare(classes::THIS, handle.clone()); + let (argument, argument_type) = match method { + "randomize" => ("$selection", class.selection_type()), + "srandom" => ("seed", int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + let argument = builder.declare(argument, argument_type.clone()); + let params = vec![ + SubroutineParam { + name: this.clone(), + source_name: classes::THIS.into(), + direction: ParamDirection::Input, + r#type: convert_type(handle.clone()), + default: None, + }, + SubroutineParam { + name: argument.clone(), + source_name: argument.clone(), + direction: ParamDirection::Input, + r#type: convert_type(argument_type), + default: None, + }, + ]; + // Faults are consumed after the kernel completes. Return immediately + // on rejection, before hooks, draws or property/mode updates. + let mut body = vec![Stmt::If { + condition: classes::object_call( + ObjectOp::Check(if method == "srandom" { 0 } else { class.id }), + vec![Expr::Ident(this.clone())], + ), + then_body: Vec::new(), + else_body: vec![Stmt::Return( + (method == "randomize").then(|| Expr::Literal("32'sd0".into())), + )], + }]; + let return_var = match method { + "srandom" => { + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Seed, + vec![Expr::Ident(this.clone()), Expr::Ident(argument.clone())], + ))); + None + } + "rand_mode" => { + for property in &class.properties { + let update = Stmt::Eval(classes::object_call( + ObjectOp::ModeSet(property.field.offset), + vec![Expr::Ident(this.clone()), Expr::Ident(argument.clone())], + )); + body.push(if property.rand || property.randc { + update + } else { + Stmt::If { + condition: classes::object_call( + ObjectOp::ModeSelected(property.field.offset), + vec![Expr::Ident(this.clone())], + ), + then_body: vec![update], + else_body: Vec::new(), + } + }); + } + None + } + _ => { + let hook = |name| { + class.method(name).map(|method| Stmt::Call { + name: classes::Class::subroutine_name(&method.owner, &method.name), + args: vec![Some(Expr::Ident(this.clone()))], + arg_order: Vec::new(), + }) + }; + let mut select = vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePush, + vec![Expr::Ident(this.clone())], + ))]; + for (index, property) in class.properties.iter().enumerate() { + let selected = Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal((index + 1).to_string())), + }), + op: BinaryOp::BitAnd, + right: Box::new(Expr::Literal("1'b1".into())), + }; + select.push(Stmt::Eval(classes::object_call( + ObjectOp::ModeSelect(property.field.offset, property.rand), + vec![Expr::Ident(this.clone()), selected], + ))); + } + body.push(Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: select, + 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 + { + 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), + vec![Expr::Ident(this.clone())], + )), + }, + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![ + Expr::Ident(this.clone()), + classes::object_call( + ObjectOp::Random, + vec![Expr::Ident(this.clone())], + ), + ], + ))], + else_body: Vec::new(), + }); + } + body.extend(hook("post_randomize")); + body.push(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(), + }); + let returned = builder.declare("randomize", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(returned.clone()), + rhs: Expr::Literal("32'sd1".into()), + nonblocking: false, + }); + Some(returned) + } + }; + if method != "srandom" { + // randomize is virtual, while its pre/post hooks are not (18.6.2). + // Object-wide rand_mode also covers the dynamic object's members. + let mut items = Vec::new(); + let aliases = item.type_aliases(&dimensions.type_aliases); + for declaration in &tree.declarations().classes { + if declaration.interface || declaration.virtual_class { + continue; + } + let name = instances::normalize_identifier(&declaration.name.spelling); + if name == class.name { + continue; + } + let Ok(derived) = classes::class(tree, &name, &item.env, &aliases) else { + continue; + }; + if (method == "randomize" && derived.check_randomize(tree).is_err()) + || !derived.derives_from(tree, &class.name, &item.env, &aliases) + { + continue; + } + let args = vec![ + Some(Expr::Ident(this.clone())), + Some(Expr::Ident(argument.clone())), + ]; + let name = classes::Class::subroutine_name(&name, method); + let call = if method == "randomize" { + vec![Stmt::Return(Some(Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order: Vec::new(), + }))] + } else { + vec![ + Stmt::Call { + name, + args, + arg_order: Vec::new(), + }, + Stmt::Return(None), + ] + }; + items.push(CaseItemBase { + labels: vec![CaseLabel::Value(Expr::Literal(format!( + "32'd{}", + derived.id + )))], + body: call, + }); + } + body.insert( + 0, + Stmt::Case { + kind: CaseKind::Exact, + selector: classes::object_call( + ObjectOp::ClassOf, + vec![Expr::Ident(this.clone())], + ), + items, + default: None, + }, + ); + } + for stmt in &mut body { + qualify_stmt(item, stmt); + } + result.push(Subroutine { + name: item.name(&classes::Class::subroutine_name(&class.name, method)), + is_task: false, + automatic_locals: builder.state.locals[first_local..] + .iter() + .map(|local| local.name.clone()) + .collect(), + persistent_locals: Vec::new(), + return_type: return_var.as_ref().map(|_| convert_type(int_type())), + params, + return_var, + body, + sensitivity_body: Vec::new(), + }); + } + Ok(result) +} diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 4418f7f1ab5..3fda772fed5 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -786,12 +786,35 @@ pub enum ObjectOp { Store(ObjectField), /// The run-time class of the object in the argument, 0 for `null`. ClassOf, + /// Advance the object's independent RNG, returning 64 random bits. + Random, + /// Seed the object's RNG from the second argument. + Seed, + /// Validate a receiver; a nonzero class also rejects unsupported dynamic + /// dispatch through a base handle before randomizing its properties. + Check(u32), + /// Query or set the random mode of a property at its byte offset. + ModeGet(u32, bool), + ModeSet(u32), + ModePush, + ModePop, + ModeSelect(u32, bool), + ModeSelected(u32), } impl ObjectOp { /// The width and signedness of the result. pub fn result_type(&self) -> (usize, bool) { match self { + Self::Random => (64, false), + Self::Seed + | Self::Check(_) + | Self::ModeSet(_) + | Self::ModePush + | Self::ModePop + | Self::ModeSelect(..) + | Self::ModeSelected(_) => (32, false), + Self::ModeGet(..) => (32, true), Self::Load(field) => (field.width as usize, field.signed), Self::New { .. } | Self::ClassOf | Self::Store(_) => (32, false), } @@ -805,6 +828,15 @@ impl fmt::Display for ObjectOp { Self::Load(_) => "property read", Self::Store(_) => "property write", Self::ClassOf => "class query", + Self::Random => "object random bits", + Self::Seed => "object random seed", + Self::Check(_) => "object receiver check", + Self::ModeGet(..) => "random mode query", + Self::ModeSet(_) => "random mode update", + Self::ModePush => "save random modes", + Self::ModePop => "restore random modes", + Self::ModeSelect(..) => "select random property", + Self::ModeSelected(_) => "selected random property query", }) } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index cd2978e2577..dcc648cb2c5 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6571,3 +6571,97 @@ fn explicit_output_data_types_default_to_variables() { assert!(ports[3].is_net()); assert!(ports[4].is_net()); } + +#[test] +fn class_randomize_rejects_unsupported_semantics() { + for (members, call, expected) in [ + ( + "rand int x; constraint c { x == 1; }", + "c.randomize()", + "constraints", + ), + ("randc bit [1:0] x;", "c.randomize()", "randc"), + ("rand int x;", "c.srandom()", "argument"), + ("rand int x;", "c.srandom(1, 2)", "arguments"), + ( + "rand int x; extern constraint c;", + "c.randomize()", + "constraints", + ), + ("rand const int x;", "c.randomize()", "const"), + ("static rand int x;", "c.randomize()", "static random"), + ("rand int x;", "C::randomize()", "object receiver"), + ("rand int x;", "C::srandom(1)", "object receiver"), + ( + "static function int f(); return randomize(); endfunction", + "c.f()", + "object receiver", + ), + ("rand string x;", "c.randomize()", "integral non-enum"), + ( + "rand int x;", + "c.randomize() with { x == 1; }", + "unsupported", + ), + ("rand int x;", "c.randomize(x + 1)", "arguments"), + ("rand int x;", "c.randomize(c.x)", "arguments"), + ("rand int x;", "c.randomize(null, x)", "arguments"), + ( + "rand int x;", + "c.randomize(missing)", + "not an instance property", + ), + ("const int x = 1;", "c.randomize(x)", "const"), + ("local int x;", "c.randomize(x)", "non-public"), + ("protected int x;", "c.randomize(x)", "non-public"), + ("rand int x;", "c.rand_mode()", "getter requires"), + ("int x;", "c.x.rand_mode()", "rand or randc"), + ( + "rand int x; function void pre_randomize(int arg); endfunction", + "c.randomize()", + "hooks", + ), + ( + "function int randomize(); return 1; endfunction", + "c.randomize()", + "overriding", + ), + ] { + let source = format!( + "module Top; class C; {members} endclass C c; initial begin c = new; void'({call}); end endmodule" + ); + let error = analyze_source(&source, Path::new("randomize_unsupported.sv")) + .unwrap_err() + .to_string(); + assert!(error.to_lowercase().contains(expected), "{source}: {error}"); + } +} + +#[test] +fn rand_mode_setter_cannot_be_used_as_a_value() { + let source = "module Top; class C; rand int x; endclass C c; int result; initial begin c = new; result = c.x.rand_mode(1); end endmodule"; + let error = analyze_source(source, Path::new("mode_value.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("setter is void"), "{error}"); +} + +#[test] +fn rand_mode_name_outside_a_class_is_an_ordinary_function() { + let source = "module Top(output int value); function int rand_mode(); return 42; endfunction initial value = rand_mode(); endmodule"; + analyze_source(source, Path::new("ordinary_rand_mode.sv")).unwrap(); +} + +#[test] +fn randomization_signatures_do_not_force_unused_interface_class_layouts() { + for declaration in [ + "interface class I; typedef int T; pure virtual function void f(T x); endclass + interface class J extends I; pure virtual function void g(T x); endclass", + "interface class I #(type T = logic); pure virtual function void f(T x); endclass + interface class J #(type T = logic); pure virtual function void g(T x); endclass + interface class K #(type U = logic) extends I#(U), J#(U); typedef U T; endclass", + ] { + let source = format!("module Top; {declaration} endmodule"); + analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap(); + } +} diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index e72c9d6fcee..b52c7abebc2 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -957,6 +957,8 @@ pub struct ClassDeclaration { /// The interface classes of `implements`, or those an interface class /// extends (8.26). pub interfaces: Vec, + /// Whether the class declares constraints, including prototypes. + pub has_constraints: bool, pub properties: Vec, pub methods: Vec, pub tokens: TokenRange, @@ -980,6 +982,7 @@ pub struct ClassQualifiers { pub local: bool, pub protected: bool, pub rand: bool, + pub randc: bool, } /// A property declaration of a class. diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index e9ea1f3df5f..821fed8c460 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -91,7 +91,8 @@ impl Parser<'_> { "extern" => &mut qualifiers.is_extern, "local" => &mut qualifiers.local, "protected" => &mut qualifiers.protected, - "rand" | "randc" => &mut qualifiers.rand, + "rand" => &mut qualifiers.rand, + "randc" => &mut qualifiers.randc, _ => return false, }; *flag = true; @@ -206,6 +207,7 @@ impl Parser<'_> { interface, base, interfaces, + has_constraints: false, properties: Vec::new(), methods: Vec::new(), tokens: TokenRange { start, end: start }, diff --git a/crates/celox-sv-syntax/src/parser/constraints.rs b/crates/celox-sv-syntax/src/parser/constraints.rs index 0c8b81cc54d..3dcdfc0bbc4 100644 --- a/crates/celox-sv-syntax/src/parser/constraints.rs +++ b/crates/celox-sv-syntax/src/parser/constraints.rs @@ -28,6 +28,9 @@ impl Parser<'_> { } pub(super) fn class_constraint(&mut self) -> Result<()> { + if let Some(class) = self.class_stack.last_mut() { + class.has_constraints = true; + } let prototype = self.eat("extern") || self.eat("pure"); self.eat("static"); self.expect("constraint")?; diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index f5aea670507..d66393e16f5 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2786,3 +2786,16 @@ fn class_declarations_record_names_bases_properties_and_method_qualifiers() { ); } } + +#[test] +fn class_random_qualifiers_and_constraints_are_preserved() { + let syntax = parse( + "class C; rand bit x; randc bit y; extern constraint limits; endclass module M; endmodule", + ); + let class = &syntax.classes[0]; + assert!(class.has_constraints); + assert!(class.properties[0].qualifiers.rand); + assert!(!class.properties[0].qualifiers.randc); + assert!(class.properties[1].qualifiers.randc); + assert!(!class.properties[1].qualifiers.rand); +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 99270bee0a2..51e04377b4c 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -577,6 +577,12 @@ interface. Verilator 5.052 executes the same emitted Veryl design successfully. The [retained diagnostic](verification/repros/interface_nested_icarus.json) records this compile limitation. +Class randomization (`sv_icarus_class_randomize`) excludes the two cases +`class::unconstrained_randomize` and `class::randomize_without_rand_members` +from Icarus 13.0. It rejects the built-in `randomize` and `srandom` methods +during elaboration; [the original diagnostics](verification/repros/sv_class_randomize_icarus.json) +remain available. Both cases pass Verilator and Celox. + ## Veryl analyzer floating-point constant expressions Veryl analyzer 0.22 can fold negative `f32` casts and dependent floating-point @@ -645,3 +651,21 @@ an unknown display format code. It prints a lowercase `e` for the uppercase `%E` conversion in `real_display_negative_zero`; the negative-zero value is otherwise correct. Its `real_file_display_formats` case passes. The shared assertions remain enabled, and these external differences are not exclusions. + +Randomization control (`sv_icarus_randomization_control`) excludes four new +`class::randomization_*` cases from Icarus 13.0: it rejects `randomize`, `srandom` +and property/object `rand_mode` calls. [Retained diagnostics](verification/repros/sv_randomization_control_icarus.json) +record the failures; they are not passing simulation results. + +Verilator 5.052 has two narrower exclusions, recorded in the +[randomization control evidence](verification/repros/sv_randomization_control_verilator.json): + +- `sv_verilator_inherited_srandom`: `class::randomization_inheritance` fails + compilation with duplicate `srandom` declarations when the same derived + object is seeded through derived and base handles (IEEE 1800-2023 18.6.2, + 18.13.3). Assertions for hidden inherited members and hook dispatch remain. +- `sv_verilator_rand_mode_bit_argument`: `class::randomization_mode_bit_argument` + reports two errors because both forms of `rand_mode(2)` enable the variable. + The setter's formal is `bit` (18.8), so the required conversion truncates 2 to + 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, + inline member selection and pre-hook control cases pass Verilator. diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 9aec1add777..768617f2953 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -711,3 +711,221 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "1 8\n1 1\n0 8\n")) + +(case unconstrained_randomize + (source "randomize.sv" #" +module Top(output bit done, output int errors); + class Sample; + rand bit flag; + rand bit signed [6:0] narrow; + rand bit [63:0] wide; + int untouched = 42; + int phase; + bit [63:0] observed; + function void pre_randomize(); + if (phase != 0) untouched = -1; + phase = 1; + endfunction + function void post_randomize(); + if (phase != 1) untouched = -2; + observed = wide; + phase = 0; + endfunction + function int again(); + return randomize(); + endfunction + endclass + Sample a, b, alias_a; + bit [63:0] saved, changed; + bit saved_flag; + bit signed [6:0] saved_small; + int ignored; + initial begin + a = new; + b = new; + alias_a = a; + a.srandom(0); + if (a.randomize() != 1) errors++; + saved = a.wide; + saved_flag = a.flag; + saved_small = a.narrow; + if (a.observed != saved || a.untouched != 42 || a.phase != 0) errors++; + changed = 0; + repeat (12) begin + if (a.again() != 1) errors++; + changed |= saved ^ a.wide; + end + if (changed[63:32] == 0 || changed[31:0] == 0) errors++; + alias_a.srandom(0); + repeat (5) begin + ignored = $urandom; + ignored = b.randomize(); + end + if (a.randomize() != 1) errors++; + if (a.wide != saved || a.flag != saved_flag || a.narrow != saved_small) errors++; + if (a.observed != saved || a.untouched != 42 || a.phase != 0) errors++; + b.srandom(0); + if (b.randomize() != 1 || b.wide != saved) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomize_without_rand_members + (source "randomize_empty.sv" #" +module Top(output bit done, output int errors); + class Empty; + int value = 5; + function void pre_randomize(); value += 1; endfunction + function void post_randomize(); value *= 2; endfunction + endclass + Empty object; + initial begin + object = new; + if (object.randomize() != 1 || object.value != 12) errors++; + if (object.randomize() != 1 || object.value != 26) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_inheritance + (source "randomization_inheritance.sv" #" +module Top(output bit done, output int errors); + class Base; + rand bit [63:0] x; + int pre, post; + function void pre_randomize(); pre += 1; endfunction + function void post_randomize(); post += 1; endfunction + function bit [63:0] base_x(); return x; endfunction + function int again(); return randomize(); endfunction + endclass + class Child extends Base; + rand bit [63:0] x; + rand bit [63:0] y; + function void pre_randomize(); super.pre_randomize(); pre += 10; endfunction + function void post_randomize(); super.post_randomize(); post += 10; endfunction + endclass + class Grandchild extends Child; endclass + Base b; + Grandchild c; + bit [63:0] bx, cx, cy; + initial begin + c = new; + b = c; + c.srandom(31); + if (!c.randomize()) errors++; + bx = c.base_x(); cx = c.x; cy = c.y; + b.srandom(31); + if (!b.again()) errors++; + if (b.x != bx || c.x != cx || c.y != cy) errors++; + if (b.pre != 22 || b.post != 22) errors++; + b.rand_mode(0); + if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++; + if (!b.randomize() || b.x != bx || c.x != cx || c.y != cy) errors++; + // Inline selection is resolved in the static receiver class. + b.srandom(31); + if (!b.randomize(x) || b.x != bx || c.x != cx || c.y != cy) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_modes_and_selection + (source "randomization_modes.sv" #" +module Top(output bit done, output int errors); + class C; + rand bit [63:0] x, y; + bit [63:0] plain = 19; + int hooks; + function void pre_randomize(); hooks++; endfunction + function void post_randomize(); hooks++; endfunction + function int select_plain(); return randomize(plain); endfunction + function void disable_x(); x.rand_mode(0); endfunction + endclass + C c, alias_c, reference; + int plain = 99; + bit [63:0] x, y, p; + initial begin + c = new; reference = new; alias_c = c; + if (c.x.rand_mode() != 1 || c.y.rand_mode() != 1) errors |= 1; + c.disable_x(); + c.srandom(42); reference.srandom(42); + if (!c.randomize() || !reference.randomize(y)) errors |= 2; + if (c.x != 0 || c.y != reference.y || c.plain != 19) errors |= 4; + c.rand_mode(0); + x = c.x; y = c.y; + if (!c.randomize() || c.x != x || c.y != y) errors |= 8; + alias_c.x.rand_mode(1); + if (c.x.rand_mode() != 1 || c.y.rand_mode() != 0) errors |= 16; + c.x.rand_mode(0); + if (c.x.rand_mode() != 0) errors |= 32; + c.srandom(9); reference.srandom(9); + if (!c.randomize(plain) || !reference.randomize(plain)) errors |= 64; + if (plain != 99 || c.plain != reference.plain || c.x != x || c.y != y) errors |= 128; + if (c.x.rand_mode() || c.y.rand_mode()) errors |= 256; + p = c.plain; + if (!c.randomize(null) || c.x != x || c.y != y || c.plain != p) errors |= 512; + if (c.hooks != 8) errors |= 1024; + c.srandom(7); reference.srandom(7); + if (!c.select_plain() || !reference.randomize(plain)) errors |= 2048; + if (c.plain != reference.plain) errors |= 4096; + c.rand_mode(1); + if (!c.x.rand_mode() || !c.y.rand_mode()) errors |= 8192; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_pre_hook_controls_modes + (source "randomization_hook.sv" #" +module Top(output bit done, output int errors); + class C; + rand bit [63:0] x; + bit disable_randomization; + int seen; + function void pre_randomize(); + seen = x.rand_mode(); + if (disable_randomization) rand_mode(0); + endfunction + endclass + C c, reference; + initial begin + c = new; reference = new; + c.disable_randomization = 1; + if (!c.randomize() || c.x != 0 || c.x.rand_mode()) errors++; + c.srandom(8); reference.srandom(8); + if (!c.randomize(x) || !reference.randomize()) errors++; + if (c.x != 0 || c.x.rand_mode() || c.seen != 1) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + + +(case randomization_mode_bit_argument + (source "mode_bit_argument.sv" #" +module Top(output bit done, output int errors); + class C; rand int x; endclass + C c; + initial begin + c = new; + c.x.rand_mode(2); + if (c.x.rand_mode() != 0) errors++; + c.x.rand_mode(3); + if (c.x.rand_mode() != 1) errors++; + c.rand_mode(2); + if (c.x.rand_mode() != 0) errors++; + c.rand_mode(3); + if (c.x.rand_mode() != 1) errors++; + if (c.x.rand_mode() < -1) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json new file mode 100644 index 00000000000..653f13b2791 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json @@ -0,0 +1,31 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:11: Error: randomize is not a method of class Empty.\n/source_0.sv:11: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:11: error: Unable to elaborate condition expression.\n/source_0.sv:12: Error: randomize is not a method of class Empty.\n/source_0.sv:12: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:12: error: Unable to elaborate condition expression.\n6 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomize_without_rand_members", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:20: error: No function named `randomize' found in this context (celox_suite_tb.dut.Sample.again).\n/source_0.sv:32: error: Can't find task srandom in class Sample\n/source_0.sv:32: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:33: Error: randomize is not a method of class Sample.\n/source_0.sv:33: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:33: error: Unable to elaborate condition expression.\n/source_0.sv:44: error: Can't find task srandom in class Sample\n/source_0.sv:44: error: Enable of unknown task ``alias_a.srandom''.\n/source_0.sv:47: Error: randomize is not a method of class Sample.\n/source_0.sv:47: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:49: Error: randomize is not a method of class Sample.\n/source_0.sv:49: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:49: error: Unable to elaborate condition expression.\n/source_0.sv:52: error: Can't find task srandom in class Sample\n/source_0.sv:52: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:53: Error: randomize is not a method of class Sample.\n/source_0.sv:53: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:53: error: Unable to elaborate condition expression.\n18 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::unconstrained_randomize", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "note": "Focused unexcluded class randomization failures. Both shared cases pass Celox native, Cranelift, Wasm and Verilator." +} diff --git a/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json b/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json new file mode 100644 index 00000000000..28e83c0af99 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json @@ -0,0 +1,60 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "case_fingerprint": "0790ca7f7a064b5ada217c1bcb303cc08f64d22140af1e703f2687aa00b567f5", + "category": "Types", + "detail": "Icarus build exit status: 22; see /build.log\n/source_0.sv:9: error: No function named `randomize' found in this context (celox_suite_tb.dut.Base.again).\n/source_0.sv:24: error: Can't find task srandom in class Grandchild\n/source_0.sv:24: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:25: Error: randomize is not a method of class Grandchild.\n/source_0.sv:25: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:25: error: Unable to elaborate condition expression.\n/source_0.sv:27: error: Can't find task srandom in class Base\n/source_0.sv:27: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:31: error: Can't find task rand_mode in class Base\n/source_0.sv:31: error: Enable of unknown task ``b.rand_mode''.\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.b has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: y.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:33: Error: randomize is not a method of class Base.\n/source_0.sv:33: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:33: error: Unable to elaborate condition expression.\n/source_0.sv:35: error: Can't find task srandom in class Base\n/source_0.sv:35: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:36: Error: randomize is not a method of class Base.\n/source_0.sv:36: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n22 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "ca2c64e1d788293a78db1e56128c2d271ac015be7f14c463c9829778dc0a114f", + "category": "Types", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:7: error: Can't find task rand_mode in class C\n/source_0.sv:7: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:8: sorry: Method name nesting is not supported yet.\n/source_0.sv:8: : method path: x.rand_mode\n/source_0.sv:8: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:8: error: Unable to elaborate condition expression.\n/source_0.sv:9: error: Can't find task rand_mode in class C\n/source_0.sv:9: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:10: sorry: Method name nesting is not supported yet.\n/source_0.sv:10: : method path: x.rand_mode\n/source_0.sv:10: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:10: error: Unable to elaborate condition expression.\n/source_0.sv:11: error: Can't find task rand_mode in class C\n/source_0.sv:11: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:12: sorry: Method name nesting is not supported yet.\n/source_0.sv:12: : method path: x.rand_mode\n/source_0.sv:12: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:12: error: Unable to elaborate condition expression.\n/source_0.sv:13: error: Can't find task rand_mode in class C\n/source_0.sv:13: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:14: sorry: Method name nesting is not supported yet.\n/source_0.sv:14: : method path: x.rand_mode\n/source_0.sv:14: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:14: error: Unable to elaborate condition expression.\n/source_0.sv:15: sorry: Method name nesting is not supported yet.\n/source_0.sv:15: : method path: x.rand_mode\n/source_0.sv:15: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:15: error: Unable to elaborate condition expression.\n18 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "93d721f6fe140941ddb5068e041dc968ca7e9c60a73e13320da3c8439d0aa8f1", + "category": "Types", + "detail": "Icarus build exit status: 57; see /build.log\n/source_0.sv:10: error: Can't find task rand_mode in class C\n/source_0.sv:10: error: Enable of unknown task ``x.rand_mode''.\n/source_0.sv:10: error: Unable to elaborate statement in function disable_x.\n/source_0.sv:9: error: No function named `randomize' found in this context (celox_suite_tb.dut.C.select_plain).\n/source_0.sv:17: sorry: Method name nesting is not supported yet.\n/source_0.sv:17: : method path: x.rand_mode\n/source_0.sv:17: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:17: sorry: Method name nesting is not supported yet.\n/source_0.sv:17: : method path: y.rand_mode\n/source_0.sv:17: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:17: error: Unable to elaborate condition expression.\n/source_0.sv:19: error: Can't find task srandom in class C\n/source_0.sv:19: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:19: error: Can't find task srandom in class C\n/source_0.sv:19: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:20: Error: randomize is not a method of class C.\n/source_0.sv:20: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:20: Error: randomize is not a method of class C.\n/source_0.sv:20: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:22: error: Can't find task rand_mode in class C\n/source_0.sv:22: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:24: Error: randomize is not a method of class C.\n/source_0.sv:24: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:24: error: Unable to elaborate condition expression.\n/source_0.sv:25: error: Can't find task rand_mode in class C\n/source_0.sv:25: error: Enable of unknown task ``alias_c.x.rand_mode''.\n/source_0.sv:26: sorry: Method name nesting is not supported yet.\n/source_0.sv:26: : method path: x.rand_mode\n/source_0.sv:26: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:26: sorry: Method name nesting is not supported yet.\n/source_0.sv:26: : method path: y.rand_mode\n/source_0.sv:26: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:26: error: Unable to elaborate condition expression.\n/source_0.sv:27: error: Can't find task rand_mode in class C\n/source_0.sv:27: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:28: sorry: Method name nesting is not supported yet.\n/source_0.sv:28: : method path: x.rand_mode\n/source_0.sv:28: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:28: error: Unable to elaborate condition expression.\n/source_0.sv:29: error: Can't find task srandom in class C\n/source_0.sv:29: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:29: error: Can't find task srandom in class C\n/source_0.sv:29: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:30: Error: randomize is not a method of class C.\n/source_0.sv:30: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:30: Error: randomize is not a method of class C.\n/source_0.sv:30: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:30: error: Unable to elaborate condition expression.\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: y.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:34: Error: randomize is not a method of class C.\n/source_0.sv:34: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:34: error: Unable to elaborate condition expression.\n/source_0.sv:36: error: Can't find task srandom in class C\n/source_0.sv:36: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:36: error: Can't find task srandom in class C\n/source_0.sv:36: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:37: Error: randomize is not a method of class C.\n/source_0.sv:37: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:37: error: Unable to elaborate condition expression.\n/source_0.sv:39: error: Can't find task rand_mode in class C\n/source_0.sv:39: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:40: sorry: Method name nesting is not supported yet.\n/source_0.sv:40: : method path: x.rand_mode\n/source_0.sv:40: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:40: sorry: Method name nesting is not supported yet.\n/source_0.sv:40: : method path: y.rand_mode\n/source_0.sv:40: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:40: error: Unable to elaborate condition expression.\n57 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_modes_and_selection", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "e8d29f784ff8a2f5ff9124bc2d57b2406359db7d857778964e2389c86bc7f92b", + "category": "Types", + "detail": "Icarus build exit status: 17; see /build.log\n/source_0.sv:8: sorry: Method name nesting is not supported yet.\n/source_0.sv:8: : method path: x.rand_mode\n/source_0.sv:8: error: Object celox_suite_tb.dut.C.this has no method \"x.rand_mode(...)\".\n/source_0.sv:9: error: Enable of unknown task ``rand_mode''.\n/source_0.sv:16: Error: randomize is not a method of class C.\n/source_0.sv:16: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:16: sorry: Method name nesting is not supported yet.\n/source_0.sv:16: : method path: x.rand_mode\n/source_0.sv:16: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:16: error: Unable to elaborate condition expression.\n/source_0.sv:17: error: Can't find task srandom in class C\n/source_0.sv:17: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:17: error: Can't find task srandom in class C\n/source_0.sv:17: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:18: Error: randomize is not a method of class C.\n/source_0.sv:18: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:18: Error: randomize is not a method of class C.\n/source_0.sv:18: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:18: error: Unable to elaborate condition expression.\n/source_0.sv:19: sorry: Method name nesting is not supported yet.\n/source_0.sv:19: : method path: x.rand_mode\n/source_0.sv:19: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:19: error: Unable to elaborate condition expression.\n17 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_pre_hook_controls_modes", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json b/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json new file mode 100644 index 00000000000..964300cbefb --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json @@ -0,0 +1,34 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "case_fingerprint": "0790ca7f7a064b5ada217c1bcb303cc08f64d22140af1e703f2687aa00b567f5", + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:25:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 25 | if (!c.randomize()) errors++;\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHTRUNC?v=5.052\n ... Use \"/* verilator lint_off WIDTHTRUNC */\" and lint_on around source to disable this message.\n%Warning-WIDTHTRUNC: /source_0.sv:28:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'again' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 28 | if (!b.again()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:32:29: Logical operator LOGOR expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:32:29: Logical operator LOGOR expects 1 bit on the RHS, but RHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:32:48: Logical operator LOGOR expects 1 bit on the RHS, but RHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:33:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 33 | if (!b.randomize() || b.x != bx || c.x != cx || c.y != cy) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:36:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 36 | if (!b.randomize(x) || b.x != bx || c.x != cx || c.y != cy) errors++;\n | ^\n%Error: /source_0.sv:3:5: Duplicate declaration of member name: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: /source_0.sv:3:5: Duplicate declaration of function: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n /source_0.sv:3:5: ... Location of original declaration\n 3 | class Base;\n | ^~~~~\n%Error: Exiting due to 2 error(s)\n", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717788 + }, + { + "case_fingerprint": "ca2c64e1d788293a78db1e56128c2d271ac015be7f14c463c9829778dc0a114f", + "category": "Types", + "detail": "class::randomization_mode_bit_argument at 746:46: assert_eq errors: expected 0x0, got 0x2", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717804 + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 7d66640caf0..9e91a1b7c19 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,121 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_modes_and_selection", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_pre_hook_controls_modes", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_randomize", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [] + }, + "name": "class::randomize_without_rand_members", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", @@ -355,6 +470,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_randomize", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [] + }, + "name": "class::unconstrained_randomize", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 70b36e60f7c..b9acfdf7286 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2068,5 +2068,77 @@ "timing::process_nonblocking_assignments_outside_their_target" ] } + }, + { + "id": "sv_icarus_class_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [], + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomize_without_rand_members", + "class::unconstrained_randomize" + ] + } + }, + { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_inheritance", + "class::randomization_mode_bit_argument", + "class::randomization_modes_and_selection", + "class::randomization_pre_hook_controls_modes" + ] + } + }, + { + "id": "sv_verilator_inherited_srandom", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_inheritance" + ] + } + }, + { + "id": "sv_verilator_rand_mode_bit_argument", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_mode_bit_argument" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 50899178c71..a255bf9044d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -190,6 +190,52 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "known_issue": { + "id": "sv_verilator_inherited_srandom", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "known_issue": { + "id": "sv_verilator_rand_mode_bit_argument", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "detail": "", diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 5cbcd773323..1135f129784 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -185,7 +185,7 @@ fn difference( .heap() .same_contents(shadow.simulator.backend.heap()) { - return Some("the string heap".to_string()); + return Some("the runtime heap (strings or objects)".to_string()); } let (events, reference) = ( primary.peek_runtime_events(), @@ -503,6 +503,42 @@ mod tests { } } + #[test] + fn differential_mode_detects_object_rng_divergence_before_randomize() { + use crate::backend::SimBackend as _; + let source = r#" + module Top(output bit done); + timeunit 1ps / 1ps; + class C; rand int value; endclass + C c; + initial begin + c = new; + #5 done = 1; + #5 void'(c.randomize()); + end + endmodule + "#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("rng.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build() + .unwrap(); + sim.run_until(0).unwrap(); + let object = sim.get(sim.signal("c")).to_u32_digits()[0]; + use celox_runtime::StepObserver as _; + let mut check = + super::ShadowCheck::new(sim.shadow.as_mut().unwrap(), SchedulerMode::Differential); + check.before_step(&sim.state, &mut sim.simulator); + let result = sim.state.step_until(&mut sim.simulator, 5); + // Inject an extra draw after the primary step: before_step mirrors the + // heap, so a mutation between run_until calls would be overwritten. + sim.simulator.backend.heap_mut().random_object(object); + let error = check + .after_step(&sim.state, &mut sim.simulator, 5, &result) + .unwrap_err() + .to_string(); + assert!(error.contains("runtime heap"), "{error}"); + } + #[test] fn differential_mode_reports_a_diverging_step() { let mut sim = build(SchedulerMode::Differential); diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index d3ce2c4cdcb..17b93891c46 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -193,3 +193,188 @@ fn incompatible_class_handle_assignments_are_rejected() { assert!(want.iter().all(|want| error.contains(want)), "{error}"); } } + +sv_backends! { + fn class_unconstrained_randomize(sim) { @case "class::unconstrained_randomize"; } + fn class_randomize_without_rand_members(sim) { @case "class::randomize_without_rand_members"; } + fn class_randomize_null_receiver(sim) { + @setup { + let source = r#"module Top(output int hooks, result); + class Empty; + static int calls; + function void pre_randomize(); calls++; endfunction + function void post_randomize(); calls++; endfunction + endclass + Empty object; + initial begin + result = object.randomize(); + hooks = Empty::calls; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("null_randomize.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); + assert_eq!(sim.get(sim.signal("hooks")), 0u8.into()); + assert_eq!(sim.get(sim.signal("result")), 0u8.into()); + } +} + +sv_backends! { + fn class_randomize_rejects_dynamic_base_handle(sim) { + @setup { + let source = r#"module Top(output int value, hooks, result); + class Base; + rand int x = 77; + static int calls; + function void pre_randomize(); calls++; endfunction + function void post_randomize(); calls++; endfunction + endclass + class Derived extends Base; + constraint c { x == 1; } + endclass + Base b; + Derived d; + initial begin + d = new; + b = d; + result = b.randomize(); + value = b.x; + hooks = Base::calls; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("base_randomize.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("randomization through a base handle"), "{error}"); + assert_eq!(sim.get(sim.signal("value")), 77u8.into()); + assert_eq!(sim.get(sim.signal("hooks")), 0u8.into()); + assert_eq!(sim.get(sim.signal("result")), 0u8.into()); + } +} + +sv_backends! { + fn class_randomize_checkpoint_four_state(sim) { + @setup { + let source = r#"module Top(output bit [63:0] value); + timeunit 1ps / 1ps; + class C; rand bit [63:0] x; endclass + C c; + initial begin + c = new; + c.srandom(44); + void'(c.randomize()); + value = c.x; + #10; + void'(c.randomize()); + value = c.x; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("random_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + let value = sim.signal("value"); + sim.run_until(15).unwrap(); + let expected = sim.get_four_state(value); + sim.restore(&checkpoint).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } +} + +sv_backends! { + fn class_constructor_checkpoint_restores_process_rng(sim) { + @setup { let source = r#" + module Top(input bit clk, output bit [63:0] value); + class C; rand bit [63:0] x; endclass + C c; + always @(posedge clk) begin + c = new; + void'(c.randomize()); + value = c.x; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("constructor_rng.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + sim.tick(clk).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..4 { + sim.tick(clk).unwrap(); + expected.push(sim.get_four_state(value)); + } + assert!(expected.windows(2).any(|pair| pair[0] != pair[1])); + sim.restore(&checkpoint).unwrap(); + for expected in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } + } +} + +sv_backends! { + fn class_randomization_mode_bit_argument(sim) { @case "class::randomization_mode_bit_argument"; } + fn class_randomization_inheritance(sim) { @case "class::randomization_inheritance"; } + fn class_randomization_modes_and_selection(sim) { @case "class::randomization_modes_and_selection"; } + fn class_randomization_pre_hook_controls_modes(sim) { @case "class::randomization_pre_hook_controls_modes"; } +} + +sv_backends! { + fn class_random_modes_checkpoint_four_state(sim) { + @setup { let source = r#" + module Top(input bit enable, output int mode, output bit [63:0] value); + timeunit 1ps / 1ps; + class C; rand bit [63:0] x = 17; endclass + C c; + initial begin + c = new; + c.x.rand_mode(0); + #10 if (enable) c.x.rand_mode(1); + #10; + void'(c.randomize()); + value = c.x; + mode = c.x.rand_mode(); + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("mode_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let saved = sim.checkpoint().unwrap(); + let enable = sim.signal("enable"); + sim.modify(|io| io.set(enable, 1u8)).unwrap(); + sim.run_until(25).unwrap(); + assert_eq!(sim.get(sim.signal("mode")), 1u8.into()); + sim.restore(&saved).unwrap(); + sim.run_until(25).unwrap(); + assert_eq!(sim.get(sim.signal("mode")), 0u8.into()); + assert_eq!(sim.get_four_state(sim.signal("value")), (17u8.into(), 0u8.into())); + } + + fn class_random_selection_spans_multiple_words(sim) { + @setup { + let properties = (0..70).map(|i| format!("p{i}")).collect::>().join(", "); + let source = format!(r#" + module Top(output bit done, output int errors); + class C; + bit [63:0] {properties}; + endclass + C c, reference; + initial begin + c = new; reference = new; + c.srandom(71); reference.srandom(71); + if (!c.randomize(p69) || !reference.randomize(p0)) errors++; + if (c.p69 != reference.p0 || c.p0 != 0 || c.p68 != 0) errors++; + done = 1; + end + endmodule + "#); + } + @build celox::Simulation::from_sv_sources(vec![(source.as_str(), Path::new("wide_selection.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + assert_eq!(sim.get(sim.signal("errors")), 0u8.into()); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 2722e799c75..af7fea78edf 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -101,9 +101,43 @@ variable or advancing the random stream. Calls follow procedural statement order and short-circuit evaluation, and use the calling process's persistent random stream (IEEE 1800-2023 18.12). -Constraints (`with`), class methods, enum variables, unpacked arrays, nets, +Constraints (`with`), enum variables, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. +### Class randomization + +`object.randomize()` randomizes enabled `rand` properties and returns signed +`int` value `1`. Supported properties are 2-state, non-enum integral values up +to 64 bits in classes without constraints. Inherited properties are included, +and a call through a base handle uses the dynamic object's class and its +`pre_randomize()` / `post_randomize()` hooks. A derived hook replaces the base +hook; call `super.pre_randomize()` or `super.post_randomize()` explicitly to +include the base hook's work (IEEE 1800-2023 18.6.2). Hooks must be functions +without arguments, non-static and non-virtual. Calls inside a class may use +`randomize()` or `this.randomize()`. + +`object.member.rand_mode(0)` disables a random property; `rand_mode(1)` enables +it, and `object.member.rand_mode()` returns its current mode as signed `int`. +The setter's argument is a `bit`. `object.rand_mode(bit)` sets all random +properties, including inherited ones. All start enabled, and aliases share the +same modes (18.8). + +`object.randomize(x, y)` temporarily selects exactly those instance properties, +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. + +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 +RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. +`randc` randomization, constraints, `with`, static random properties, and random +enum/array/object/string properties remain unsupported. A constrained dynamic +subclass is rejected rather than silently randomizing only its base properties. +A call through `null` is a runtime error. + ### Time literal delays {#time-literal-delays} Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 2662f0b5f7b..c10c355185b 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -92,9 +92,37 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います (IEEE 1800-2023 18.12)。 -`with` 制約、class メソッド、enum 変数、unpacked 配列、net、定数、 +`with` 制約、enum 変数、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 +### クラスの乱数化 + +`object.randomize()` は有効な `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 +制約のないクラスで、64ビット以下の2値・非enum整数型に対応します。 +継承したプロパティも対象になり、基底型のハンドルを通した呼び出しでも、実際のオブジェクトの +クラスと `pre_randomize()` / `post_randomize()` を使います。子クラスでフックを定義すると +親のフックを置き換えるため、親の処理も必要なら `super.pre_randomize()` などを明示的に呼びます +(IEEE 1800-2023 18.6.2)。フックは引数なし・非static・非virtualの関数に限ります。 +クラス内では `randomize()` や `this.randomize()` と書けます。 + +`object.member.rand_mode(0)` で乱数プロパティを無効化し、`rand_mode(1)` で有効化します。 +引数なしの `object.member.rand_mode()` は現在のモードを signed `int` で返します。 +設定側の引数型は `bit` です。`object.rand_mode(bit)` は継承分を含む全乱数プロパティに適用します。 +初期状態はすべて有効で、aliasは同じモードを共有します(18.8)。 + +`object.randomize(x, y)` はその呼び出しに限り対象を指定します。対応型なら `rand` でない +プロパティも指定できます。名前は呼び出し元ではなくreceiverのクラスで解決し、式やアクセス権のない +メンバーは拒否します。一時モードはpreフックの前に設定し、postフックの後に復元します。 +フックから一時モードを参照・変更できます。`randomize(null)` は乱数生成や代入を行わずフックを +呼びます(18.11)。この形式でも制約付きクラスは未対応です。 + +オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 +`object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します +(18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 +`null` を通した呼び出しは実行時エラーです。 + ### 時間リテラルによる遅延 {#time-literal-delays} 遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に