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-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub(super) struct AnalysisState {
interfaces: interface_ast::State,
dimensions: dimensions::State,
root_subroutines: std::cell::Cell<bool>,
inline_randomizations: RefCell<Vec<classes::constraints::Inline>>,
next_call_site: std::rc::Rc<std::cell::Cell<usize>>,
timescales: timescales::State,
diagnostics: RefCell<Vec<warnings::AnalyzerWarning>>,
Expand Down Expand Up @@ -1308,6 +1309,13 @@ impl Module {
)?);
(subroutines, comb_processes, ff_processes, initial_processes)
};
let (inline_subroutines, inline_randomizations) =
procedural::randomization::inline_subroutines(
syntax_tree,
&mut body_state,
&packed_dimensions,
)?;
subroutines.extend(inline_subroutines);
// Static locals of the processes that keep their value are variables
// of the module, initialized once with the declaration initializers.
let statics: HashMap<String, Type> = body_state.statics.drain(..).collect();
Expand Down Expand Up @@ -1410,6 +1418,7 @@ impl Module {
// A package keeps its symbols for the scopes that use it.
let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols {
classes: classes::scope_classes(syntax_tree, &const_env),
inline_randomizations,
declarations_only: imported.declarations_only,
type_parameter_bindings: HashMap::default(),
pattern_parameter_bindings: HashMap::default(),
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::rc::Rc;
use super::*;
use crate::system_functions::{HandleProperty, ObjectField, ObjectOp};

mod constraints;
pub(super) mod constraints;
pub(super) mod specializations;

/// Bit width of a handle, see `celox_design::HANDLE_WIDTH`.
Expand Down
153 changes: 150 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,59 @@ use super::*;
use celox_heap::randomization::{Expr as ConstraintExpr, Field, Program};
use celox_sv_syntax::{ExprId, ExprKind};

#[derive(Clone)]
struct Typed {
kind: Kind,
width: u32,
signed: bool,
}
#[derive(Clone)]
enum Kind {
Leaf(ConstraintExpr),
Context(Box<Typed>),
Unary(String, Box<Typed>),
Binary(String, Box<Typed>, Box<Typed>),
}
fn relation(op: &str, left: Typed, right: Typed) -> Typed {
Typed {
kind: Kind::Binary(op.into(), Box::new(left), Box::new(right)),
width: 1,
signed: false,
}
}

// Charge copies before allocating them: source nesting alone does not bound
// the expanded tree of nested membership predicates.
fn bounded_clone(value: &Typed, budget: &std::cell::Cell<usize>) -> Result<Typed, String> {
let mut pending = vec![value];
while let Some(value) = pending.pop() {
charge(budget)?;
match &value.kind {
Kind::Leaf(_) => {}
Kind::Context(child) | Kind::Unary(_, child) => pending.push(child),
Kind::Binary(_, a, b) => pending.extend([a.as_ref(), b.as_ref()]),
}
}
Ok(value.clone())
}

fn charge(budget: &std::cell::Cell<usize>) -> Result<(), String> {
let remaining = budget
.get()
.checked_sub(1)
.ok_or("constraint expression expansion limit")?;
budget.set(remaining);
Ok(())
}

fn sized(value: Typed, width: u32, signed: bool) -> Typed {
Typed {
kind: Kind::Context(Box::new(value)),
width,
signed,
}
}

fn comparison(op: &str) -> bool {
matches!(op, "==" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||")
}
Expand All @@ -24,6 +67,7 @@ fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr {
let (width, signed) = context.unwrap_or((value.width, value.signed));
let (expr, result_width) = match value.kind {
Kind::Leaf(expr) => (expr, value.width),
Kind::Context(child) => (emit(*child, Some((value.width, value.signed))), value.width),
Kind::Unary(op, child) => {
let logical = op == "!";
(
Expand Down Expand Up @@ -66,7 +110,7 @@ fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr {
}
}

pub(super) fn bind(
pub(in crate::ast) fn bind(
id: ExprId,
tree: &AnalysisContext<'_>,
properties: &[Property],
Expand All @@ -78,11 +122,13 @@ pub(super) fn bind(
properties: &[Property],
env: &HashMap<String, i128>,
depth: usize,
budget: &std::cell::Cell<usize>,
) -> Result<Typed, String> {
if depth > 64 {
return Err("constraint expression nesting limit".into());
}
let recurse = |id| expression(id, tree, properties, env, depth + 1);
charge(budget)?;
let recurse = |id| expression(id, tree, properties, env, depth + 1, budget);
let native = tree.declarations();
Ok(match &native.expression(id).kind {
ExprKind::Group(id) => return recurse(*id),
Expand Down Expand Up @@ -138,6 +184,71 @@ pub(super) fn bind(
kind: Kind::Unary(operator.clone(), Box::new(value)),
}
}
ExprKind::Binary {
left,
operator,
right,
} if operator == "inside" => {
let value = recurse(*left)?;
let ExprKind::Set(items) = &native.expression(*right).kind else {
return Err("constraint inside set".into());
};
// Determine the context across every member and range endpoint
// before expanding comparisons, so arithmetic cannot truncate
// differently depending on which alternative is being tested.
let mut members = Vec::new();
let mut width = value.width;
let mut signed = value.signed;
for item in items {
use celox_sv_syntax::DimensionKind;
let (low, high) = match item.kind {
DimensionKind::Index(id) => (recurse(id)?, None),
DimensionKind::Range { left, right } => {
(recurse(left)?, Some(recurse(right)?))
}
_ => return Err("constraint inside range".into()),
};
for operand in std::iter::once(&low).chain(high.iter()) {
width = width.max(operand.width);
signed &= operand.signed;
}
members.push((low, high));
}
let value = sized(value, width, signed);
let mut alternatives = Vec::new();
for (low, high) in members {
charge(budget)?;
let left = bounded_clone(&value, budget)?;
let low = sized(low, width, signed);
let predicate = if let Some(high) = high {
relation(
"&&",
relation(">=", left, low),
relation(
"<=",
bounded_clone(&value, budget)?,
sized(high, width, signed),
),
)
} else {
relation("==", left, low)
};
alternatives.push(predicate);
}
// A balanced OR tree bounds recursion for large membership sets.
while alternatives.len() > 1 {
let mut next = Vec::new();
let mut items = alternatives.into_iter();
while let Some(a) = items.next() {
next.push(match items.next() {
Some(b) => relation("||", a, b),
None => a,
});
}
alternatives = next;
}
alternatives.pop().ok_or("empty constraint inside set")?
}
ExprKind::Binary {
left,
operator,
Expand Down Expand Up @@ -175,7 +286,8 @@ pub(super) fn bind(
_ => return Err("unsupported scalar constraint expression".into()),
})
}
expression(id, tree, properties, env, 0).map(|value| emit(value, None))
expression(id, tree, properties, env, 0, &std::cell::Cell::new(16_384))
.map(|value| emit(value, None))
}

impl Class {
Expand Down Expand Up @@ -212,3 +324,38 @@ impl Class {
})
}
}

/// A generated call-specific method. Its immutable predicates never change the
/// object's persistent constraints, including during nested hook calls.
#[derive(Clone)]
pub(in crate::ast) struct Inline {
pub key: usize,
pub class: std::rc::Rc<Class>,
pub constraints: Vec<ConstraintExpr>,
pub dimensions: PackedDimensions,
}

impl Inline {
pub fn name(&self, class: &str) -> String {
format!("{class}::$inline_randomize@{}", self.key)
}
}

/// Bound inline predicates survive package imports without retaining syntax or
/// the declaring scope's dimensions. Consumer scopes can add dispatch targets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::ast) struct InlineRequest {
pub key: usize,
pub class: Class,
pub constraints: Vec<ConstraintExpr>,
}

impl Inline {
pub fn request(&self) -> InlineRequest {
InlineRequest {
key: self.key,
class: (*self.class).clone(),
constraints: self.constraints.clone(),
}
}
}
13 changes: 13 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 @@ -903,6 +903,19 @@ pub(in crate::ast) fn bind_value(
ExprKind::Concatenation(_) => {
return Err(unsupported("empty unpacked array concatenation"));
}
ExprKind::RandomizeWith {
expression,
constraints,
} => {
values.push(objects::randomize_with(
tree,
*expression,
constraints.as_deref(),
native,
dimensions,
)?);
continue;
}
ExprKind::ArrayMethodWith { .. } => {
return Err(unsupported("array method with expression"));
}
Expand Down
52 changes: 52 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 @@ -933,3 +933,55 @@ fn check_random_access(
property.protected,
)
}

pub(super) fn randomize_with(
tree: &AnalysisContext<'_>,
expression: ExprId,
constraints: Option<&[ExprId]>,
native: &Declarations,
dimensions: &PackedDimensions,
) -> Converted<Expr> {
let (callee, arguments) = match &native.expression(ungroup(expression, native)).kind {
ExprKind::Call {
expression,
arguments,
} => (*expression, arguments.as_slice()),
_ => (expression, &[][..]),
};
let (method_name, _, receiver) = method(tree, callee, native, dimensions)?
.filter(|(name, _, _)| name.ends_with("::randomize"))
.ok_or_else(|| unsupported("inline constraints require class randomize"))?;
let owner = method_name.strip_suffix("::randomize").unwrap();
let class = class(tree, dimensions, owner)?;
// Inline constraints need the solver even on otherwise unconstrained classes.
class.constraint_program()?;
let constraints = constraints
.ok_or_else(|| unsupported("inline constraint form"))?
.iter()
.map(|&id| {
classes::constraints::bind(id, tree, &class.properties, &dimensions.const_env)
.map_err(|reason| unsupported(format!("inline constraints: {reason}")))
})
.collect::<Converted<Vec<_>>>()?;
let selection = random_selection(tree, dimensions, &method_name, arguments, native)?;
let handle = match receiver {
Receiver::Handle(id) => bind_value(id, native, tree, dimensions, None)?,
Receiver::This => this(),
Receiver::Static => return Err(unsupported("inline randomize object receiver")),
};
let key = tree.state.next_call_site.get();
tree.state.next_call_site.set(key + 1);
let inline = classes::constraints::Inline {
key,
class,
constraints,
dimensions: dimensions.clone(),
};
let name = inline.name(owner);
tree.state.inline_randomizations.borrow_mut().push(inline);
Ok(Expr::Call {
callee: Callee::Subroutine(name),
args: vec![Some(handle), Some(selection)],
arg_order: Vec::new(),
})
}
11 changes: 9 additions & 2 deletions crates/celox-sv-analyzer/src/ast/parameters/skipped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ pub(in crate::ast) fn validate(
ExprKind::Copy(_) => {
return Err(unsupported("shallow copy in skipped operand"));
}
ExprKind::ArrayMethodWith { .. } => {
ExprKind::ArrayMethodWith { .. } | ExprKind::RandomizeWith { .. } => {
return Err(unsupported("array method with expression"));
}
ExprKind::Parameterized { .. } => {
Expand Down Expand Up @@ -587,7 +587,7 @@ pub(in crate::ast) fn literal_widths(
visited.push(id);
let add = |jobs: &mut Vec<_>, id| jobs.push((id, evaluated, shape));
match &native.expression(id).kind {
ExprKind::ArrayMethodWith { .. } => {
ExprKind::ArrayMethodWith { .. } | ExprKind::RandomizeWith { .. } => {
return Err(unsupported("array method with expression"));
}
ExprKind::Literal(text) if evaluated => {
Expand Down Expand Up @@ -1164,6 +1164,13 @@ pub(in crate::ast) fn children(
then_expression,
else_expression,
} => children.extend([*condition, *then_expression, *else_expression]),
ExprKind::RandomizeWith {
expression,
constraints,
} => {
children.push(*expression);
children.extend(constraints.iter().flatten());
}
ExprKind::ArrayMethodWith {
expression,
predicate,
Expand Down
10 changes: 9 additions & 1 deletion crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod control;
mod final_procedures;
mod foreach;
use foreach::ForeachLoop;
mod randomization;
pub(super) mod randomization;
pub(super) mod timed_tasks;
mod timing;
use crate::procedural::{
Expand Down Expand Up @@ -1254,6 +1254,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
self.rename_expr(&mut value);
return Ok(vec![Stmt::Eval(value)]);
}
if matches!(
native.expression(query_root).kind,
celox_sv_syntax::ExprKind::RandomizeWith { .. }
) {
let mut call = self.native_value(query_root)?;
self.rename_expr(&mut call);
return Ok(vec![Stmt::Eval(call)]);
}
if let Some(call) = self.method_call_statement(query_root)? {
return Ok(vec![call]);
}
Expand Down
Loading
Loading