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
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
37 changes: 36 additions & 1 deletion crates/celox-sv-analyzer/src/ast/classes/constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,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 Down Expand Up @@ -324,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
113 changes: 102 additions & 11 deletions crates/celox-sv-analyzer/src/ast/procedural/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,45 @@ pub(super) fn lower(
state: &mut BodyState<'_>,
item: &generate::Item,
) -> Converted<Vec<Subroutine>> {
lower_methods(class, tree, dimensions, state, Some(item), None)
}

fn lower_methods(
class: &classes::Class,
tree: &AnalysisContext<'_>,
dimensions: &PackedDimensions,
state: &mut BodyState<'_>,
item: Option<&generate::Item>,
inline: Option<&classes::constraints::Inline>,
) -> Converted<Vec<Subroutine>> {
let env = item.map(|item| &*item.env).unwrap_or(&dimensions.const_env);
let aliases = item
.map(|item| item.type_aliases(&dimensions.type_aliases))
.unwrap_or_else(|| std::borrow::Cow::Borrowed(&dimensions.type_aliases));
let method_name = |class: &str, method: &str| {
if let Some(inline) = inline {
inline.name(class)
} else {
let name = classes::Class::subroutine_name(class, method);
item.map(|item| item.name(&name)).unwrap_or(name)
}
};
let handle = classes::handle_type(tree, &class.name)
.ok_or_else(|| unsupported("class randomization receiver"))?;
let convert_type = |ty| {
crate::ir::Type::from_ast(
ty,
&const_functions::Environment {
constants: &*item.env,
constants: env,
functions: &tree.state.const_functions,
},
)
};
let mut result = Vec::new();
for method in ["randomize", "srandom", "rand_mode"] {
if inline.is_some() && method != "randomize" {
continue;
}
if method == "randomize" && class.check_randomize().is_err() {
continue;
}
Expand Down Expand Up @@ -133,12 +159,16 @@ pub(super) fn lower(
else_body: Vec::new(),
});
body.extend(hook("pre_randomize"));
if class.has_constraints {
if class.has_constraints || inline.is_some() {
let mut program = class.constraint_program()?;
if let Some(inline) = inline {
program.constraints.extend(inline.constraints.clone());
}
let success = builder.declare("$constraint_success", int_type());
body.push(Stmt::Assign {
lhs: LValue::Ident(success.clone()),
rhs: classes::object_call(
ObjectOp::Randomize(class.constraint_program()?),
ObjectOp::Randomize(program),
vec![
Expr::Ident(this.clone()),
Expr::Binary {
Expand Down Expand Up @@ -216,27 +246,27 @@ pub(super) fn lower(
// randomize is virtual, while its pre/post hooks are not (18.6.2).
// Object-wide rand_mode also covers the dynamic object's members.
let mut items = Vec::new();
let aliases = item.type_aliases(&dimensions.type_aliases);
for name in classes::visible_classes(tree) {
if name == class.name {
continue;
}
let Ok(derived) = classes::class(tree, &name, &item.env, &aliases) else {
let Ok(derived) = classes::class(tree, &name, env, &aliases) else {
continue;
};
if derived.is_abstract || derived.is_interface {
continue;
}
if (method == "randomize" && derived.check_randomize().is_err())
|| !derived.derives_from(tree, &class.name, &item.env, &aliases)
if (inline.is_some() && derived.constraint_program().is_err())
|| (method == "randomize" && derived.check_randomize().is_err())
|| !derived.derives_from(tree, &class.name, env, &aliases)
{
continue;
}
let args = vec![
Some(Expr::Ident(this.clone())),
Some(Expr::Ident(argument.clone())),
];
let name = classes::Class::subroutine_name(&name, method);
let name = method_name(&name, method);
let call = if method == "randomize" {
vec![Stmt::Return(Some(Expr::Call {
callee: Callee::Subroutine(name),
Expand Down Expand Up @@ -274,11 +304,13 @@ pub(super) fn lower(
},
);
}
for stmt in &mut body {
qualify_stmt(item, stmt);
if let Some(item) = item {
for stmt in &mut body {
qualify_stmt(item, stmt);
}
}
result.push(Subroutine {
name: item.name(&classes::Class::subroutine_name(&class.name, method)),
name: method_name(&class.name, method),
is_task: false,
automatic_locals: builder.state.locals[first_local..]
.iter()
Expand Down Expand Up @@ -382,3 +414,62 @@ fn random_property(
)));
body
}

pub(in crate::ast) fn inline_subroutines(
tree: &AnalysisContext<'_>,
state: &mut BodyState<'_>,
dimensions: &PackedDimensions,
) -> Converted<(Vec<Subroutine>, Vec<classes::constraints::InlineRequest>)> {
let mut requests = std::mem::take(&mut *tree.state.inline_randomizations.borrow_mut());
for request in &scope::imported(&tree.state).inline_randomizations {
if !requests.iter().any(|known| known.key == request.key) {
requests.push(classes::constraints::Inline {
key: request.key,
class: std::rc::Rc::new(request.class.clone()),
constraints: request.constraints.clone(),
dimensions: dimensions.clone(),
});
}
}
let exported = requests
.iter()
.map(classes::constraints::Inline::request)
.collect();
let mut result = Vec::new();
for inline in requests {
let dims = &inline.dimensions;
let mut classes = vec![inline.class.clone()];
for name in classes::visible_classes(tree) {
Comment on lines +440 to +442

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 Extend imported inline helpers for consumer-defined subclasses

When a package class defines a method containing an inline randomization call and a consuming module defines a subclass, calling that inherited method on the subclass fails instead of randomizing it. For example, pkg::Base::pick() returning randomize() with { x == 1; } gets its helper generated while analyzing the package, when the module's Derived extends pkg::Base is not visible. The imported helper is never rebuilt with the consumer's subclasses (unlike imported virtual dispatchers in subroutines_with_symbolic_parameters), so its class-dispatch case misses Derived and the subsequent ObjectOp::Check(Base.id) raises RandomizationClassMismatch. Preserve the inline request metadata across scope imports and extend these helpers for subclasses visible in the consuming scope.

Useful? React with 👍 / 👎.

if name == inline.class.name {
continue;
}
let Ok(class) = classes::class(tree, &name, &dims.const_env, &dims.type_aliases) else {
continue;
};
if !class.is_abstract
&& !class.is_interface
&& class.check_randomize().is_ok()
&& class.constraint_program().is_ok()
&& class.derives_from(
tree,
&inline.class.name,
&dims.const_env,
&dims.type_aliases,
)
{
classes.push(class);
}
}
for class in classes {
result.extend(lower_methods(
&class,
tree,
dims,
state,
None,
Some(&inline),
)?);
}
}
Ok((result, exported))
}
Loading
Loading