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
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1969,6 +1969,8 @@ pub enum PortDirection {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Type {
is_enum: bool,
/// Resolved legal values for a scalar enum; None if its domain is unsupported.
enum_values: Option<Vec<i128>>,
kind: TypeKind,
is_signed: bool,
packed_ranges: Vec<PackedRange>,
Expand All @@ -1986,6 +1988,7 @@ impl Type {
fn implicit() -> Self {
Self {
is_enum: false,
enum_values: None,
kind: TypeKind::Implicit,
is_signed: false,
packed_ranges: Vec::new(),
Expand All @@ -2000,6 +2003,7 @@ impl Type {
Self {
kind,
is_enum: false,
enum_values: None,
is_signed: false,
packed_ranges: Vec::new(),
unpacked_ranges: Vec::new(),
Expand Down
7 changes: 5 additions & 2 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,12 @@ impl Class {
if property.randc {
return Err(unsupported("class randomize with randc properties"));
}
if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) {
if property.rand
&& (property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none()))
{
return Err(unsupported(
"class randomize requires integral non-enum rand properties",
"class randomize requires integral rand properties with a supported enum domain",
));
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ fn extend_variable_dimensions_from_const_env(
let packed_ranges = ranges.split_off(unpacked);
let ty = Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Logic,
is_signed: variable_type_is_signed(const_env, name),
packed_ranges,
Expand Down
11 changes: 10 additions & 1 deletion crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,16 @@ pub(in crate::ast) fn query_context_for_operand(
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
) -> Converted<PackedDimensions> {
if context.scope_types_complete {
// Literals carry their type in their spelling and cannot reference lexical
// declarations. Pattern elements otherwise rediscover the whole scope for
// each literal while the surrounding declaration is still being bound.
let operand = expression_binding::ungroup(root, tree.declarations());
if context.scope_types_complete
|| matches!(
tree.declarations().expression(operand).kind,
ExprKind::Literal(_)
)
{
return Ok(query_context(context));
}
Ok(query_context(&query_operand_dimensions_id(
Expand Down
56 changes: 56 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,59 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() {
);
}
}

#[test]
fn preliminary_literal_queries_do_not_discover_scope_declarations() {
let tree = crate::source_tree::parse_scope_fixture(
r#"module Top;
logic [7:0] unrelated [0:31];
localparam A = $bits(123);
localparam B = $bits((8'shff));
localparam C = $bits(4'bx);
localparam D = $bits("ab");
localparam E = $bits('1);
endmodule"#,
Path::new("literal_query.sv"),
)
.unwrap();
let tree = AnalysisContext::unspecialized(&tree);
let input = PackedDimensions::default();
let calls = native_calls(&tree);
assert_eq!(calls.len(), 5);
// Keep the discovery path as an independent reference for the result.
let discovered = calls
.iter()
.map(|call| {
let celox_sv_syntax::ExprKind::Call { arguments, .. } =
&tree.declarations().expression(*call).kind
else {
unreachable!()
};
let context =
query_operand_dimensions_id(arguments[0].value.unwrap(), &tree, &input).unwrap();
query_number(
*call,
&tree,
&HashMap::default(),
&HashMap::default(),
Some(&context),
)
})
.collect::<Vec<_>>();
SYNTAX_TYPE_DISCOVERIES.with(|count| count.set(0));
let direct = calls
.iter()
.map(|call| {
query_number(
*call,
&tree,
&HashMap::default(),
&HashMap::default(),
Some(&input),
)
})
.collect::<Vec<_>>();
assert_eq!(&direct[..4], &[Some(32), Some(8), Some(4), Some(16)]);
assert_eq!(direct, discovered);
assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|count| count.get()), 0);
}
9 changes: 5 additions & 4 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ enum Finish {
/// A string operation on the bound children, see [`strings`].
StringCall(StringOp),
/// A read of property `property` of the object handle child.
ObjectLoad(crate::ast::classes::Property),
ObjectLoad(Box<crate::ast::classes::Property>),
/// A call of method subroutine `name` with `formals` formals; the first
/// child is the object handle when `receiver` is one.
MethodCall {
Expand Down Expand Up @@ -756,9 +756,10 @@ pub(in crate::ast) fn bind_value(
let (property, receiver) = objects::property(tree, id, native, dimensions)?
.expect("checked by the guard");
match receiver {
Some(receiver) => {
(Finish::ObjectLoad(property), vec![(receiver, None)])
}
Some(receiver) => (
Finish::ObjectLoad(Box::new(property)),
vec![(receiver, None)],
),
None => {
values.push(objects::load(&property, objects::this()));
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,9 +555,12 @@ pub(super) fn random_selection(
if property.constant {
return Err(unsupported("randomize argument is a const property"));
}
if property.field.handle.is_some() || property.r#type.is_enum || property.randc {
if property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
|| property.randc
{
return Err(unsupported(
"randomize arguments require integral non-enum, non-randc properties",
"randomize arguments require integral, non-randc properties with a supported enum domain",
));
}
bits[index + 1] = '1';
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-sv-analyzer/src/ast/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,11 @@ pub(super) fn coerce_const_parameter_value(value: i128, width: usize, signed: bo
}
}

fn enum_initializer_fits_base_type(value: i128, value_type: ExprType, base_type: ExprType) -> bool {
pub(super) fn enum_initializer_fits_base_type(
value: i128,
value_type: ExprType,
base_type: ExprType,
) -> bool {
// A same-width initializer may change its numeric interpretation when
// the enum base has different signedness, but it does not lose any bits.
if value_type.width <= base_type.width || base_type.width >= 128 {
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap<String, i128>) -
pub(super) fn int_type() -> Type {
Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Bit,
is_signed: true,
packed_ranges: vec![PackedRange::new(
Expand Down
81 changes: 70 additions & 11 deletions crates/celox-sv-analyzer/src/ast/procedural/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub(super) fn lower(
for property in &class.properties {
if property.constant
|| property.field.handle.is_some()
|| property.r#type.is_enum
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
{
continue;
}
Expand All @@ -150,16 +150,7 @@ pub(super) fn lower(
vec![Expr::Ident(this.clone())],
)),
},
then_body: vec![Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![
Expr::Ident(this.clone()),
classes::object_call(
ObjectOp::Random,
vec![Expr::Ident(this.clone())],
),
],
))],
then_body: random_property(&mut builder, property, &this),
else_body: Vec::new(),
});
}
Expand Down Expand Up @@ -264,3 +255,71 @@ pub(super) fn lower(
}
Ok(result)
}

/// Select a declared enum value with rejection sampling, so non-power-of-two
/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the
/// mode guard: a disabled property must not consume its object's random stream.
fn random_property(
builder: &mut BodyBuilder<'_, '_, '_>,
property: &classes::Property,
this: &str,
) -> Vec<Stmt> {
let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]);
let mut body = Vec::new();
let value = if let Some(values) = &property.r#type.enum_values {
let count = values.len() as u64;
let threshold = count.wrapping_neg() % count;
let draw = builder.declare("$enum_draw", classes::unsigned_type(64));
body.push(Stmt::Loop {
kind: LoopKind::DoWhile,
init: Vec::new(),
condition: Some(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Lt,
right: Box::new(Expr::Literal(format!("64'd{threshold}"))),
}),
step: Vec::new(),
body: vec![Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: random(),
nonblocking: false,
}],
});
body.push(Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Mod,
right: Box::new(Expr::Literal(format!("64'd{count}"))),
},
nonblocking: false,
});
let literal = |value| {
Expr::Literal(format_typed_parameter_literal(
value,
property.field.width as usize,
property.field.signed,
))
};
let mut value = literal(*values.last().unwrap());
for (index, &member) in values.iter().enumerate().rev().skip(1) {
value = Expr::Mux {
condition: Box::new(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Eq,
right: Box::new(Expr::Literal(format!("64'd{index}"))),
}),
then_expr: Box::new(literal(member)),
else_expr: Box::new(value),
};
}
value
} else {
random()
};
body.push(Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![Expr::Ident(this.into()), value],
)));
body
}
73 changes: 70 additions & 3 deletions crates/celox-sv-analyzer/src/ast/type_binding/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in(
) -> Converted<Option<Type>> {
enum Job {
Enter(TypeId),
Enum(Vec<PackedRange>),
Enum(TypeId, Vec<PackedRange>),
Aggregate {
owner: Arc<str>,
union: bool,
Expand Down Expand Up @@ -78,11 +78,12 @@ pub(in crate::ast) fn bind_in(
}
DataTypeKind::Enum { base, .. } => {
if let Some(base) = base {
jobs.push(Job::Enum(ranges));
jobs.push(Job::Enum(id, ranges));
jobs.push(Job::Enter(*base));
} else {
let mut ty = builtin_type("int", None).unwrap();
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect();
values.push(ty);
}
Expand Down Expand Up @@ -156,14 +157,15 @@ pub(in crate::ast) fn bind_in(
}
}
}
Job::Enum(ranges) => {
Job::Enum(id, ranges) => {
let Some(mut ty) = values.pop() else {
return Err(unsupported("enum base type"));
};
let mut outer = ranges;
outer.extend(ty.packed_ranges);
ty.packed_ranges = outer;
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
values.push(ty);
}
Job::Aggregate {
Expand Down Expand Up @@ -272,3 +274,68 @@ pub(in crate::ast) fn expression_type(
let value = expression_binding::bind(root, tree, &query)?;
Ok(dimensions::bound_bits_type(&tree.state, &value, &query))
}

/// Domain metadata is best-effort during signature discovery. Only a caller
/// requesting randomization requires a resolved domain; unused types must not
/// start reporting new errors merely because this metadata is collected.
fn enum_values(
id: TypeId,
native: &celox_sv_syntax::Declarations,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
ty: &Type,
) -> Option<Vec<i128>> {
let data = native.data_type(id);
if !data.packed_dimensions.is_empty() {
return None;
}
let DataTypeKind::Enum { items, .. } = &data.kind else {
return None;
};
let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?;
if shape.width > 64 {
return None;
}
let mut env = context.const_env.clone();
let mut next = 0i128;
let mut values = Vec::new();
for item in items {
if !item.dimensions.is_empty() {
return None;
}
let value = if let Some(id) = item.value {
let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases)
.ok()??;
// Unbased fills take the enum base's width and signedness, just
// as they do when resolving the declared enum constants (5.7.1).
let expr = match expr {
ConstExpr::Literal(literal) => ConstExpr::Literal(
resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed)
.unwrap_or(literal),
),
expr => expr,
};
let value = eval_ast_const_expr(&tree.state, &expr, &env)?;
let value_type = infer_const_expr_type(&expr, &parameter_types_from_const_env(&env))?;
if !parameters::enum_initializer_fits_base_type(value, value_type, shape) {
return None;
}
value
} else {
if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next {
return None;
}
next
};
let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed);
if values.contains(&value) {
return None;
}
values.push(value);
let name = normalize_identifier(&item.name.spelling);
env.insert(name.clone(), value);
dimensions::insert_parameter_type_markers(&mut env, &name, shape);
next = value.checked_add(1)?;
}
(!values.is_empty()).then_some(values)
}
Loading
Loading