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/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs index 25f2fb3a1a4..d496582b0fc 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_ast.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -144,9 +144,19 @@ pub(super) fn signature( .collect::>(); let rename = scope::Renamer { names: &names }; module.name = name; + let header_ports = module.ports.clone(); module.ports = members .iter() .map(|name| { + if let Some(port) = header_ports.iter().find(|port| port.name == *name) { + return Ok(Port::new( + rename.name(name), + PortDirection::Input, + rename.r#type(port.r#type.clone()), + port.is_net, + ) + .with_unresolved_net(port.unresolved_net)); + } let signal = declarations .iter() .find(|signal| signal.name() == name) diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index da526c4c675..9e9f0c423b8 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -229,7 +229,7 @@ pub(super) fn analyze_module( } else { format!("{}${ordinal}", port.name) }; - let interface = + let mut interface = timescales::with_interface_instance(&tree.state.timescales, handle, || { interface_ast::analyze( &tree.child(definition_tree, &values), @@ -241,6 +241,18 @@ pub(super) fn analyze_module( imported.declarations_only, ) })?; + // Header ports are members of the interface view, just like body signals. + for port in &interface.ports { + interface.symbols.as_mut().unwrap().signals.push(Signal { + name: port.name.clone(), + r#type: port.r#type.clone(), + is_net: port.is_net, + unresolved_net: port.unresolved_net, + is_const: false, + package_variable: None, + hierarchical: None, + }); + } let symbols = interface.symbols.as_ref().unwrap(); let names = binding_names_with_prefix( &interface, diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 4750eb0768f..94323863aaf 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -685,6 +685,7 @@ struct InterfaceDecl { parameter_order: Vec, items: Vec, members: Vec, + has_ports: bool, functions: Vec, modports: HashMap>, /// The names declared in the interface scope. @@ -2401,11 +2402,6 @@ impl InterfaceDecl { let unit = tree.root_unit()?; let native = tree.declarations(); let interface_name = native_name(&unit.name); - if !unit.ports.is_empty() { - return Err(unsupported(format!( - "ports of interface `{interface_name}`" - ))); - } if native.types.iter().any(|ty| { unit.tokens.start <= ty.tokens.start && ty.tokens.end <= unit.tokens.end @@ -2430,12 +2426,33 @@ impl InterfaceDecl { parameter_order: Vec::new(), items: Vec::new(), members: Vec::new(), + has_ports: !unit.ports.is_empty(), functions: Vec::new(), modports: HashMap::default(), names: HashSet::default(), references: Vec::new(), lvalues: HashSet::default(), }; + for port in &unit.ports { + let native::PortKind::Named(name) = &port.kind else { + return Err(unsupported(format!( + "non-ANSI ports of interface `{interface_name}`" + ))); + }; + interface.add_member(Member { + name: native_name(name), + data_type: port + .data_type + .and_then(|id| file.range_span(native.data_type(id).tokens)), + dimensions: port + .dimensions + .iter() + .map(|dimension| file.span(dimension.tokens)) + .collect::>()?, + // A port default is not a variable initializer. + initializer: None, + })?; + } for id in &unit.package_bindings { let binding = native.package_binding(*id); if unit.header.start <= binding.tokens.start && binding.tokens.end <= unit.header.end { @@ -3366,7 +3383,9 @@ pub fn plan_interfaces_with_member_paths( .copied() .unwrap_or(module.span); for instance in &instantiation.instances { - check_no_connections(instance, &interface)?; + if !design.interfaces[&interface].has_ports { + check_no_connections(instance, &interface)?; + } let handle = native_name(&instance.name); handles.insert( handle, 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-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 7c5873c72d4..52819c1c8c9 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -4819,10 +4819,6 @@ fn rejects_unsupported_interface_uses() { ); } for (interface, message) in [ - ( - "interface I(input logic clk); endinterface", - "ports of interface `I`", - ), ( "interface I; enum {Idle, Busy} state; endinterface", "enum type in interface `I`", @@ -7458,3 +7454,16 @@ fn constraint_mode_names_do_not_intercept_struct_members() { analyze_source(source, Path::new("constraint_mode_struct.sv")).unwrap(); } } + +#[test] +fn interface_header_members_preserve_parameter_dependent_types() { + let source = "interface Bus #(parameter W=8)(input logic [W-1:0] data); modport reader(input data); endinterface"; + let signatures = crate::interface_prototypes(&[(source, Path::new("bus.sv"))]).unwrap(); + let port = &signatures[0].module.ports()[0]; + assert_eq!(port.name(), "h$data"); + let values = fxhash::FxHashMap::from_iter([("h$W".to_string(), 12)]); + assert_eq!( + typecheck::eval_const_expr(port.r#type().packed_ranges()[0].left(), &values), + Some(11), + ); +} 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/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index bd95060fcb5..ac5e5aa8526 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -546,7 +546,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_runtime_packed_subselect` | compile | icarus | 3 | Icarus 13.0 rejects a further select after a runtime index into a multidimensional packed array, or after runtime indices into an unpacked array of them (t[k][j], t[k][2:1], u[j][k][i]: "Array index expressions must be constant here"). Verilator passes the two-state case; the four-state one is outside what it checks. | | `sv_verilator_multidimensional_interface_connections` | compile | verilator | 1 | Verilator 5.052 validates a 2x2 scalar interface array against a two-bit connection instead of four bits. See the focused interface-array evidence above. | | `sv_icarus_interface_array_connections` | compile | icarus | 3 | Icarus 13.0 rejects distributed unpacked actuals and multidimensional instances, and aborts on interface array ports. See the focused interface-array evidence above. | -| `sv_icarus_interfaces` | compile | icarus | 15 | Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports ("sorry: modport task/function ports are not yet supported") and multidimensional interface instance arrays ("sorry: Multi-dimensional arrays of instances are not yet supported"). Verilator passes these cases. The implicit named interface cases have [focused pre-exclusion evidence](verification/sv/limitations/implicit-interface-ports-icarus.json). The mixed module-contract/local-interface case retains its [port-declaration diagnostics](verification/repros/sv_mixed_interface_connections_icarus.json). | +| `sv_icarus_interfaces` | compile | icarus | 16 | Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports ("sorry: modport task/function ports are not yet supported") and multidimensional interface instance arrays ("sorry: Multi-dimensional arrays of instances are not yet supported"). Verilator passes these cases. The implicit named interface cases have [focused pre-exclusion evidence](verification/sv/limitations/implicit-interface-ports-icarus.json). The mixed module-contract/local-interface case retains its [port-declaration diagnostics](verification/repros/sv_mixed_interface_connections_icarus.json). | | `sv_icarus_packed_inner_index_range` | execute | icarus | 1 | Icarus 13.0 flattens an out-of-range inner index of a multidimensional packed array into the neighbouring element: a read gives a known value instead of X, and a write lands in that element; IEEE 1800-2023 7.4.6 and 11.5.1 make the select out of range. Verilator cannot check four-state values, and it truncates out-of-range packed indices. | | `sv_icarus_string_methods` | compile | icarus | 3 | Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa ("Method getc is not a string method"), and requires a constant replication count for a string ("A reference to a net or variable is not allowed in a constant expression"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases. | | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | 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-test-suite/src/sv/cases/interfaces.vtest b/crates/celox-test-suite/src/sv/cases/interfaces.vtest index 2d80947667f..f8eeefe5b67 100644 --- a/crates/celox-test-suite/src/sv/cases/interfaces.vtest +++ b/crates/celox-test-suite/src/sv/cases/interfaces.vtest @@ -982,3 +982,28 @@ (modify (set value value)) (assert_eq descending (+ (* value 2) 0x300 20)) (assert_eq ascending (+ (* value 2) 0xc00 20)))) + +(case forwards_header_ports_through_modports + (source "interface_header_modport.sv" #" + interface Bus #(parameter W=8)(input logic clk, input logic [W-1:0] data, output wire [W-1:0] result); + modport consumer(input clk, data, output result); + endinterface + module Consumer(Bus.consumer b, output logic [7:0] sampled); + assign b.result = b.data ^ 8'h5a; + always @(posedge b.clk) sampled <= b.data; + endmodule + module Relay(Bus.consumer b, output wire [7:0] sampled); + Consumer child(b, sampled); + endmodule + module Top(input logic clk, input logic [7:0] data, + output wire [7:0] result, sampled); + Bus #(.W(8)) bus(.clk(clk), .data(data), .result(result)); + Relay relay(bus, sampled); + endmodule + "#) + (top Top) + (for value (list 0 23 255) + (modify (set clk 0) (set data value)) + (assert_eq result (^ value 0x5a)) + (tick clk 1) + (assert_eq sampled value))) diff --git a/crates/celox-test-suite/verification/repros/sv_header_modport_icarus.json b/crates/celox-test-suite/verification/repros/sv_header_modport_icarus.json new file mode 100644 index 00000000000..1ec2742d29d --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_header_modport_icarus.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: Errors in port declarations.\n/source_0.sv:9: syntax error\n/source_0.sv:9: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "interfaces::forwards_header_ports_through_modports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/sv/icarus/interfaces.json b/crates/celox-test-suite/verification/sv/icarus/interfaces.json index 5ed546a6a29..36b48e841cd 100644 --- a/crates/celox-test-suite/verification/sv/icarus/interfaces.json +++ b/crates/celox-test-suite/verification/sv/icarus/interfaces.json @@ -11,6 +11,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -37,6 +38,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -63,6 +65,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -89,6 +92,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -115,6 +119,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -141,6 +146,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -167,6 +173,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -204,6 +211,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -230,6 +238,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -256,6 +265,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -282,6 +292,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -317,6 +328,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -426,6 +438,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -452,6 +465,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -547,6 +561,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -561,6 +576,33 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "name": "interfaces::forwards_header_ports_through_modports", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", + "verification/sv/limitations/implicit-interface-ports-icarus.json", + "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 7de2f2a253b..5e0c87de2d0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -722,6 +722,7 @@ "verification/sv/limitations/interface-array-ports-icarus.json", "verification/sv/limitations/implicit-interface-ports-icarus.json", "verification/repros/sv_mixed_interface_connections_icarus.json", + "verification/repros/sv_header_modport_icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { @@ -735,6 +736,7 @@ "interfaces::clocks_interface_processes_from_member_clocks", "interfaces::drives_members_through_child_outputs_and_array_generate_regions", "interfaces::elaborates_net_members_typedefs_and_localparams", + "interfaces::forwards_header_ports_through_modports", "interfaces::infers_directions_of_ports_without_modport", "interfaces::mixes_module_contracts_with_local_interface_connections", "interfaces::overrides_body_parameters_and_drives_members_from_imported_functions", 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/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index 984d742005a..95b6d6fc64e 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -1,6 +1,9 @@ use super::*; sv_backends! { + fn forwards_header_ports_through_modports(sim) { + @case "interfaces::forwards_header_ports_through_modports"; + } fn defers_interface_dependent_declarations_before_binding_array_ports(sim) { @case "interfaces::defers_interface_dependent_declarations_before_binding_array_ports"; } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8efcd2f127b..6be75009799 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 @@ -345,7 +345,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: Interfaces are supported within the limits below: -- **Declarations:** ports on an interface, tasks, implicit nets, +- **Declarations:** ANSI header ports can be passed through module interface + ports and modports, including clock inputs and parameter-dependent widths. + Tasks, implicit nets, enums and module instances inside an interface, and virtual interfaces are unsupported. Macros and compiler directives inside an interface are also unsupported. - **Modports and connections:** `inout`, `ref`, expression ports, `export` and @@ -445,7 +447,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 +470,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 +488,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 diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index d6968d5875f..f7be4d744d3 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -187,7 +187,8 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 - [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、宣言した package やコンパイル単位の外でのパラメータ付きクラスの特殊化、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 -- interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 +- `inout` / `ref` / 式を使う modport、virtual interface など。 + ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 - 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、