Skip to content
Closed
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
9 changes: 9 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ 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::RandomCyclic { offset, count } => {
let object = self.handle(&args[0])?;
let count = self.constant64(u64::from(*count));
self.heap_call(
ops::encode(ops::OBJECT_RANDOM_CYCLIC, u64::from(*offset)),
&[object, count],
)
}
ObjectOp::Random
| ObjectOp::Check(_)
| ObjectOp::ModeGet(..)
Expand Down Expand Up @@ -121,6 +129,7 @@ impl Ff<'_, '_> {
ObjectOp::Store(_)
| ObjectOp::ClassOf
| ObjectOp::Random
| ObjectOp::RandomCyclic { .. }
| ObjectOp::Seed
| ObjectOp::Check(_)
| ObjectOp::ModeGet(..)
Expand Down
80 changes: 75 additions & 5 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub(crate) struct Object {
random_state: u64,
random_modes: RandomModes,
saved_random_modes: Vec<RandomModes>,
/// Remaining domain indices for each randc property, keyed by byte offset.
random_cycles: fxhash::FxHashMap<u32, Vec<u16>>,
bytes: Box<[u8]>,
/// Byte offsets of the handle properties, with what they refer to.
pub(crate) handles: Vec<(u32, HandleKind)>,
Expand All @@ -30,6 +32,14 @@ struct RandomModes {
}

impl Object {
fn random(&mut self) -> u64 {
self.random_state = self.random_state.wrapping_add(0x9e3779b97f4a7c15);
let mut word = self.random_state;
word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb);
word ^ (word >> 31)
}

pub(crate) fn size(&self) -> usize {
self.bytes.len()
}
Expand Down Expand Up @@ -71,6 +81,7 @@ impl Heap {
random_state: 0,
random_modes: RandomModes::default(),
saved_random_modes: Vec::new(),
random_cycles: Default::default(),
bytes: vec![0; size].into(),
handles: Vec::new(),
},
Expand All @@ -92,11 +103,36 @@ impl Heap {
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)
object.random()
}

/// Draw without replacement from an immutable domain (IEEE 1800-2023
/// 18.4.2). Lazy Fisher-Yates uses bounded storage and uniform draws.
/// Seeding changes the RNG, but does not discard an unfinished cycle.
pub(crate) fn random_cyclic_object(&mut self, handle: Handle, offset: u32, count: u64) -> u64 {
assert!((1..=256).contains(&count), "invalid randc domain size");
let Some(object) = self.object_mut(handle) else {
return 0;
};
let remaining = object.random_cycles.entry(offset).or_default();
if remaining.is_empty() {
remaining.extend(0..count as u16);
}
let count = remaining.len() as u64;
let threshold = count.wrapping_neg() % count;
let index = loop {
let draw = object.random();
if draw >= threshold {
break (draw % count) as usize;
}
};
u64::from(
object
.random_cycles
.get_mut(&offset)
.unwrap()
.swap_remove(index),
)
}

/// Random properties start enabled. Modes are shared by aliases of an
Expand Down Expand Up @@ -287,6 +323,40 @@ mod tests {
mod random_tests {
use super::*;

#[test]
fn cyclic_domains_survive_reseeding_and_checkpoint_restore() {
for count in [1, 3, 256] {
let mut heap = Heap::new();
let object = heap.new_object(1, 2);
let other = heap.new_object(1, 2);
heap.seed_object(object, 12);
heap.seed_object(other, 12);
let first = heap.random_cyclic_object(object, 0, count);
assert_eq!(first, heap.random_cyclic_object(other, 0, count));
let mut saved = heap.clone();
let mut seen = crate::HashSet::from_iter([first]);
for _ in 1..count {
// Seeding does not make consumed values eligible again.
heap.seed_object(object, 19);
saved.seed_object(object, 19);
let value = heap.random_cyclic_object(object, 0, count);
assert_eq!(value, saved.random_cyclic_object(object, 0, count));
assert!(seen.insert(value));
}
for offset in [0, 1, 0] {
let seen: crate::HashSet<_> = (0..count)
.map(|_| heap.random_cyclic_object(object, offset, count))
.collect();
assert_eq!(seen.len(), count as usize);
assert!(seen.iter().all(|&value| value < count));
}
assert_eq!(heap.take_fault(), None);
}
let mut heap = Heap::new();
assert_eq!(heap.random_cyclic_object(NULL, 0, 3), 0);
assert_eq!(heap.take_fault(), Some(Fault::NullDereference));
}

#[test]
fn random_streams_are_independent_and_checkpointed() {
let mut heap = Heap::new();
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ pub const OBJECT_MODE_POP: u64 = 59;
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;
/// Draw a randc domain index; parameter is the property offset, b its domain size.
pub const OBJECT_RANDOM_CYCLIC: u64 = 62;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -187,6 +189,7 @@ impl Heap {
}
OBJECT_CLASS => self.class_of(a as Handle).into(),
OBJECT_RANDOM => self.random_object(a as Handle),
OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b),
OBJECT_SEED => {
self.seed_object(a as Handle, b as u32);
0
Expand Down
4 changes: 2 additions & 2 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ mod expressions;
mod ff_process;
mod functions;
mod generate;
mod imports;
pub(crate) mod imports;
mod inlining;
mod instances;
mod interface_ast;
Expand All @@ -147,7 +147,7 @@ mod subroutine_owners;
pub(crate) mod timescales;
pub(crate) mod type_parameters;
mod types;
mod validation;
pub(crate) mod validation;
pub(crate) mod warnings;

use array_compatibility::selected_unpacked_shape;
Expand Down
27 changes: 24 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ pub(super) struct Property {
pub initializer: Option<celox_sv_syntax::ExprId>,
}

impl Property {
pub fn cyclic_domain_size(&self) -> Option<u16> {
if self.field.handle.is_some() {
return None;
}
if self.r#type.is_enum {
self.r#type.enum_values.as_ref().and_then(|values| {
(1..=256)
.contains(&values.len())
.then_some(values.len() as u16)
})
} else {
(1..=8)
.contains(&self.field.width)
.then(|| 1u16 << self.field.width)
}
}
}

/// A static property of a class: one variable of the module that declares
/// the class, shared by all of its objects (IEEE 1800-2023 8.9).
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -119,10 +138,12 @@ impl Class {
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.randc && property.cyclic_domain_size().is_none() {
return Err(unsupported(
"randc requires a 1-8 bit integer or an enum with at most 256 declared values",
));
}
if property.rand
if (property.rand || property.randc)
&& (property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none()))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,10 @@ pub(super) fn random_selection(
}
if property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
|| property.randc
|| (property.randc && property.cyclic_domain_size().is_none())
{
return Err(unsupported(
"randomize arguments require integral, non-randc properties with a supported enum domain",
"randomize arguments require integral properties with a supported enum domain",
));
}
bits[index + 1] = '1';
Expand Down
8 changes: 4 additions & 4 deletions crates/celox-sv-analyzer/src/ast/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,10 +692,10 @@ fn parameter_literal_references(
ranges.push(item.tokens);
}
let mut references = HashSet::default();
for (_, expression) in native.expression_nodes() {
if !ranges.iter().any(|range| {
range.start <= expression.tokens.start && expression.tokens.end <= range.end
}) {
let scope = crate::source_tree::Ranges::new(ranges.iter().copied());
for id in tree.spans().expressions.within(&ranges) {
let expression = native.expression(id);
if !scope.contains(expression.tokens) {
continue;
}
if let ExprKind::Name(name) | ExprKind::Member { name, .. } = &expression.kind {
Expand Down
103 changes: 68 additions & 35 deletions crates/celox-sv-analyzer/src/ast/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ impl ScopeImports {
// Qualified expression and type names carry their package segment natively.
let native = tree.declarations();
let ranges = active_ranges(tree)?;
for expression in &native.expressions {
let spans = tree.spans();
for id in spans.expressions.within(&ranges) {
let expression = native.expression(id);
if !in_ranges(expression.tokens.start, &ranges) {
continue;
}
Expand Down Expand Up @@ -138,7 +140,8 @@ impl ScopeImports {
}
}
}
for ty in &native.types {
for id in spans.types.within(&ranges) {
let ty = native.data_type(id);
if in_ranges(ty.tokens.start, &ranges)
&& let celox_sv_syntax::DataTypeKind::Named(path) = &ty.kind
&& let [package, name] = path.as_slice()
Expand Down Expand Up @@ -353,6 +356,59 @@ fn in_ranges(offset: usize, ranges: &[celox_sv_syntax::TokenRange]) -> bool {
let next = ranges.partition_point(|range| range.start <= offset);
next > 0 && offset < ranges[next - 1].end
}
/// Whole-file facts the reference collection selects from, built once per
/// file so each scope costs what its own token ranges contain.
#[derive(Debug)]
pub(crate) struct Facts {
/// Token spans of the plain-name packages of qualified names.
qualified_bases: HashSet<(usize, usize)>,
/// First tokens of the bare-name keys of patterns.
pattern_keys: HashSet<usize>,
}

impl Facts {
fn of(tree: &SyntaxTree) -> &Self {
use celox_sv_syntax::ExprKind;
tree.spans().imports.get_or_init(|| {
let native = tree.declarations();
let name = |id| {
matches!(native.expression(id).kind, ExprKind::Name(_))
.then_some(native.expression(id).tokens)
};
let qualified_bases = native
.expressions
.iter()
.filter_map(|expression| match &expression.kind {
ExprKind::Member {
expression,
separator,
..
} if separator == "::" => name(*expression),
_ => None,
})
.map(|tokens| (tokens.start, tokens.end))
.collect();
// Bare pattern keys name members; they do not bind wildcard imports.
let pattern_keys = native
.expressions
.iter()
.flat_map(|expression| match &expression.kind {
ExprKind::Pattern { items, .. } => {
items.iter().filter_map(|item| item.key).collect::<Vec<_>>()
}
_ => Vec::new(),
})
.filter_map(name)
.map(|tokens| tokens.start)
.collect();
Self {
qualified_bases,
pattern_keys,
}
})
}
}

/// Unqualified expression and type references in the selected native scope.
pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap<String, Vec<usize>> {
use celox_sv_syntax::{DataTypeKind, ExprKind};
Expand All @@ -361,33 +417,10 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap<String, Vec<usize>
return HashMap::default();
};
let nested = nested_declarations(tree);
let qualified: HashSet<_> = native
.expressions
.iter()
.filter_map(|expression| match &expression.kind {
ExprKind::Member {
expression,
separator,
..
} if separator == "::" => Some(*expression),
_ => None,
})
.collect();
// Bare pattern keys name members; they do not bind wildcard imports.
let pattern_keys: HashSet<_> = native
.expressions
.iter()
.flat_map(|expression| match &expression.kind {
ExprKind::Pattern { items, .. } => {
items.iter().filter_map(|item| item.key).collect::<Vec<_>>()
}
_ => Vec::new(),
})
.filter_map(|id| {
matches!(native.expression(id).kind, ExprKind::Name(_))
.then_some(native.expression(id).tokens.start)
})
.collect();
let Facts {
qualified_bases,
pattern_keys,
} = Facts::of(tree);
let mut names: HashMap<String, Vec<usize>> = HashMap::default();
let mut add = |name: &str, offset| {
let name = normalize_identifier(name);
Expand All @@ -399,18 +432,18 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap<String, Vec<usize>
names.entry(name).or_default().push(offset);
}
};
for expression in &native.expressions {
let spans = tree.spans();
for id in spans.expressions.within(&ranges) {
let expression = native.expression(id);
if let ExprKind::Name(name) = &expression.kind
&& !pattern_keys.contains(&expression.tokens.start)
&& !qualified.iter().any(|base| {
native.expression(*base).tokens == expression.tokens
&& matches!(&native.expression(*base).kind, ExprKind::Name(_))
})
&& !qualified_bases.contains(&(expression.tokens.start, expression.tokens.end))
{
add(&name.spelling, expression.tokens.start);
}
}
for ty in &native.types {
for id in spans.types.within(&ranges) {
let ty = native.data_type(id);
if let DataTypeKind::Named(path) = &ty.kind
&& let [name] = path.as_slice()
{
Expand Down
Loading
Loading