From 2c09ebb874410ccd2cc6fd29b9754ff0105021e5 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 22:24:42 +0900 Subject: [PATCH] feat(sv): support dynamic container class properties UVM queue and pool wrappers keep their storage in protected class properties. Support dynamic arrays, queues and integral/string-indexed associative arrays as instance or static properties, including member initializers, this/super, inheritance and protected/local access (IEEE 1800-2023 8.5, 8.9, 8.18). Keep constructed declarations in the parser's class property list instead of silently dropping declarations with [] or new initializers. Store containers as traced object handles. Bind property element access, methods, assignments, queries, reductions and foreach through the existing container operations. Evaluate an owning object once and publish mutations back into that property; nested pop arguments retain their updates. Keep method locals/formals in their own lexical scope so they can shadow properties without hiding this.q. Array assignment and shallow object copies keep independent container values; class elements retain identity (8.12). Add seven portable cases for generic queue/pool wrappers, all three containers, static/inherited storage, receiver evaluation, X/Z, string/object elements, copies and forced heap collection. Test interpreter state modes, native-image round trips, serialized checkpoint replay and null-receiver errors. Const containers, fixed unpacked class arrays, container ports/ref parameters and multidimensional containers remain unsupported. Retain merged ordering support after rebasing onto master. Exercise reverse, sort and rsort on a class queue property as an integration regression. Validation: - Common SV suite: 6,042 passed, 20 existing ignored; focused class-container tests: 37 passed; complete container group: 205 passed. The revised receiver-evaluated-once case passed all five backend configurations without depending on argument evaluation order. - Syntax/analyzer/frontend units: 135 / 863 / 11 passed, 3 existing analyzer ignores. Affected-crate all-targets Clippy with -D warnings, formatting and git diff --check passed. Debug NAPI build and JS integration: 435 passed. - Official sv-tests chapter-8 runner: 53 unmodified pinned cases, 106 verdicts, 98 pass and 8 existing fail; no expectation changes. Not a full-corpus run. - Verilator 5.052: 6 shared cases passed, 1 four-state adapter unsupported. Icarus 13.0: all seven have compilation errors; no passes claimed. - Previously built xezim 0.11.3: 4 passed, 3 mismatch (nested queue pop arguments lose an update; packed pop type queries execute the pop). Current pinned xezim has the previously observed offline dependency build problem; this comparison does not claim to use that revision. No external assertions, exclusions or retained verification baselines are changed. UVM evidence: inspected unmodified uvm_queue.svh and uvm_pool.svh at revision 656f20d087370a7c742e00188d20bbf30fa95339. A diagnostic harness including the actual queue header with registration/reporting/base stubs still stops resolving the compilation-unit parameterized class. Shared wrappers exercise its storage pattern; this does not establish that the UVM library runs. A separate minimal package reproducer confirms that specializing a generic class outside its declaring scope remains unsupported. Package-wide matching specializations must share type and static-member identity (8.25); this is a remaining UVM dependency, not implemented by this property change. Change-Id: Ifa5267930c6aef232c04d6445904fd139015138b --- .../src/lowering/ff/containers.rs | 35 ++- .../src/ast/array_reductions.rs | 29 ++- crates/celox-sv-analyzer/src/ast/classes.rs | 15 +- .../celox-sv-analyzer/src/ast/containers.rs | 100 ++++++--- .../src/ast/dimensions/query_binding.rs | 3 +- .../src/ast/expression_binding.rs | 2 +- .../src/ast/expression_binding/objects.rs | 10 +- .../src/ast/expression_binding/strings.rs | 16 +- .../celox-sv-analyzer/src/ast/procedural.rs | 23 ++ .../src/ast/procedural/foreach.rs | 10 +- crates/celox-sv-syntax/src/parser/classes.rs | 12 +- crates/celox-sv-syntax/src/parser/tests.rs | 21 ++ .../src/sv/cases/containers.vtest | 212 ++++++++++++++++++ .../frontends/systemverilog/containers.rs | 75 +++++++ docs/guide/systemverilog-reference.md | 22 +- 15 files changed, 521 insertions(+), 64 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs index 545ef09367d..d2870c038a2 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/containers.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -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); @@ -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 => { @@ -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 = diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs index f9a69653396..fc675659de1 100644 --- a/crates/celox-sv-analyzer/src/ast/array_reductions.rs +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -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 @@ -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", diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 49f03400b4c..bb26c9a7087 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -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); @@ -1122,10 +1131,8 @@ fn field( env: &HashMap, offset: u32, ) -> Converted { - 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 => { diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index afd61445515..514e2f3fa80 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -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>> { + 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 { @@ -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()), @@ -189,7 +197,7 @@ pub(super) fn assignment( .collect::>>()?; 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, @@ -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", )); @@ -228,7 +237,7 @@ fn element_value( target: &ContainerType, ) -> Converted { 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() { @@ -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) { @@ -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 { @@ -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)?, None => Expr::Binary { left: Box::new(call( ContainerOp::Size, @@ -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 != "." { @@ -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))) @@ -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 @@ -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 { @@ -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( @@ -696,7 +705,7 @@ 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)?, ], )))) } @@ -704,6 +713,41 @@ pub(super) fn set( #[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 [ diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 576659c6776..c7b9cb3c8c6 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -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 diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 26416384f7c..477a66af5db 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -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, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index a3d1c036622..00b26543eba 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -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 diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs index 746009e9a0d..342776acd26 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -135,13 +135,19 @@ pub(in crate::ast) fn native_string( ) -> bool { match &native.expression(ungroup(id, native)).kind { ExprKind::Select { expression, .. } - if containers::native_type(*expression, native, dimensions).is_some() => + if containers::native_type(*expression, native, tree, dimensions) + .ok() + .flatten() + .is_some() => { - containers::native_type(*expression, native, dimensions).is_some_and(|ty| { - ty.layout.handle == Some(crate::system_functions::HandleProperty::String) - }) + containers::native_type(*expression, native, tree, dimensions) + .ok() + .flatten() + .is_some_and(|ty| { + ty.layout.handle == Some(crate::system_functions::HandleProperty::String) + }) } - ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, .. } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") && containers::native_type(*base, native, dimensions).is_some_and(|ty| ty.layout.handle == Some(crate::system_functions::HandleProperty::String))) => { + ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, .. } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") && containers::native_type(*base, native, tree, dimensions).ok().flatten().is_some_and(|ty| ty.layout.handle == Some(crate::system_functions::HandleProperty::String))) => { true } ExprKind::Name(name) diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 35249e4e24e..55ce480f14d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -682,6 +682,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let bind = |right| { expression_binding::bind_value(right, native, self.tree, &self.dims, Some(&target)) }; + if let Some(container) = property.r#type.container.as_deref() { + if op != "=" { + return Err(unsupported("compound assignment to a container property")); + } + let value = containers::assignment(right, self.tree, &self.dims, container)?; + return self.property_store(&property, handle, op, value).map(Some); + } let mut value = match property.r#type.class() { Some(class) if op == "=" => { match expression_binding::object_constructor( @@ -2297,6 +2304,9 @@ pub(super) fn lower_subroutine( builder.push_scope(); if let Some(class) = class { builder.enter_class_scope(class); + // Method formals and locals may shadow properties, but not another + // declaration in the method's own lexical scope (8.5, 6.21). + builder.push_scope(); } // Defaults bind in the enclosing declaration scope, before // any formal can shadow those names (IEEE 1800-2023 13.5.3). @@ -2401,6 +2411,9 @@ pub(super) fn lower_subroutine( None => body.extend(builder.native_body(&items, &native.authored_statements)?), } builder.pop_scope(); + if class.is_some() { + builder.pop_scope(); + } let static_types: HashMap = builder .state .statics @@ -2715,6 +2728,16 @@ impl BodyBuilder<'_, '_, '_> { let Some(initializer) = property.initializer else { continue; }; + if let Some(container) = property.r#type.container.as_deref() { + let mut value = + containers::assignment(initializer, self.tree, &self.dims, container)?; + self.rename_expr(&mut value); + body.push(Stmt::Eval(classes::object_call( + system_functions::ObjectOp::Store(property.field), + vec![Expr::Ident(this.to_owned()), value], + ))); + continue; + } let mut value = match property.r#type.class() { Some(class) => expression_binding::object_constructor( self.tree, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs index 546d1691293..4a780198d6b 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs @@ -18,6 +18,7 @@ impl BodyBuilder<'_, '_, '_> { header: &ForeachHeader, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + let container = containers::native_type(header.array, native, self.tree, &self.dims)?; let mut array = header.array; let mut unit_member = None; let array = loop { @@ -36,16 +37,11 @@ impl BodyBuilder<'_, '_, '_> { _ => return Err(unsupported("foreach array")), } }; - if let Some(container) = self - .dims - .get(&array) - .and_then(|shape| shape.container.clone()) - { + if let Some(container) = container { let [Some(variable)] = header.variables.as_slice() else { return Err(unsupported("one-dimensional container foreach index")); }; - let mut array = Expr::Ident(array); - self.rename_expr(&mut array); + let array = self.native_value(header.array)?; let mut index_type = int_type(); let status = if let ContainerKind::Associative { key_width, diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index f2650d03c26..67892cf54b2 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -77,7 +77,10 @@ impl Parser<'_> { } } let declaration = self.local_declaration()?; - if special_const && let LocalDeclaration::Variables(value) = &declaration { + if special_const + && let LocalDeclaration::Variables(value) | LocalDeclaration::Constructed(value) = + &declaration + { if value.variables.len() != 1 || !value.variables[0].dimensions.is_empty() { return Err( self.error("qualified const class property requires one scalar declarator") @@ -87,8 +90,11 @@ impl Parser<'_> { self.validate_constant_operators(value)?; } } - if let (Some(class), LocalDeclaration::Variables(mut declaration)) = - (self.class_stack.last_mut(), declaration) + if let ( + Some(class), + LocalDeclaration::Variables(mut declaration) + | LocalDeclaration::Constructed(mut declaration), + ) = (self.class_stack.last_mut(), declaration) { declaration.constant |= qualified_const; class.properties.push(ClassProperty { diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index 52ce03c18a8..2579922160b 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2494,6 +2494,27 @@ fn constructed_declarations_validate_types_dimensions_and_allocation_operands() } } +#[test] +fn class_properties_retain_constructed_declarations_and_initializers() { + let syntax = parse( + "module M; class Cell; endclass class Store; int data[] = new[2]; int q[$], map[string]; Cell child = new; endclass endmodule", + ); + let properties = &syntax.classes[1].properties; + let names = properties + .iter() + .flat_map(|property| &property.declaration.variables) + .map(|variable| variable.name.spelling.as_str()) + .collect::>(); + assert_eq!(names, ["data", "q", "map", "child"]); + let data = &properties[0].declaration.variables[0]; + assert!(matches!(data.dimensions[0].kind, DimensionKind::Unsized)); + assert!(matches!( + syntax.expression(data.value.unwrap()).kind, + ExprKind::Select { .. } + )); + assert!(properties[2].declaration.variables[0].value.is_some()); +} + #[test] fn class_property_payloads_validate_while_opaque_nonproperty_items_keep_boundaries() { let members = "rand protected int x=1; static const int y=2; const protected static int z=3; C object=new old_object; int data[]=new[2]; constraint c { x > 0; } int after_constraint=1; extern constraint forward; nettype int N with resolver; covergroup cg; coverpoint x; endgroup int after_covergroup=2; virtual function int f(); return x; endfunction extern function int g(); function new(); super.new(); endfunction"; diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest index dc6149245df..52d1985d914 100644 --- a/crates/celox-test-suite/src/sv/cases/containers.vtest +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -1,5 +1,217 @@ (group containers (category types)) +(case class_container_inheritance_static + (source "class_containers.sv" #" +module Top(output bit [3:0] flags); + class Base; + protected int q[$]; + static int counts[string]; + function void push(int value); q.push_back(value); endfunction + function int count(); return q.size(); endfunction + endclass + class Derived extends Base; + function int pop(); return super.q.pop_front(); endfunction + function void shadow(); + int q[$]; + q.push_back(99); + this.q.push_back(7); + endfunction + endclass + Derived d; + Base alias_d; + int value; + initial begin + d = new; alias_d = d; d.push(3); d.shadow(); + flags[0] = alias_d.count() == 2; + value = d.pop(); + flags[1] = value == 3 && d.count() == 1; + Base::counts["shared"] = 4; + flags[2] = d.counts["shared"] == 4; + d.counts["shared"] = 8; + flags[3] = Base::counts.num() == 1 && alias_d.counts["shared"] == 8; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case class_container_receiver_evaluation + (source "class_containers.sv" #" +module Top(output bit [2:0] flags); + class Store; int q[$]; endclass + Store first, second, stores[$]; + int calls; + function automatic int next_index(); calls++; return 0; endfunction + initial begin + first = new; second = new; stores = {first, second}; + stores[next_index()].q.push_back(5); + flags[0] = calls == 1 && first.q.size() == 1 && second.q.size() == 0; + flags[1] = first.q[0] == 5; + first.q = {1, 2}; first.q.push_back(first.q.pop_front()); + flags[2] = first.q.size() == 2 && first.q[0] == 2 && first.q[1] == 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 7)) + +(case class_container_properties + (source "class_containers.sv" #" +module Top(output bit [8:0] flags); + class Store; + int data[] = new[2]; + int q[$], map[string]; + function void add(int value); q.push_back(value); endfunction + function int take(); return q.pop_front(); endfunction + function int count(); return this.q.size(); endfunction + endclass + Store s, alias_s; + int copy_values[], value; + initial begin + s = new; alias_s = s; + flags[0] = s.data.size() == 2 && s.q.size() == 0 && s.map.num() == 0; + s.data[0] = 4; s.data[1] = 5; copy_values = s.data; + s.data[0] = 9; + flags[1] = copy_values[0] == 4 && copy_values[1] == 5 && alias_s.data[0] == 9; + s.add(1); s.add(2); s.q.push_back(s.q.pop_front()); + flags[2] = s.count() == 2 && s.q[0] == 2 && s.q[1] == 1; + value = alias_s.take(); + flags[3] = value == 2 && s.q.size() == 1; + s.map["first"] = 10; alias_s.map["second"] = 20; + flags[4] = s.map.num() == 2 && s.map.exists("second") && s.map["first"] == 10; + s.data = '{6, 7, 8}; s.data = new[4](s.data); + flags[5] = s.data.size() == 4 && s.data[0] == 6 && s.data[2] == 8; + flags[6] = s.data.sum() == 21 && $size(s.data) == 4 && $bits(s.q.pop_front()) == 32 && s.q.size() == 1; + s.q.push_back(3); s.q.reverse(); + flags[8] = s.q[0] == 3 && s.q[1] == 1; + s.q.sort(); flags[8] = flags[8] && s.q[0] == 1 && s.q[1] == 3; + s.q.rsort(); flags[8] = flags[8] && s.q[0] == 3 && s.q[1] == 1; + s.data.delete(); s.q.delete(); s.map.delete("first"); + flags[7] = s.data.size() == 0 && alias_s.q.size() == 0 && s.map.size() == 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 511)) + +(case class_container_queue_pool + (source "class_containers.sv" #" +module Top(output bit [5:0] flags); + class Queue #(type T = int); + protected T queue[$]; + virtual function void push_back(T value); queue.push_back(value); endfunction + virtual function T pop_front(); return queue.pop_front(); endfunction + virtual function T get(int index); return queue[index]; endfunction + virtual function int size(); return queue.size(); endfunction + endclass + class Pool #(type KEY = string, type T = int); + protected T pool[KEY]; + virtual function void add(KEY key, T value); pool[key] = value; endfunction + virtual function T get(KEY key); return pool[key]; endfunction + virtual function int num(); return pool.num(); endfunction + virtual function int total(); + int result = 0; + foreach (pool[key]) result += pool[key]; + return result; + endfunction + endclass + Queue #(int) numbers; + Queue #(string) words; + Pool #(string, int) pool; + int value; + initial begin + numbers = new; words = new; pool = new; + numbers.push_back(11); numbers.push_back(22); + flags[0] = numbers.size() == 2 && numbers.get(1) == 22; + value = numbers.pop_front(); + flags[1] = value == 11 && numbers.size() == 1; + words.push_back("alpha"); words.push_back("beta"); + flags[2] = words.pop_front() == "alpha" && words.get(0) == "beta"; + pool.add("first", 30); pool.add("second", 40); + flags[3] = pool.num() == 2 && pool.get("second") == 40; + flags[4] = pool.total() == 70; + pool.add("first", 50); + flags[5] = pool.num() == 2 && pool.total() == 90; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 63)) + +(case class_container_strings_handles + (source "class_containers.sv" #" +module Top(output bit [3:0] flags); + class Cell; bit [31:0] value; endclass + class Store; + string words[$]; + Cell cells[int]; + endclass + Store s; + Cell c, selected; + string text; + initial begin + s = new; c = new; c.value = 7; + s.words.push_back("kept"); s.words.push_back("last"); + text = s.words.pop_front(); + flags[0] = text == "kept" && s.words[0] == "last"; + s.cells[3] = c; selected = s.cells[3]; selected.value = 9; + flags[1] = s.cells[3] == c && s.cells[3].value == 9; + c = null; selected = null; + #1; + flags[2] = s.words.pop_back() == "last" && s.words.size() == 0; + selected = s.cells[3]; + flags[3] = selected.value == 9; + end +endmodule +"#) + (top Top) (run_until 1) (assert_eq flags 15)) + +(case class_container_four_state + (source "class_containers.sv" #" +module Top(output bit [3:0] flags); + class Store; logic [3:0] data[], q[$], map[int]; endclass + Store s; + logic [3:0] value; + initial begin + s = new; s.data = new[2]; + flags[0] = s.data[0] === 4'bxxxx; + s.data[0] = 4'b1xz0; s.q.push_back(s.data[0]); + value = s.q.pop_front(); + flags[1] = value === 4'b1xz0 && s.q.size() == 0; + s.map[-1] = value; + flags[2] = s.map[-1] === 4'b1xz0 && s.map[5] === 4'bxxxx; + s.q.push_back(4'bz01x); + flags[3] = $bits(s.q.pop_front) == 4 && s.q.size() == 1 && s.q[0] === 4'bz01x; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case class_container_copy_and_gc + (source "class_containers.sv" #" +module Top(output bit [3:0] flags); + class Store; + string words[$]; + int data[]; + function void append(string value); words.push_back(value); endfunction + endclass + Store original, copy_object, garbage; + int i; + initial begin + original = new; original.append("live"); original.data = '{1, 2}; + copy_object = new original; + copy_object.words.push_back("copy"); copy_object.data[0] = 9; + flags[0] = original.words.size() == 1 && original.words[0] == "live"; + flags[1] = original.data[0] == 1 && copy_object.data[0] == 9; + original = null; + for (i = 0; i < 1100; i++) garbage = new; + garbage = null; + #1; + flags[2] = copy_object.words[0] == "live" && copy_object.words[1] == "copy"; + copy_object.append("third"); + flags[3] = copy_object.words.size() == 3 && copy_object.words[2] == "third"; + end +endmodule +"#) + (top Top) (run_until 1) (assert_eq flags 15)) + (case ordering_integral (source "ordering.sv" #" module Top(output bit [10:0] flags); diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index 0b2a47631b6..b9c99830c6d 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -1,6 +1,13 @@ use super::*; sv_backends! { + fn class_container_inheritance_static(sim) { @case "containers::class_container_inheritance_static"; } + fn class_container_receiver_evaluation(sim) { @case "containers::class_container_receiver_evaluation"; } + fn class_container_properties(sim) { @case "containers::class_container_properties"; } + fn class_container_queue_pool(sim) { @case "containers::class_container_queue_pool"; } + fn class_container_strings_handles(sim) { @case "containers::class_container_strings_handles"; } + fn class_container_four_state(sim) { @case "containers::class_container_four_state"; } + fn class_container_copy_and_gc(sim) { @case "containers::class_container_copy_and_gc"; } fn ordering_integral(sim) { @case "containers::ordering_integral"; } fn ordering_strings(sim) { @case "containers::ordering_strings"; } fn ordering_four_state(sim) { @case "containers::ordering_four_state"; } @@ -147,6 +154,74 @@ fn ordering_survives_native_images_and_serialized_checkpoints() { assert_eq!(sim.get(value), BigUint::from(1u8)); } +#[test] +fn class_container_native_images_and_checkpoints_preserve_object_graphs() { + let source = r#"module Top(output int value); + timeunit 1ps / 1ps; + class Store; int data[], q[$], map[string]; endclass + Store s; + initial begin + s = new; s.data = '{1, 2}; s.q.push_back(3); s.map["key"] = 4; + #10 value = s.data[0] + s.q[0] + s.map["key"]; + #10 s.data[0] = 5; s.q.push_back(6); s.map["key"] = 7; + #10 value = s.data[0] + s.q[1] + s.map["key"]; + end + endmodule"#; + for four_state in [false, true] { + let mut interpreted = celox::Simulation::from_sv_sources( + vec![(source, Path::new("class-container-interpreter.sv"))], + "Top", + ) + .four_state(four_state) + .build_interpreter() + .unwrap(); + interpreted.run_until(35).unwrap(); + assert_eq!( + interpreted.get(interpreted.signal("value")), + BigUint::from(18u8) + ); + let image = celox::Simulation::from_sv_sources( + vec![(source, Path::new("class-container-image.sv"))], + "Top", + ) + .four_state(four_state) + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let mut sim = celox::Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.run_until(15).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(8u8)); + let bytes = sim.checkpoint().unwrap().to_bytes().unwrap(); + // SAFETY: bytes came from this simulator's checkpoint. + let checkpoint = unsafe { sim.checkpoint_from_bytes(&bytes) }.unwrap(); + sim.run_until(35).unwrap(); + assert_eq!(sim.get(value), BigUint::from(18u8)); + sim.restore(&checkpoint).unwrap(); + sim.run_until(35).unwrap(); + assert_eq!(sim.get(value), BigUint::from(18u8)); + } +} + +#[test] +fn class_container_methods_reject_null_receivers() { + let source = + "module Top; class Store; int q[$]; endclass Store s; initial s.q.push_back(1); endmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("null-class-container.sv"))], + "Top", + ) + .build_native() + .unwrap(); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); +} + const EMPTY_REDUCTION_MODES: &str = r#" module Top(output bit [63:0] dp, da, qp, qa, ap, aa, sp, sa, output bit [3:0] flags); bit [63:0] values[], q[$], numbers[int], words[string]; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8efcd2f127b..75767ab3721 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -33,7 +33,7 @@ synthesis and is tested at the design level. | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Dynamic containers | one-dimensional dynamic arrays, queues (including bounded queues), and associative arrays with integral or string keys; element access, value assignment, equality, `foreach` and built-in container methods. See [dynamic containers](#dynamic-containers) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | +| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state integral types up to 64 bits, `string` and class handle types, plus dynamic arrays, queues and associative arrays, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -445,7 +445,11 @@ including X/Z for four-state elements. `foreach` visits sequence positions or associative keys in order. Range errors read the element type's default and ignore writes; unknown indices never create associative entries. -Containers work in procedural code as module variables or locals. Automatic +Containers work in procedural code as module variables, locals, and class +instance or static properties. Class properties support unqualified access in +methods, `this` / `super`, access through handles, inherited visibility and +member initializers (IEEE 1800-2023 8.5, 8.9, 8.18). +Automatic local initializers and module declaration initializers may allocate with `new[]`. Checkpoints, including serialized checkpoints, preserve contents; portable state files require a checkpoint instead. Strings and class objects @@ -464,13 +468,13 @@ Rust's `SimulatorBuilder::legacy_empty_reductions(true)` or the frontend's affects compilation and is preserved in generated native images; it does not change nonempty reductions. Fixed arrays may have elements wider than 64 bits. These methods currently -require a one-dimensional array variable; +require a one-dimensional array variable or dynamic-container class property; `with` expressions and iterator arguments remain unsupported. Multidimensional containers, elements wider than 64 bits, real elements, wildcard or class keys, slices, array locator methods, keyed patterns, container operands within concatenations, compound or nonblocking element -assignments, container ports / subroutine parameters / class properties and +assignments, container ports / subroutine parameters and const containers remain unsupported. A `new[]` initializer currently requires another compatible dynamic array or queue; fixed-size arrays are unsupported. Static local initializers retain the existing constant-initializer restriction. @@ -482,6 +486,16 @@ and serialized checkpoints from earlier container versions must be regenerated. ### Classes {#classes} +Class container properties use the same element and key types as +[dynamic containers](#dynamic-containers), including four-state integral +elements. Object aliases share those properties; assigning an array property +or making a shallow object copy preserves independent array values, while +class handles inside the arrays keep reference semantics (8.12). Heap +collection and serialized checkpoints follow the nested object/container graph. +Fixed-size unpacked class properties and const container properties remain +unsupported. This supports the protected-container pattern used by UVM queue +and pool wrappers; it does not establish support for the full UVM library. + A class variable holds a handle of an object in the simulator's heap, `null` until a constructor runs. Like a string, a handle costs the same as a 32-bit integer to copy or compare; reading or writing a property and creating an