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
38 changes: 36 additions & 2 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,44 @@ 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::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)?;
Expand All @@ -94,7 +122,13 @@ impl Ff<'_, '_> {
| ObjectOp::ClassOf
| ObjectOp::Random
| ObjectOp::Seed
| ObjectOp::Check(_) => None,
| 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;
Expand Down
26 changes: 26 additions & 0 deletions crates/celox-heap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,32 @@ mod tests {
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();
Expand Down
61 changes: 61 additions & 0 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,20 @@ pub const NULL: Handle = 0;
pub(crate) struct Object {
class: u32,
random_state: u64,
random_modes: RandomModes,
saved_random_modes: Vec<RandomModes>,
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<u32, bool>,
/// Non-rand properties temporarily made random by an argument list.
selected: fxhash::FxHashSet<u32>,
}

impl Object {
pub(crate) fn size(&self) -> usize {
self.bytes.len()
Expand Down Expand Up @@ -60,6 +69,8 @@ impl Heap {
Object {
class,
random_state: 0,
random_modes: RandomModes::default(),
saved_random_modes: Vec::new(),
bytes: vec![0; size].into(),
handles: Vec::new(),
},
Expand Down Expand Up @@ -88,6 +99,56 @@ impl Heap {
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;
Expand Down
38 changes: 38 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ 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 {
Expand Down Expand Up @@ -181,6 +192,33 @@ impl Heap {
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}"),
}
}
Expand Down
29 changes: 25 additions & 4 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ 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,
Expand Down Expand Up @@ -93,15 +97,27 @@ pub(super) struct Class {
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"));
}
if self.base.is_some() {
return Err(unsupported("class randomize with inheritance"));
}
for property in &self.properties {
if property.randc {
return Err(unsupported("class randomize with randc properties"));
Expand Down Expand Up @@ -428,11 +444,16 @@ 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,
Expand All @@ -451,7 +472,7 @@ 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") {
if matches!(method_name.as_str(), "randomize" | "srandom" | "rand_mode") {
return Err(unsupported(
"overriding built-in class randomization methods",
));
Expand Down
35 changes: 24 additions & 11 deletions crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ fn class_signatures(
context,
);
}
for method in ["randomize", "srandom"] {
for method in ["randomize", "srandom", "rand_mode"] {
let mut formals = vec![(
FunctionArgumentMetadata {
name: classes::THIS.into(),
Expand All @@ -478,16 +478,29 @@ fn class_signatures(
},
handle.clone(),
)];
if method == "srandom" {
formals.push((
FunctionArgumentMetadata {
name: "seed".into(),
direction: ParamDirection::Input,
has_default: false,
},
procedural::int_type(),
));
}
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,
Expand Down
4 changes: 2 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,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,
Expand Down
Loading
Loading