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
4 changes: 2 additions & 2 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -649,8 +649,8 @@ chapter-18/18.7--in-line-constraints--randomize_5.sv 2state fail
chapter-18/18.7--in-line-constraints--randomize_5.sv 4state fail
chapter-18/18.7--in-line-constraints--randomize_6.sv 2state fail
chapter-18/18.7--in-line-constraints--randomize_6.sv 4state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 2state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 4state fail
chapter-18/18.7.1--local-scope-resolution_0.sv 2state pass
chapter-18/18.7.1--local-scope-resolution_0.sv 4state pass
chapter-18/18.7.1--local-scope-resolution_1.sv 2state fail
chapter-18/18.7.1--local-scope-resolution_1.sv 4state fail
chapter-18/18.8--disabling-random-variables-with-rand_mode_0.sv 2state fail
Expand Down
14 changes: 13 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,19 @@ impl Ff<'_, '_> {
buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, value, count]);
}
let program = self.heap_call(ops::FREEZE, &[buffer]);
self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check])
if args.len() == 2 {
self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check])
} else {
let mut inputs = self.heap_call(ops::NEW, &[]);
let one = self.constant64(1);
inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, check, one]);
for value in &args[2..] {
let value = self.integer_of_width(value, 64, false)?;
let eight = self.constant64(8);
inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, value, eight]);
}
self.heap_call(ops::OBJECT_RANDOMIZE_INPUTS, &[object, program, inputs])
}
}
ObjectOp::Container { .. } => unreachable!("handled by container_call"),
ObjectOp::New {
Expand Down
53 changes: 50 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,20 +115,31 @@ pub(in crate::ast) fn bind(
tree: &AnalysisContext<'_>,
properties: &[Property],
env: &HashMap<String, i128>,
) -> Result<ConstraintExpr, String> {
bind_inputs(id, tree, properties, env, &HashMap::default())
}

pub(in crate::ast) fn bind_inputs(
id: ExprId,
tree: &AnalysisContext<'_>,
properties: &[Property],
env: &HashMap<String, i128>,
inputs: &HashMap<String, (usize, u32, bool)>,
) -> Result<ConstraintExpr, String> {
fn expression(
id: ExprId,
tree: &AnalysisContext<'_>,
properties: &[Property],
env: &HashMap<String, i128>,
inputs: &HashMap<String, (usize, u32, bool)>,
depth: usize,
budget: &std::cell::Cell<usize>,
) -> Result<Typed, String> {
if depth > 64 {
return Err("constraint expression nesting limit".into());
}
charge(budget)?;
let recurse = |id| expression(id, tree, properties, env, depth + 1, budget);
let recurse = |id| expression(id, tree, properties, env, inputs, depth + 1, budget);
let native = tree.declarations();
Ok(match &native.expression(id).kind {
ExprKind::Group(id) => return recurse(*id),
Expand All @@ -145,6 +156,12 @@ pub(in crate::ast) fn bind(
width: property.field.width,
signed: property.field.signed,
}
} else if let Some(&(index, width, signed)) = inputs.get(&name) {
Typed {
kind: Kind::Leaf(ConstraintExpr::Input { index, width }),
width,
signed,
}
} else if env.contains_key(&name) {
// Parameter type reconstruction belongs to the general expression binder.
// Do not guess its width/sign here.
Expand All @@ -153,6 +170,21 @@ pub(in crate::ast) fn bind(
return Err(format!("constraint variable `{name}`"));
}
}
ExprKind::Member {
expression,
separator,
name,
} if separator == "::"
&& matches!(&native.expression(*expression).kind, ExprKind::Name(root) if root.spelling == "local") =>
{
let key = format!("local::{}", instances::normalize_identifier(&name.spelling));
let &(index, width, signed) = inputs.get(&key).ok_or("inline local variable")?;
Typed {
kind: Kind::Leaf(ConstraintExpr::Input { index, width }),
width,
signed,
}
}
ExprKind::Literal(text) => {
if text.starts_with("'0") || text.starts_with("'1") {
return Err("unbased unsized constraint literal".into());
Expand Down Expand Up @@ -286,8 +318,16 @@ pub(in crate::ast) fn bind(
_ => return Err("unsupported scalar constraint expression".into()),
})
}
expression(id, tree, properties, env, 0, &std::cell::Cell::new(16_384))
.map(|value| emit(value, None))
expression(
id,
tree,
properties,
env,
inputs,
0,
&std::cell::Cell::new(16_384),
)
.map(|value| emit(value, None))
}

impl Class {
Expand Down Expand Up @@ -332,10 +372,15 @@ pub(in crate::ast) struct Inline {
pub key: usize,
pub class: std::rc::Rc<Class>,
pub constraints: Vec<ConstraintExpr>,
pub inputs: Vec<Type>,
pub dimensions: PackedDimensions,
}

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

pub fn name(&self, class: &str) -> String {
format!("{class}::$inline_randomize@{}", self.key)
}
Expand All @@ -348,6 +393,7 @@ pub(in crate::ast) struct InlineRequest {
pub key: usize,
pub class: Class,
pub constraints: Vec<ConstraintExpr>,
pub inputs: Vec<Type>,
}

impl Inline {
Expand All @@ -356,6 +402,7 @@ impl Inline {
key: self.key,
class: (*self.class).clone(),
constraints: self.constraints.clone(),
inputs: self.inputs.clone(),
}
}
}
106 changes: 101 additions & 5 deletions crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -955,12 +955,96 @@ pub(super) fn randomize_with(
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"))?
let constraint_ids = constraints.ok_or_else(|| unsupported("inline constraint form"))?;
let mut inputs = HashMap::default();
let mut input_types = Vec::new();
let mut input_values = Vec::new();
let mut pending = constraint_ids.to_vec();
while let Some(id) = pending.pop() {
let candidate = match &native.expression(id).kind {
ExprKind::Name(name) => {
let name = instances::normalize_identifier(&name.spelling);
if class.properties.iter().any(|p| p.name == name) {
None
} else if class.statics.iter().any(|p| p.name == name) {
return Err(unsupported("static properties in inline constraints"));
} else {
Some((name.clone(), name))
}
}
ExprKind::Member {
expression,
separator,
name,
} if separator == "::"
&& matches!(&native.expression(*expression).kind, ExprKind::Name(root) if root.spelling == "local") =>
{
let name = instances::normalize_identifier(&name.spelling);
Some((format!("local::{name}"), name))
}
ExprKind::Group(id) | ExprKind::Unary { expression: id, .. } => {
pending.push(*id);
None
}
ExprKind::Binary { left, right, .. } => {
pending.extend([*right, *left]);
None
}
ExprKind::Set(items) => {
for item in items {
match item.kind {
celox_sv_syntax::DimensionKind::Index(id) => pending.push(id),
celox_sv_syntax::DimensionKind::Range { left, right } => {
pending.extend([right, left])
}
_ => {}
}
}
None
}
_ => None,
};
let Some((key, name)) = candidate else {
continue;
};
if inputs.contains_key(&key) {
continue;
}
let variable = dimensions
.get(&name)
.ok_or_else(|| unsupported(format!("inline local variable `{name}`")))?;
if variable.real
|| variable.string
|| variable.class.is_some()
|| variable.container.is_some()
|| !variable.unpacked.is_empty()
|| !variable.is_2state
{
return Err(unsupported(
"inline inputs require two-state scalar variables",
));
}
let value = Expr::Ident(name);
let width = expr_static_width(&tree.state, &value, dimensions)
.filter(|width| (1..=64).contains(width))
.ok_or_else(|| unsupported("inline input width"))?;
let mut ty = classes::unsigned_type(width);
ty.is_signed = variable.signed;
inputs.insert(key, (input_types.len(), width as u32, variable.signed));
input_types.push(ty);
input_values.push(Some(value));
}
let constraints = constraint_ids
.iter()
.map(|&id| {
classes::constraints::bind(id, tree, &class.properties, &dimensions.const_env)
.map_err(|reason| unsupported(format!("inline constraints: {reason}")))
classes::constraints::bind_inputs(
id,
tree,
&class.properties,
&dimensions.const_env,
&inputs,
)
.map_err(|reason| unsupported(format!("inline constraints: {reason}")))
})
.collect::<Converted<Vec<_>>>()?;
let selection = random_selection(tree, dimensions, &method_name, arguments, native)?;
Expand All @@ -975,13 +1059,25 @@ pub(super) fn randomize_with(
key,
class,
constraints,
inputs: input_types,
dimensions: dimensions.clone(),
};
let name = inline.name(owner);
// Argument evaluation is left-to-right. Prepare the receiver and run its
// pre-hook before sampling any caller-scope input. Evaluate the receiver once.
let handle = if input_values.is_empty() {
handle
} else {
Expr::Call {
callee: Callee::Subroutine(inline.prepare_name(owner)),
args: vec![Some(handle), Some(selection.clone())],
arg_order: Vec::new(),
}
};
tree.state.inline_randomizations.borrow_mut().push(inline);
Ok(Expr::Call {
callee: Callee::Subroutine(name),
args: vec![Some(handle), Some(selection)],
args: [vec![Some(handle), Some(selection)], input_values].concat(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read captured constraint variables after pre_randomize

When pre_randomize() modifies a caller-scope variable used by the inline constraint, passing that variable as an input argument here snapshots its value before the hook executes. In procedural/randomization.rs, lower_methods() runs the hook before solving, but the solver receives the already-copied $input parameter. For example, if module-scope wanted starts at 2 and the hook changes it to 5, p.randomize() with { x == wanted; } incorrectly solves for x == 2. Preserve access to mutable caller-scope variables until after the pre-hook so solving uses their current values.

Useful? React with 👍 / 👎.

arg_order: Vec::new(),
})
}
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/ast/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ impl ScopeImports {
if package == "std" && normalize_identifier(&name.spelling) == "randomize" {
continue;
}
// Inline constraint local:: lookup bypasses the receiver class,
// not through a package dependency (18.7.1).
if package == "local" {
continue;
}
// `C::name` names a member of class `C` (IEEE 1800-2023 8.23).
if visible_class(tree, &package) {
continue;
Expand Down
Loading
Loading