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
35 changes: 34 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ impl Ff<'_, '_> {
if op.reduction().is_some() {
return self.container_reduction(op, layout, &args[0], parameter);
}
// Evaluate the owning object once, before argument side effects. Read
// its current container after the arguments, so a nested pop is kept.
let property = if !matches!(op, New | Literal | Convert | Equal | CaseEqual)
&& let sv::ir::Expr::Call {
callee: sv::ir::Callee::Object(object),
args,
..
} = &args[0]
&& let sv::ir::ObjectOp::Load(field) = **object
{
let owner = args[0]
.as_ref()
.ok_or_else(|| unsupported("container property owner"))?;
Some((field, self.handle(owner)?))
} else {
None
};
let zero = self.constant64(0);
let (width, signed) = op.result_type(layout);
let element_result = matches!(op, Get | PopFront | PopBack);
Expand Down Expand Up @@ -148,7 +165,13 @@ impl Ff<'_, '_> {
};
// Arguments can mutate the receiver (e.g. q.push_back(q.pop_front())).
// Read its current contents and derive positions only after evaluating them.
let handle = self.handle(&args[0])?;
let handle = if let Some((field, owner)) = property {
let offset = self.constant64(u64::from(field.offset));
let count = self.constant64(u64::from(field.bytes()));
self.heap_call(celox_heap::ops::OBJECT_LOAD, &[owner, offset, count])
} else {
self.handle(&args[0])?
};
let index = match op {
PushBack => self.heap_call(code(heap::LEN), &[handle]),
PopBack => {
Expand Down Expand Up @@ -277,6 +300,16 @@ impl Ff<'_, '_> {
updated =
this.heap_call(code(heap::SET_MASK), &[updated, index, mask]);
}
if let Some((field, owner)) = property {
let place = this.constant64(
u64::from(field.offset) | u64::from(field.bytes()) << 32,
);
this.heap_call(
celox_heap::ops::OBJECT_STORE,
&[owner, place, updated],
);
return Ok(());
}
let (id, updated_name) =
this.m.temp("container_update", 32, false, false);
this.m.variables.get_mut(&id).unwrap().value_kind =
Expand Down
29 changes: 20 additions & 9 deletions crates/celox-sv-analyzer/src/ast/array_reductions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ pub(super) fn bind(
_ => op,
};
}
if let Some(container) = containers::native_type(*base, native, tree, dims)? {
if let ExprKind::Call { arguments, .. } = &native.expression(id).kind
&& !arguments.is_empty()
{
return Err(unsupported(
"array reduction arguments require a with expression",
));
}
if container.layout.handle.is_some() {
return Err(unsupported("array reduction requires integral elements"));
}
return Ok(Some((
containers::call(
op,
container.layout,
vec![expression_binding::value(*base, native, tree, dims)?],
),
procedural::dimensions_from_type(&container.element),
)));
}
let ExprKind::Name(receiver) = &native
.expression(expression_binding::ungroup(*base, native))
.kind
Expand All @@ -59,15 +79,6 @@ pub(super) fn bind(
"array reduction arguments require a with expression",
));
}
if let Some(container) = shape.container.as_deref() {
if container.layout.handle.is_some() {
return Err(unsupported("array reduction requires integral elements"));
}
return Ok(Some((
containers::call(op, container.layout, vec![Expr::Ident(receiver)]),
procedural::dimensions_from_type(&container.element),
)));
}
if shape.unpacked.len() != 1 || shape.real || shape.string || shape.class.is_some() {
return Err(unsupported(
"array reduction requires one-dimensional integral elements",
Expand Down
15 changes: 11 additions & 4 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -733,9 +733,18 @@ pub(super) fn class(
)?
.ok_or_else(|| unsupported("class property type"))?;
for variable in &property.declaration.variables {
if !variable.dimensions.is_empty() {
let ty = containers::with_dimensions(
ty.clone(),
&variable.dimensions,
tree,
&PackedDimensions::new(HashMap::default(), env, aliases),
)?;
if !ty.unpacked_ranges.is_empty() {
return Err(unsupported("class property with unpacked dimensions"));
}
if ty.container.is_some() && property.declaration.constant {
return Err(unsupported("const dynamic container class property"));
}
let property_name = instances::normalize_identifier(&variable.name.spelling);
if property.qualifiers.is_static {
statics.retain(|known| known.name != property_name);
Expand Down Expand Up @@ -1122,10 +1131,8 @@ fn field(
env: &HashMap<String, i128>,
offset: u32,
) -> Converted<ObjectField> {
if ty.container.is_some() {
return Err(unsupported("dynamic container class property"));
}
let (width, signed, handle) = match ty.kind() {
_ if ty.container.is_some() => (HANDLE_WIDTH, false, Some(HandleProperty::Object)),
TypeKind::String => (HANDLE_WIDTH, false, Some(HandleProperty::String)),
TypeKind::Object => (HANDLE_WIDTH, false, Some(HandleProperty::Object)),
TypeKind::Bit => {
Expand Down
100 changes: 72 additions & 28 deletions crates/celox-sv-analyzer/src/ast/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,28 @@ pub(super) fn with_dimensions(
Ok(ty)
}

pub(super) fn native_type<'a>(
pub(super) fn native_type(
id: ExprId,
native: &celox_sv_syntax::Declarations,
dims: &'a PackedDimensions,
) -> Option<&'a ContainerType> {
let ExprKind::Name(name) = &native
tree: &AnalysisContext<'_>,
dims: &PackedDimensions,
) -> Converted<Option<Arc<ContainerType>>> {
if let ExprKind::Name(name) = &native
.expression(expression_binding::ungroup(id, native))
.kind
else {
return None;
};
dims.get(&instances::normalize_identifier(&name.spelling))?
.container
.as_deref()
&& let Some(shape) = dims.get(&instances::normalize_identifier(&name.spelling))
{
return Ok(shape.container.clone());
}
if let Some((property, _)) = expression_binding::object_property(tree, id, native, dims)? {
return Ok(property.r#type.container);
}
if let Some(name) = expression_binding::object_static_property(tree, id, native, dims)?
&& let Some(shape) = dims.get(&name)
{
return Ok(shape.container.clone());
}
Ok(None)
}

pub(super) fn call(op: ContainerOp, layout: ContainerLayout, args: Vec<Expr>) -> Expr {
Expand Down Expand Up @@ -162,7 +170,7 @@ pub(super) fn assignment(
let size = expression_binding::value(size, native, tree, dims)?;
let init = match initializer {
Some(id) => {
check_compatible(id, native, dims, target)?;
check_compatible(id, native, tree, dims, target)?;
expression_binding::value(id, native, tree, dims)?
}
None => Expr::Literal("0".into()),
Expand All @@ -189,7 +197,7 @@ pub(super) fn assignment(
.collect::<Converted<Vec<_>>>()?;
return Ok(call(ContainerOp::Literal, target.layout, values));
}
check_compatible(root, native, dims, target)?;
check_compatible(root, native, tree, dims, target)?;
Ok(call(
ContainerOp::Convert,
target.layout,
Expand All @@ -199,10 +207,11 @@ pub(super) fn assignment(
fn check_compatible(
id: ExprId,
native: &celox_sv_syntax::Declarations,
tree: &AnalysisContext<'_>,
dims: &PackedDimensions,
target: &ContainerType,
) -> Converted<()> {
let Some(source) = native_type(id, native, dims) else {
let Some(source) = native_type(id, native, tree, dims)? else {
return Err(unsupported(
"container assignment requires a compatible container",
));
Expand All @@ -228,7 +237,7 @@ fn element_value(
target: &ContainerType,
) -> Converted<Expr> {
let native = tree.declarations();
if native_type(id, native, dims).is_some() {
if native_type(id, native, tree, dims)?.is_some() {
return Err(unsupported("container used as an element"));
}
if let Some(class) = target.element.class.as_deref() {
Expand Down Expand Up @@ -325,14 +334,14 @@ pub(super) fn value(
left,
operator,
right,
} if native_type(*left, native, dims).is_some()
|| native_type(*right, native, dims).is_some() =>
} if native_type(*left, native, tree, dims)?.is_some()
|| native_type(*right, native, tree, dims)?.is_some() =>
{
let Some(target) = native_type(*left, native, dims) else {
let Some(target) = native_type(*left, native, tree, dims)? else {
return Err(unsupported("container comparison requires two containers"));
};
check_compatible(*right, native, dims, target)?;
let source = native_type(*right, native, dims).expect("checked compatibility");
check_compatible(*right, native, tree, dims, &target)?;
let source = native_type(*right, native, tree, dims)?.expect("checked compatibility");
if std::mem::discriminant(&source.layout.kind)
!= std::mem::discriminant(&target.layout.kind)
{
Expand Down Expand Up @@ -367,7 +376,7 @@ pub(super) fn value(
expression,
dimension,
} => {
let Some(target) = native_type(*expression, native, dims) else {
let Some(target) = native_type(*expression, native, tree, dims)? else {
return Ok(None);
};
let index = match dimension.kind {
Expand All @@ -385,7 +394,7 @@ pub(super) fn value(
vec![
expression_binding::value(*expression, native, tree, dims)?,
match index {
Some(index) => index_value(index, *expression, tree, dims, target)?,
Some(index) => index_value(index, *expression, tree, dims, &target)?,
Comment on lines 395 to +397

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 Reuse the captured receiver when resolving queue dollar indices

For a property access such as stores[next_index()].q[$], the receiver is evaluated twice: once when lowering the outer Get, and again by the nested Size expression generated for $. The same duplication affects $-1 indices and element assignments. Consequently, next_index() runs twice and can select a different queue for the size calculation, producing an incorrect element or write target. Reuse the captured owner/container when resolving dollar indices rather than rebinding the original receiver expression.

Useful? React with 👍 / 👎.

None => Expr::Binary {
left: Box::new(call(
ContainerOp::Size,
Expand Down Expand Up @@ -417,7 +426,7 @@ pub(super) fn value(
else {
return Ok(None);
};
let Some(target) = native_type(*base, native, dims) else {
let Some(target) = native_type(*base, native, tree, dims)? else {
return Ok(None);
};
if separator != "." {
Expand Down Expand Up @@ -533,9 +542,9 @@ pub(super) fn value(
} else if matches!(op, ContainerOp::PushFront | ContainerOp::PushBack)
|| op == ContainerOp::Insert && index == 1
{
args.push(element_value(id, tree, dims, target)?);
args.push(element_value(id, tree, dims, &target)?);
} else {
args.push(index_value(id, *base, tree, dims, target)?);
args.push(index_value(id, *base, tree, dims, &target)?);
}
}
Ok(Some(call(op, target.layout, args)))
Expand Down Expand Up @@ -577,7 +586,7 @@ fn query(
let Some(base) = arguments.first().and_then(|a| a.value) else {
return Ok(None);
};
let Some(target) = native_type(base, native, dims) else {
let Some(target) = native_type(base, native, tree, dims)? else {
return Ok(None);
};
if arguments
Expand Down Expand Up @@ -667,7 +676,7 @@ pub(super) fn set(
else {
return Ok(None);
};
let Some(target) = native_type(*expression, native, dims) else {
let Some(target) = native_type(*expression, native, tree, dims)? else {
return Ok(None);
};
if op != "=" || nonblocking {
Expand All @@ -676,7 +685,7 @@ pub(super) fn set(
));
}
let index = match dimension.kind {
DimensionKind::Index(index) => index_value(index, *expression, tree, dims, target)?,
DimensionKind::Index(index) => index_value(index, *expression, tree, dims, &target)?,
DimensionKind::Queue(None) if matches!(target.layout.kind, ContainerKind::Queue { .. }) => {
Expr::Binary {
left: Box::new(call(
Expand All @@ -696,14 +705,49 @@ pub(super) fn set(
vec![
expression_binding::value(*expression, native, tree, dims)?,
index,
element_value(right, tree, dims, target)?,
element_value(right, tree, dims, &target)?,
],
))))
}

#[cfg(test)]
mod tests {
use super::*;
#[test]
fn class_containers_preserve_access_and_compatibility_checks() {
for (source, expected) in [
(
"module Top; class C; local int q[$]; endclass C c; initial begin c=new; c.q.push_back(1); end endmodule",
"local",
),
(
"module Top; class C; protected int q[$]; endclass C c; int v; initial begin c=new; v=$size(c.q); end endmodule",
"protected",
),
(
"module Top; class C; const int q[$]; endclass C c; initial c=new; endmodule",
"const dynamic",
),
(
"module Top; class C; int q[$]; byte a[]; endclass C c; initial begin c=new; c.q=c.a; end endmodule",
"incompatible",
),
(
"module Top; class C; int q[$]; endclass C c; initial begin c=new; c.q[0]<=1; end endmodule",
"nonblocking",
),
(
"module Top; class C; int q[2]; endclass C c; initial c=new; endmodule",
"unpacked dimensions",
),
] {
let error = crate::analyze_source(source, Path::new("class-container-rejection.sv"))
.unwrap_err()
.to_string();
assert!(error.contains(expected), "{source}: {error}");
}
}

#[test]
fn unsupported_container_forms_fail_before_lowering() {
for (source, expected) in [
Expand Down
3 changes: 2 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 @@ -726,7 +726,8 @@ pub(in crate::ast) fn shape(
if let ExprKind::Member {
expression, name, ..
} = &native.expression(callee).kind
&& let Some(container) = containers::native_type(*expression, native, context)
&& let Some(container) =
containers::native_type(*expression, native, tree, context)?
{
// Validate the call without executing it. Pop returns the
// declared element type, including packed dimensions and
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub(super) use objects::{
check_access as check_member_access, check_assignment as check_handle_assignment,
constraint_mode_call as object_constraint_mode_call, constructor as object_constructor,
method as object_method, property as object_property, rand_mode_call as object_rand_mode_call,
receiver as object_receiver, this as object_this,
receiver as object_receiver, static_property as object_static_property, this as object_this,
};
pub(super) use strings::{
call as string_call, method as string_method, native_string, to_string as string_operand,
Expand Down
10 changes: 9 additions & 1 deletion crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,16 @@ pub(in crate::ast) fn native_class(
dimension,
} = &expression.kind
&& matches!(dimension.kind, celox_sv_syntax::DimensionKind::Index(_))
&& let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind
{
if let Some(ty) = containers::native_type(*expression, native, tree, dimensions)
.ok()
.flatten()
{
return ty.element.class().map(str::to_owned);
}
let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind else {
return None;
};
let ty = dimensions.get(&instances::normalize_identifier(&name.spelling))?;
return ty
.container
Expand Down
Loading
Loading