Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,24 @@ impl Ff<'_, '_> {
self.heap_call(ops::OBJECT_RANDOMIZE_INPUTS, &[object, program, inputs])
}
}
ObjectOp::ConstraintModeGet(index) => {
let object = self.handle(&args[0])?;
self.heap_call(
ops::encode(ops::OBJECT_CONSTRAINT_MODE_GET, u64::from(*index)),
&[object],
)
}
ObjectOp::ConstraintModeSet(index) => {
let object = self.handle(&args[0])?;
let enabled = self.integer_of_width(&args[1], 1, false)?;
self.heap_call(
ops::encode(
ops::OBJECT_CONSTRAINT_MODE_SET,
u64::from(index.unwrap_or(u32::MAX)),
),
&[object, enabled],
)
}
ObjectOp::Container { .. } => unreachable!("handled by container_call"),
ObjectOp::New {
class,
Expand Down Expand Up @@ -161,6 +179,8 @@ impl Ff<'_, '_> {
HandleProperty::Object => celox_design::ValueKind::ObjRef,
}),
ObjectOp::Randomize(_)
| ObjectOp::ConstraintModeGet(_)
| ObjectOp::ConstraintModeSet(_)
| ObjectOp::Store(_)
| ObjectOp::ClassOf
| ObjectOp::Random
Expand Down
52 changes: 52 additions & 0 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ pub(crate) struct Object {
class: u32,
random_state: u64,
random_modes: RandomModes,
constraint_default: bool,
constraint_modes: fxhash::FxHashMap<u32, bool>,
saved_random_modes: Vec<RandomModes>,
/// Remaining domain indices for each randc property, keyed by byte offset.
random_cycles: fxhash::FxHashMap<u32, Vec<u16>>,
Expand Down Expand Up @@ -90,6 +92,8 @@ impl Heap {
class,
random_state: 0,
random_modes: RandomModes::default(),
constraint_default: true,
constraint_modes: Default::default(),
saved_random_modes: Vec::new(),
random_cycles: Default::default(),
bytes: vec![0; size].into(),
Expand All @@ -100,6 +104,28 @@ impl Heap {
handle
}

/// Persistent per-object constraint modes (IEEE 1800-2023 18.9).
pub fn constraint_mode(&mut self, handle: Handle, index: u32) -> bool {
self.object_mut(handle).is_some_and(|object| {
object
.constraint_modes
.get(&index)
.copied()
.unwrap_or(object.constraint_default)
})
}

pub fn set_constraint_mode(&mut self, handle: Handle, index: Option<u32>, enabled: bool) {
if let Some(object) = self.object_mut(handle) {
if let Some(index) = index {
object.constraint_modes.insert(index, enabled);
} else {
object.constraint_modes.clear();
object.constraint_default = enabled;
}
}
}

/// 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) {
Expand Down Expand Up @@ -319,6 +345,32 @@ mod tests {
assert_eq!(heap.class_of(NULL), 0);
}

#[test]
fn constraint_modes_are_object_state_and_do_not_follow_random_mode_scopes() {
let mut heap = Heap::new();
let handle = heap.new_object(1, 4);
assert!(heap.constraint_mode(handle, 0));
let original = heap.clone();
heap.set_constraint_mode(handle, None, false);
heap.set_constraint_mode(handle, Some(1), true);
assert!(!heap.same_contents(&original));
heap.push_random_modes(handle);
heap.set_constraint_mode(handle, Some(0), true);
heap.pop_random_modes(handle);
assert!(heap.constraint_mode(handle, 0));
assert!(heap.constraint_mode(handle, 1));
assert!(!heap.constraint_mode(handle, 2));
let bytes = serde_json::to_vec(&heap.objects[&handle]).unwrap();
let restored: Object = serde_json::from_slice(&bytes).unwrap();
assert_eq!(restored, heap.objects[&handle]);
let copy = heap.copy_object(handle);
heap.set_constraint_mode(copy, None, true);
assert!(heap.constraint_mode(copy, 2));
assert!(!heap.constraint_mode(handle, 2));
assert!(!heap.constraint_mode(NULL, 0));
assert_eq!(heap.take_fault(), Some(Fault::NullDereference));
}

#[test]
fn copies_are_shallow() {
let mut heap = Heap::new();
Expand Down
14 changes: 14 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ pub const OBJECT_RANDOMIZE: u64 = 64;
/// Program b for object a; c is an input buffer (check-only byte followed by
/// big-endian u64 values). The buffer is consumed, including on failure.
pub const OBJECT_RANDOMIZE_INPUTS: u64 = 65;
/// Constraint index is encoded in the parameter; set-all uses u32::MAX.
pub const OBJECT_CONSTRAINT_MODE_GET: u64 = 66;
pub const OBJECT_CONSTRAINT_MODE_SET: u64 = 67;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -248,6 +251,17 @@ impl Heap {
0
}
OBJECT_CHECK => u64::from(self.check_object(a as Handle, parameter as u32)),
OBJECT_CONSTRAINT_MODE_GET => {
self.constraint_mode(a as Handle, parameter as u32) as u64
}
OBJECT_CONSTRAINT_MODE_SET => {
self.set_constraint_mode(
a as Handle,
(parameter != u64::from(u32::MAX)).then_some(parameter as u32),
b & 1 != 0,
);
0
}
OBJECT_MODE_GET => {
u64::from(self.random_mode(a as Handle, parameter as u32, parameter >> 32 != 0))
}
Expand Down
14 changes: 14 additions & 0 deletions crates/celox-heap/src/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ pub struct Field {

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Expr {
/// Top-level named block predicate; inline predicates remain unconditional.
Enabled {
index: u32,
value: Box<Expr>,
},
Literal(u32, u64),
Field(usize),
/// Read-only scalar supplied by this call, never a solver variable.
Expand Down Expand Up @@ -57,6 +62,7 @@ fn boolean(value: Term) -> Term {
impl Expr {
fn term(&self, fields: &[Term], inputs: &[u64]) -> Result<Term, String> {
Ok(match self {
Self::Enabled { .. } => return Err("nested constraint mode predicate".into()),
Self::Literal(width, value) => bv(*width, *value),
Self::Input { index, width } => {
if !(1..=64).contains(width) {
Expand Down Expand Up @@ -221,6 +227,14 @@ impl Heap {
terms.push(term);
}
for constraint in &program.constraints {
let constraint = if let Expr::Enabled { index, value } = constraint {
if !self.constraint_mode(handle, *index) {
continue;
}
value.as_ref()
} else {
constraint
};
formula = and(formula, truth(constraint.term(&terms, inputs)?));
}
let seed = if projection.is_empty() {
Expand Down
14 changes: 11 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,10 @@ 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") {
if matches!(
method_name.as_str(),
"randomize" | "srandom" | "rand_mode" | "constraint_mode"
) {
return Err(unsupported(
"overriding built-in class randomization methods",
));
Expand Down Expand Up @@ -868,7 +871,7 @@ pub(super) fn class(
.unwrap_or_default();
for block in &declaration.constraints {
let block_name = block.name.spelling.clone();
constraints.retain(|(name, _)| *name != block_name);

let expressions = block
.expressions
.as_ref()
Expand All @@ -879,7 +882,12 @@ pub(super) fn class(
.map(|&id| constraints::bind(id, tree, &properties, env))
.collect()
});
constraints.push((block_name, expressions));
// Constraint indices survive overrides, including calls via base handles.
if let Some((_, inherited)) = constraints.iter_mut().find(|(name, _)| *name == block_name) {
*inherited = expressions;
} else {
constraints.push((block_name, expressions));
}
}
let class = Rc::new(Class {
name: name.to_owned(),
Expand Down
9 changes: 7 additions & 2 deletions crates/celox-sv-analyzer/src/ast/classes/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,12 +350,17 @@ impl Class {
});
}
let mut constraints = Vec::new();
for (_, block) in &self.constraints {
for (index, (_, block)) in self.constraints.iter().enumerate() {
constraints.extend(
block
.as_ref()
.map_err(|reason| unsupported(format!("constraints: {reason}")))?
.clone(),
.iter()
.cloned()
.map(|value| ConstraintExpr::Enabled {
index: index as u32,
value: Box::new(value),
}),
);
}
Ok(Program {
Expand Down
5 changes: 3 additions & 2 deletions crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ pub(super) use lvalues::{net_lvalue, variable_lvalue};
pub(super) use objects::{
Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast,
check_access as check_member_access, check_assignment as check_handle_assignment,
constructor as object_constructor, method as object_method, property as object_property,
rand_mode_call as object_rand_mode_call, receiver as object_receiver, this as object_this,
constraint_mode_call as object_constraint_mode_call, constructor as object_constructor,
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,
Expand Down
6 changes: 6 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,12 @@ pub(in crate::ast) fn bind_value(
values.push(value);
continue;
}
if let Some(call) =
objects::constraint_mode_call(tree, id, native, dimensions, false)?
{
values.push(call);
continue;
}
if let Some(call) = objects::rand_mode_call(tree, id, native, dimensions, false)? {
values.push(call);
continue;
Expand Down
117 changes: 117 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,123 @@ pub(super) fn random_selection(
)))
}

/// Constraint block modes are independent of member rand_mode and inline constraints (18.9).
pub(in crate::ast) fn constraint_mode_call(
tree: &AnalysisContext<'_>,
id: ExprId,
native: &Declarations,
dimensions: &PackedDimensions,
allow_set: bool,
) -> Converted<Option<Expr>> {
let (callee, args) = match &native.expression(ungroup(id, native)).kind {
ExprKind::Call {
expression,
arguments,
} => (*expression, arguments.as_slice()),
_ => (id, &[][..]),
};
let (owner, block, handle) = match &native.expression(ungroup(callee, native)).kind {
ExprKind::Member {
expression,
separator,
name,
} if separator == "." && name.spelling == "constraint_mode" => {
if let Some(owner) = native_class(tree, *expression, native, dimensions) {
Comment thread
tignear marked this conversation as resolved.
Resolved
(
owner,
None,
receiver(tree, Some(*expression), native, dimensions)?,
)
} else {
match &native.expression(ungroup(*expression, native)).kind {
ExprKind::Member {
expression: object,
separator,
name,
} if separator == "." => {
let Some(owner) = native_class(tree, *object, native, dimensions) else {
return Ok(None);
};
(
owner,
Some(name.spelling.clone()),
receiver(tree, Some(*object), native, dimensions)?,
)
}
ExprKind::Name(name)
if scope_class(dimensions).is_some()
&& dimensions.get(THIS).is_some()
&& dimensions.get(&name.spelling).is_none() =>
{
(
scope_class(dimensions).unwrap(),
Some(name.spelling.clone()),
this(),
)
}
_ => return Ok(None),
}
}
}
ExprKind::Name(name)
if name.spelling == "constraint_mode"
&& dimensions.get("constraint_mode").is_none() =>
{
let Some(owner) = scope_class(dimensions) else {
return Ok(None);
};
if dimensions.get(THIS).is_none() {
return Err(unsupported("constraint_mode requires an object receiver"));
}
(owner, None, this())
}
_ => return Ok(None),
};
let class = class(tree, dimensions, &owner)?;
if class.constraints.iter().any(|(_, block)| {
block
.as_ref()
.is_err_and(|reason| reason == "unsupported constraint block form")
}) {
return Err(unsupported(
"constraint_mode for external or static constraint blocks",
));
}
let index = block
.map(|name| {
class
.constraints
.iter()
.position(|(block, _)| *block == name)
.map(|index| index as u32)
.ok_or_else(|| unsupported(format!("unknown constraint block {name}")))
})
.transpose()?;
if args.is_empty() {
let index = index
.ok_or_else(|| unsupported("constraint_mode getter requires one named constraint"))?;
return Ok(Some(classes::object_call(
ObjectOp::ConstraintModeGet(index),
vec![handle],
)));
}
if !allow_set {
return Err(unsupported(
"constraint_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(
"constraint_mode setter requires one on_off argument",
));
}
let enabled = bind_value(args[0].value.unwrap(), native, tree, dimensions, None)?;
Ok(Some(classes::object_call(
ObjectOp::ConstraintModeSet(index),
vec![handle, enabled],
)))
}

/// 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(
Expand Down
9 changes: 6 additions & 3 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,9 +762,12 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
root: celox_sv_syntax::ExprId,
) -> Result<Option<Stmt>, AnalyzerError> {
let native = self.tree.declarations();
if let Some(mut call) =
expression_binding::object_rand_mode_call(self.tree, root, native, &self.dims, true)?
{
if let Some(mut call) = expression_binding::object_constraint_mode_call(
self.tree, root, native, &self.dims, true,
)?
.or(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 {
Expand Down
Loading
Loading