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
116 changes: 114 additions & 2 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 @@ -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
37 changes: 26 additions & 11 deletions crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6587,11 +6587,6 @@ fn explicit_output_data_types_default_to_variables() {
#[test]
fn class_randomize_rejects_unsupported_semantics() {
for (members, call, expected) in [
(
"rand int x; constraint c { if (x) x == 1; }",
"c.randomize()",
"constraints",
),
(
"rand int x; constraint c { soft x == 1; }",
"c.randomize()",
Expand All @@ -6603,15 +6598,10 @@ fn class_randomize_rejects_unsupported_semantics() {
"constraints",
),
(
"rand int x; constraint c { x inside {[1:3]}; }",
"rand int x; constraint c { x inside {[1:$]}; }",
"c.randomize()",
"constraint",
),
(
"rand int x; constraint c { (x == 1) -> (x < 3); }",
"c.randomize()",
"constraints",
),
(
"rand int x; constraint c { (x == 1) <-> (x < 3); }",
"c.randomize()",
Expand Down Expand Up @@ -7345,3 +7335,28 @@ fn final_procedures_only_follow_defaults_for_omitted_arguments() {
}
}
}

#[test]
fn class_randomize_bounds_nested_membership_expansion() {
for levels in [4, 25] {
let mut expr = "x".to_owned();
for _ in 0..levels {
expr = format!("({expr}) inside {{0, 1}}");
}
let source = format!(
"module Top; class C; rand bit x; constraint c {{ {expr}; }} endclass C c; initial begin c = new; c.randomize(); end endmodule"
);
let result = analyze_source(&source, Path::new("nested_membership.sv"));
if levels == 4 {
result.expect("small nested membership must remain supported");
} else {
let error = result
.expect_err("expanded membership must be bounded")
.to_string();
assert!(
error.contains("constraint expression expansion limit"),
"{error}"
);
}
}
}
92 changes: 76 additions & 16 deletions crates/celox-sv-syntax/src/parser/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ enum Job {
Block(bool),
Expression,
Set,
Else,
Guard {
condition: ExprId,
first: usize,
start: usize,
negate: bool,
has_else: bool,
},
}

impl Parser<'_> {
Expand Down Expand Up @@ -43,8 +49,6 @@ impl Parser<'_> {
}) {
return Err(self.error("duplicate constraint block"));
}
let mut expressions = Vec::new();
let mut supported = !is_static;
if self.eat(";") {
if let Some(class) = self.class_stack.last_mut() {
class.constraints.push(ClassConstraint {
Expand All @@ -57,6 +61,19 @@ impl Parser<'_> {
if prototype {
return Err(self.error("extern or pure constraint requires a prototype"));
}
let expressions = self.constraint_block()?;
if let Some(class) = self.class_stack.last_mut() {
class.constraints.push(ClassConstraint {
name,
expressions: if is_static { None } else { expressions },
});
}
Ok(())
}

pub(super) fn constraint_block(&mut self) -> Result<Option<Vec<ExprId>>> {
let mut expressions = Vec::new();
let mut supported = true;
self.expect("{")?;
let mut jobs = vec![Job::Block(true)];
while let Some(job) = jobs.pop() {
Expand Down Expand Up @@ -84,18 +101,60 @@ impl Parser<'_> {
jobs.push(Job::Expression);
}
}
Job::Else => {
if self.eat("else") {
Job::Guard {
condition,
first,
start,
negate,
has_else,
} => {
let guard = if negate {
self.node(
start,
ExprKind::Unary {
operator: "!".into(),
expression: condition,
postfix: false,
},
)?
} else {
condition
};
let body: Vec<_> = expressions.drain(first..).collect();
for expression in body {
expressions.push(self.node(
start,
ExprKind::Binary {
left: guard,
operator: "||".into(),
right: expression,
},
)?);
}
if has_else && self.eat("else") {
jobs.push(Job::Guard {
condition,
first: expressions.len(),
start,
negate: false,
has_else: false,
});
jobs.push(Job::Set);
}
}
Job::Expression => {
let start = self.at;
if self.eat("if") {
supported = false;
self.expect("(")?;
self.expression(0)?;
let condition = self.expression(0)?;
self.expect(")")?;
jobs.push(Job::Else);
jobs.push(Job::Guard {
condition,
first: expressions.len(),
start,
negate: true,
has_else: true,
});
jobs.push(Job::Set);
} else if self.eat("foreach") {
supported = false;
Expand All @@ -121,7 +180,14 @@ impl Parser<'_> {
supported &= simple;
}
if !soft && self.eat("->") {
supported = false;
let condition = expressions.pop().expect("condition retained");
jobs.push(Job::Guard {
condition,
first: expressions.len(),
start,
negate: true,
has_else: false,
});
jobs.push(Job::Set);
} else {
if self.eat("dist") {
Expand All @@ -134,13 +200,7 @@ impl Parser<'_> {
}
}
}
if let Some(class) = self.class_stack.last_mut() {
class.constraints.push(ClassConstraint {
name,
expressions: supported.then_some(expressions),
});
}
Ok(())
Ok(supported.then_some(expressions))
}

fn constraint_condition(&mut self) -> Result<(ExprId, bool)> {
Expand Down
10 changes: 8 additions & 2 deletions crates/celox-sv-syntax/src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3047,10 +3047,16 @@ fn malformed_array_method_with_is_rejected() {
#[test]
fn constraints_retain_simple_expressions_and_mark_other_forms() {
let tree = parse(
"class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } endclass",
"class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } constraint c { soft x == 1; } constraint d { if (1) {} } endclass",
);
let blocks = &tree.classes[0].constraints;
assert_eq!(blocks[0].name.spelling, "a");
assert_eq!(blocks[0].expressions.as_ref().unwrap().len(), 2);
assert!(blocks[1].expressions.is_none());
let guarded = blocks[1].expressions.as_ref().unwrap();
assert_eq!(guarded.len(), 1);
assert!(
matches!(&tree.expression(guarded[0]).kind, ExprKind::Binary { operator, .. } if operator == "||")
);
assert!(blocks[2].expressions.is_none());
assert!(blocks[3].expressions.as_ref().unwrap().is_empty());
}
Loading
Loading